C#, Linq

Implementing ToJSON() Extension Method

In my previous post Extension Methods in .net 3.5, I have given basic idea and example of Extension methods.

What is JSON (JavaScript Object Notation)

JSON is a lightweight data-interchange format. It is easy for humans
to read and write. It is easy for machines to parse and generate.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is
    realized as an object, record, struct, dictionary, hash table, keyed
    list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

e.g.

{"StudentID":2,"Name":"Amol","School":"MIT"}

For more details see json.org , JSON in JavaScript and wikipedia

Implementing ToJSON() Extension Method

JavaScriptSerializer class provides Serialize method which Converts an object to a JSON string.

using System.Web.Script.Serialization; 
public static class JSONHelper
{
public static string ToJSON(this object obj)
    {
        JavaScriptSerializer serializerObj = new JavaScriptSerializer();
        return serializerObj.Serialize(obj);
    }
}

Uses

There is no difference between calling an extension method and the methods that are actually defined in a object.

See below example,

List stringList=new List();
        stringList.Add("Amol");
        stringList.Add("Jon");
      string jsonString= stringList.ToJSON();
// ToJSON method will return,
// ["Amol","Jon"]
 
Student studObj = new Student();
        studObj.Name = "Amol";
        studObj.School = "MIT";
        studObj.StudentID = 2;
        string jsonString= studObj.ToJSON();
// ToJSON method will return,
//{"StudentID":2,"Name":"Amol","School":"MIT"}
Javascripts, Linq

Overview: jLinq

jLinq is a Javascript library that lets you write queries against arrays of javascript objects and JSON data.

Syntax and Examples

Syntax for jLinq is much similar to LINQ ,

var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();

Some important commands

  • .startsWith( field?, value ): Check to see if the field starts with the specified value.
    //Some sample queries
    var results = jLinq.from(records)
    .startsWith("firstname", "jo") // first name starting with 'jo'
    .or("ji") // or first name starting with 'ji'
     
    var results = jLinq.from(records)
    //you can use an array of values to check
    .startsWith("firstname", ["a","e","i","o","u"])
    
  • .endsWith( field?, value ) : Check to see if the field starts with the specified value.
  • .contains( field?, value ) : Check to see if the field contains the specified value.
  • .match( field?, regexp ): Check to see if the
    value matches the regular expression. This command will still take case
    sensitivity into account.
  • .empty( field? ): Check to see if the field contains any value.
  • .greater( field?, value ): Check to see if the field is less than the provided value.

If the field is…

– a string, checks if it ends with the value
– an array, checks if the last element matches the value
– else, convert to a string and check returns jLinq Object

For all commands with examples see this.

Retrieve and Display Results

results[index][‘field’] will retrieve values from result object.

Following e.g. will retrieve data and displays in table,

var results = jLinq.from(data.users)
.startsWith("first", "a")
.toTable();
document.write(results);

Creating A Query Command

We can also create our own commands,

jLinq.extend({
    name:"evenValues", //the name of this command i.e. method
    type:"query", //the kind of command this is
    count:0, //how many parameters we expect
    method:function(query) {
        //determine how to evaluate the value being compared
        var compare = query.when({
            "string":function() {
                return query.value.length;
            },
            "array":function() {
                return query.value.length;
            },
            "other":function() {
                return query.helper.getNumericValue(query.value);
            }
        });
        //the actual comparison
        return compare % 2 == 0;
    }
});

E.g using custom command,

//this method is one way to do it
jLinq.from(data.users)
    .less("age", 30)
    .or()
    .evenValues()
    .select();

When you extend a query command , several additional operator prefixed name command are added to jLinq as well. Each of these perform the correct switches when they are used.

//this orEvenValues command is generated automatically
 
jLinq.from(data.users)
    .less("age", 30)
    .orEvenValues()
    .select();
Asp.net, C#, Freebies, Html & CSS, Linq, Regex

8 useful Cheat Sheets for developer

I have found awesome collections of  cheat sheets on internet which gives quick reference guide of various functionality.

Here are some  good cheats links,

C#, Linq

Lambda Expressions

What are Lambda Expressions?

C#  introduced the concept of anonymous methods, which allow code blocks to be written “in-line” where delegate values are expected.

Lambda Expressions provide a more concise, functional syntax for writing anonymous methods.They end up being super useful when writing LINQ query expressions – since they provide a very compact and type-safe way to write functions that can be passed as arguments for subsequent evaluation.

List stringList = GetList();
//filter list whose value starts with "am"
stringList = stringList.Where(name => name.StartsWith("am")).ToList();

e.g. In above example name is parameter name of string record.

C#, Linq

RSS Feed Reader

Now a days RSS feeds are getting popular. Their are many software available in market that reads rss feeds. Here i have wrote a simple rss reader fuction that returns a list  of rss news of items.

 public List ReadXML(String fileName)
    {
        List itemList = null;
        try
        {
            XmlTextReader reader = new XmlTextReader(fileName);
            reader.WhitespaceHandling = WhitespaceHandling.None;
            itemList = new List();
            RssItem objItem = null;
            while (reader.Read())
            {
                bool isStart = reader.NodeType.Equals(XmlNodeType.Element);
                bool isEnd = reader.NodeType.Equals(XmlNodeType.EndElement);

                if (isEnd && reader.Name.Equals("item"))
                    objItem = null;

                else if (isStart && reader.Name.Equals("item"))
                {
                    objItem = new RssItem();
                    itemList.Add(objItem);
                }
                //read rss item tag and add into Hashtable
                else if (isStart && objItem != null)
                {
                    if (reader.Name.Equals("title"))
                    {
                        reader.Read();
                        objItem.Title = reader.Value;
                    }
                    else if (reader.Name.Equals("link"))
                    {
                        reader.Read();
                        objItem.Link = reader.Value;
                    }
                    else if (reader.Name.Equals("description"))
                    {
                        reader.Read();
                        objItem.Description = reader.Value;
                    }
                }
            }
        }
        catch (Exception e) { throw e; }
        return itemList;
    }

or we can use xml to linq also to parse xml,

public List ReadXML(String fileName)
    {
        // Loading from a file, you can also load from a stream
        XDocument response = XDocument.Load(fileName);
        IEnumerable results = from c in response.Descendants("item")
                                       select new RssItem
                                         {
                                             title = (c.Element("title") == null) ? string.Empty : c.Element("title").Value,
                                             link = (c.Element("link") == null) ? string.Empty : c.Element("link").Value,
                                             description = (c.Element("description") == null) ? string.Empty : c.Element("description").Value
                                         };
        return results.ToList();
    }

RssItem Class to store rss items

public class RssItem
{
public string Title {get ;set;}
public string Link {get ;set;}
public string Description {get ;set;}
}
C#, Linq

Extension methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

e.g which add extension method in string data type.

Defination of extension method

public static class test
{
    public static bool EqualWithIgnoreCase(this string str, string str2)
    {
        return (str.ToLower().Equals(str2.ToLower()));
    }
}

Uses:

string name = "Amol";
if (name.EqualWithIgnoreCase("amol"))
{
    //do something
}

(for more info visit: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx)