RSS

Tag Archives: c#

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: , , , ,