RSS

Tag Archives: asp.net

Linq, Anonymous Functions, Delegates, Events

Given the following:

class MyObj { 
  private String _Name;
  public String Name {
    get { return _Name; }
    set { _Name = value; } 
  }
  public MyObj(String s) { _Name = s; }
}
(..)
List list = new List();
list.Add(new MyObj("dog"));
list.Add(new MyObj("cat"));
list.Add(new MyObj("dolphin"));

Linq

Given a list of objects, filter out some item:

List lFiltered = (
  from x in list
  where (x.Name.Length == 3)
  select x
  ).ToList();

Sort the list (ascending):

list.Sort(delegate(MyObj m1, MyObj m2)
  {
    return m1.Name.CompareTo(m2.Name);
  });

Find an item. The find returns NULL if not found, the first item found otherwise:

MyObj o = list.Find(delegate(MyObj lItem) { return (lItem.Name == "cat"); });
if (o != null) {
  // got it
}

Functions

// Let's find an item using a Func type:
Func f = (item) => item.Name == "dog";
var lx = list.Where(f);

// Define and use an anonymous function (compact):
var ly = list.Where(item => item.Name == "dolphin");

// Another use of the Func type: select all names
Func getName = (x) => x.Name;
var names = list.Select(getName);

Delegates

Restyle our class, with a delegate:

public class MyObj {
  private String _Name;
  public String Name {
    get { return _Name; }
    set { 
      _Name = value;
      if (OnNameChanged != null) OnNameChanged(this);
    } 
  }
  public MyObj(String s) { _Name = s; }
  // the type of the delegate
  public delegate void OnNameChangedDelegate(MyObj sender);
  // the event that uses it
  public static event OnNameChangedDelegate OnNameChanged;
}

Now we can hook our method when a name change:

// the one and only instance
private static MyObj.OnNameChangedDelegate handleNameChanged = new MyObj.OnNameChangedDelegate(writeNameChanged);
// and its handler
private static void writeNameChanged(MyObj x) {
  System.Diagnostics.Debug.WriteLine(x.Name);
}
(..)
MyObj.OnNameChanged -= handleNameChanged; // avoiding multiple instances of handleNameChanged
MyObj.OnNameChanged += handleNameChanged;
(..)
MyObj o = new MyObj("ant");
o.Name = "bee"; // this will raise the event

A Delegate into a Predicate

public class MyObj
{
    public Int32 TheValue = 23;
    (..)
    public static Predicate Match(MyObj x)
    {
        return delegate(MyObj y)
        {
            return y.TheValue == x.TheValue;
        };
    }
}

// generic search with predicate
List _l = new List();
public Int32 IndexOf(Predicate match)
{
    for (int i = 0; i < _l.Count; i++)
    {
        if (match(_l[i])) return i;
    }
    return -1;
}

(..)

// finally somewhere ...
MyObj i = new MyObj();
i.TheValue = 97;
Int32 idx = miaListaDiMyObj.IndexOf(MyObj.Match(i)); 
 
Leave a comment

Posted by on 2014/04/11 in dev

 

Tags: ,

Javascript as C# code

One of the most handy things I created during my daily job as a .NET developer is a system to automagically include my javascript code libraries into every new project I’m going to develop. It’s a sort of javascript dll…no wait IT ACTUALLY IS a .dll file! =)
Here’s the trick…

Preparing the recipe

  • Create a new library (.dll) project … name it “My.Common.Js” (it’s just an example)
  • Include your javascript file (i.e. “myJsFile.js“) into the project
  • Include a folder that contains the minified version of the script (something like “minified/myJsFile.min.js“) into the project
  • Right click on the “myJsFile.min.js” and choose: Build Action “Embedded Resource”

Mix them all

Into the .cs file include the following (at the top, under the “using” block):

[assembly: WebResource("My.Common.Js.minified.myJsFile.min.js", "application/x-javascript")]

Let’s define a class that uses these files:

namespace My.Common
{
    public class JsUtil
(..)

The JsUtil class has one interesting private function that takes the name of a resource and create its phisical file into the given path, including its inclusion (sorry for the joke) into the given page:

private static void dumpResource(Page p, String rezname, String path, String inclPath, Boolean toTheEnd)
{
  String jsns = "My.Common.Js.minified.";
 
  // fix path
  if (!path.EndsWith(@"\")) path += @"\";
  if (!inclPath.EndsWith(@"/")) inclPath += @"/";
  String fout = path + rezname;
  String version = "?ver=1";

  // recreate the file only if needed
  if (!System.IO.File.Exists(fout))
  {
    // read the embedded resource
    String rez = String.Empty;
    System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(typeof(JsUtils));
    Version v = a.GetName().Version;
    version = "?ver=" + v.Build.ToString();
    using (StreamReader sr = new StreamReader(a.GetManifestResourceStream(jsns + rezname)))
    {
      rez = sr.ReadToEnd();
    }

    // write it into a file
    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    try
    {
      using (StreamWriter sw = new StreamWriter(fout))
      {
        sw.Write(rez);
      }
    }
    catch
    {
      // we're racing...let them win
    }
  }

  // include it into the page 
  System.Web.UI.HtmlControls.HtmlGenericControl headctrl = new System.Web.UI.HtmlControls.HtmlGenericControl("script");
  headctrl.Attributes.Add("type", "text/javascript");
  headctrl.Attributes.Add("src", inclPath + rezname + version);
  if (toTheEnd || p.Header.Controls.Count == 0)
    p.Header.Controls.Add(headctrl);
  else
    p.Header.Controls.AddAt(0, headctrl);
}

Ok, now it’s easy. My JsUtil class exposes a very minimal static method:

public static void Include_myJsFile(System.Web.UI.Page page, String jsPath, String inclPath)
{
  dumpResource(page, "myJsFile.min.js", jsPath, inclPath, true);
}

Serve hot

Somewhere in your page:

// filesystem path
String filepath = HttpContext.Current.Server.MapPath("~") + @"\JS\my.common";
// js path
String includepath = @"../JS/my.common"; // js format
// check
if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath);
// include
JsUtils.Include_myJsFile(this, filepath, includepath);
 
Leave a comment

Posted by on 2013/12/27 in dev

 

Tags: , , , ,

Handling jQueryUI modal dialogs inside ASP.NET UpdatePanels

Some time ago I had some problem handling a modal jQueryUI dialog inside an UpdatePanel. When the dialog was closed an
TypeError: $(…).data(…) is null
.data( widgetFullName )._focusTabbable(); jquery-ui.js (line 10343)
error was raised into the FireBug console.

Here’s the the mystery solved, as published in http://forum.jquery.com:

the $.ui.dialog.overlayInstances global variable keeps tracks of every overlay created (maybe from multiple modal dialogs). This variable is initializated during the inclusion of the jqueryui.js file and its initial value is 0.
It’s a global, so you can access it from everywhere.

An opened modal dialog creates an overlay and increments that variable; when you close (or destroy) that dialog the variable will be decremented.

What happens if the dialog is inside an UpdatePanel?
In my test the dialog was built closed (autoOpen=false). Inside the dialog there’s a postback button: it generate a partial reload of the page and only the UpdatePanel will be rendered again.

Some event somewhere calls the .dialog(“open”) and the dialog appears (overlayInstances = 1). Now if we click that postback button, the dialog will be flushed away (not destroyed nor closed!) and the UpdatePanel will be rendered with a new copy of the dialog.
The dialog (again) starts closed but now it will be opened: the .dialog(“open”) is called and overlayInstances++ will be executed.
The $.ui.dialog.overlayInstances isn’t reinitialized, and now its value is (wrongly) 2!.

One final note:
I created another test case: the same page in HTML / javascript, with a postback emulation.
I saw that everything was running clear….until I noticed that I was replacing the UpdatePanel content with a $(“#updatePanel”).html(remoteData).
The .html() funtion is SAFE!! It destroys the inner elements and detach their events. =)
Using a document.getElementById(“updatePanel”).innerHTML = remoteData I saw the overlayInstances problem again.

The fix (updated!) :

I need to keep the balance between “open” and “close” calls to avoid the extra overlay: on every postback button I need to add a js click event that close the dialog. This will forces a _destroyOverlay event that keeps aligned the overlayInstances global value.
Here’s the code:

$('form').on("submit", function () {
  // on EVERY postback the overlay counter will be decremented.
  // if the overlay exists and will be unsafely destroyed (POSTBACK) => ok (because the destructor of the overlay has not been called)
  // if the overlay exists and will be safely destroyed (before POSTBACK) => fails! Please avoid closing dialogs in POSTBACK buttons. It is safe to set the $(settings.popupState).val('0') then postback
  // if the overlay exists and will be safely destroyed (NO POST) => ok (because the "submit" will not be raised)
  // if there's no overlay => it's ok (there's a safeness test on 0)
  if ($.ui.dialog.overlayInstances > 0)
    $.ui.dialog.overlayInstances--; // emulate the dialog closure: very rude, sir
});

This was the old fix...it has some issues:
$('input[type="submit"]', $popup)
  .add('input[type="image"]', $popup)
  .click(function () {
    $popup.dialog('close');
});

If the dialog was opened it is closed before the page load. On page load it will be (re)opened.
If the dialog was closed, it is safe to call an extra close on it.
The dialog is modal, so only inner buttons can raise a postback

 
Leave a comment

Posted by on 2013/08/20 in dev

 

Tags: , , , , ,

ASP.NET Server Side Tags

Source:
http://naspinski.net/post/inline-aspnet-tags-sorting-them-all-out-%283c25242c-3c253d2c-3c252c-3c252c-etc%29.aspx

The most basic inline tag, basically runs normal code

<% ... %>

Used for small chunks of information, usually from objects

<%= ... %>

This tag is identical to the previous except that it auto-html-encodes the value within the tag

<%: ... %>

Used for Binding Expressions; such as Eval and Bind

<%# .. %>

Used for expressions, not code

<%$ ... %>

Example:
<asp:SqlDataSource ID="party" runat="server"  ConnectionString="<%$
ConnectionStrings:letsParty %>" />

This is for directive syntax

<%@ ... %>

This is a server side comment

<%-- ... --%>
 
Leave a comment

Posted by on 2013/03/19 in dev

 

Tags:

Injecting javascript from C#

Sometimes I find handy to inject javascript code from the server side.
I always use a custom method that detects if it is a partial (vs) full page load and uses the appropriate object (ScriptManager vs ClientScriptManager) to register the given script.

Here it is:

public static void RegisterScript(System.Web.UI.Page page, String key, String script, Boolean addTags)
{
  System.Web.UI.ScriptManager sm = System.Web.UI.ScriptManager.GetCurrent(page);
  Boolean isAsyncLoad = (sm != null) && (sm.IsInAsyncPostBack);
  if (isAsyncLoad)
  {
    System.Web.UI.ScriptManager.RegisterClientScriptBlock(page, page.GetType(), key, script , addTags);
  }
  else
  {
    System.Web.UI.ClientScriptManager csi = page.ClientScript;
    csi.RegisterClientScriptBlock(page.GetType(), key, script, addTags);
  }
}

It’s a static method into a JSUtils class; here’s how to use it into a page:

JSUtils.RegisterScript(this, "myscript_key", @"alert('Got it!')", true);
 
Leave a comment

Posted by on 2013/03/14 in dev

 

Tags: , ,

Keepin’ postbacks alive

An ASP.NET page is a big HTML form.
Every item that cause a postback it’s an item that will SUBMIT the form to the server; when using jQuery to handle / style stuff we must remember that the DOM will be probably changed.

To keep the postback alive we have to be sure that our new item(s) will be inside the big form.

Here’s an example that mixes ASP stuff with a jQuery dialog.
Let’s build a dialog popup with a button and a server-side event:

< div id="mypopup" >
    <asp:Button runat="server" ID="btn" Text="clickme" OnClick="btn_OnClick" />
</div>

then style the dialog with some custom option:

$(function () {
  $("#mypopup").dialog({
    modal: true
    , width: 500
    , appendTo: "form" // this will keep the postback "live" on jQueryui >= 1.10.0
    , closeOnEscape: false
    , autoOpen: false
  });
});

…done!
There’s a catch: the “autoOpen: false” will initialize the popup closed. The postback will reload the page (and the popup will be re-initialized closed).
You have to use some trick (i.e. an hidden asp:TextBox) to remember the popup state and, eventually, reopen it.

That’s all, folks

Added:
if you’re using jQueryui < 1.10.0 here's the code:

$(function () {
  $("#mypopup").dialog({
    modal: true
    , width: 500
    , closeOnEscape: false
    , autoOpen: false
  }).parent().detach().appendTo("form"); // this will keep the postback "live" on jQueryui < 1.10.0
});
 
Leave a comment

Posted by on 2013/03/13 in dev

 

Tags: , , ,