Pages

Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Thursday, April 18, 2013

Tips: Simplify code for better approach

Developers always concentrated on the problem and try different algorithms. Often the first solution won’t be the best. They think again, be creative, try a different approach. Come up with more ideas and choose from better. The better the algorithm is, the better the solution.

However in this blog post, I'm not going to discuss about algorithms. I will be concentrating on tips which (C#) developer neglect in a hurry to solve problems. Just by following the items one can simplify the code for better understanding and readability.

1.  Never use unused “using” statements within a class/page. Use “Remove and Sort” under “Organize Usings” from the context menu
2.    Pascal Casing (first word capitalized). Use PascalCasing for classes, types, methods and constants
3.    Camel Casing (all but first word capitalized). Use camelCasing for local variables and method arguments
4.    Try to skip underscores (“_”) to separate words
5.    Variables names may follow Hungarian Notation or camel case
Ex:
string firstName;
6.    Method names must follow Pascal Notation
Ex:
public string GetUserFirstName()
       {
              // Some statements...
       }
7.  Class variables or member names should start with an “_”
Ex:
int _familyId;
8.    Always check the negative conditions first to exit the method
Ex:
Old:
            if (!IsPostBack)
       {
           // Some Statements
       }
New:
            if (IsPostBack) return;
       // Some Statements
9.    Never use “this” keyword to identify page controls or properties
10.  Try to reduce the no. of lines of code as well as unused variable declarations
Ex: The method allows us to create a random string using Global unique Identity class (GUID)
Old:
private string generateString()
       {
            string pName;
            Guid fileName = Guid.NewGuid();
            pName = fileName.ToString().Substring(0, 8);
            return pName;
       }
New:
private string generateString()
       {
            return Guid.NewGuid().ToString().Substring(0, 8);
       }
11.  Use implicitly typed local variable declaration (var) only when necessary
Note1: When the class name of an object declaration and initialization is same, we can replace the declaration with var keyword.
Ex:
Old:
BlogBase bb = new BlogBase();
New:
var bb = new BlogBase();

Note2: We need to declare the object with class name only if the initialization of an object is done by the resultant output of a method or function.
Ex:
FamilyMember fm = FamilyMember.SelectByMultipleFields("FamilyID", familyId, "MemberId", memberId); // The method will return an object of type FamilyMember class
12.  Try to reduce if... else... statements either using logical assignment or ternary operator ( ? : )
Ex1: Using logical assignment
Old:
            if (Emailids.Tables.Count == 0)
       {
              lbtnDelete.Visible = false;
       }
       else
       {
              lbtnDelete.Visible = true;
       }
New:
            lbtnDelete.Visible = Emailids.Tables.Count != 0;
Ex2: Using ternary operator
Old:
if (stringMode.Equals("new"))
ViewState.Add("Mode", "new");
else
ViewState.Add("Mode", "ex");
New:
ViewState.Add("Mode", stringMode.Equals("new") ? "new" : "ex");
13.  Use LINQ & lambda expressions whenever necessary
Ex:
Old:
string bColor = "";
for (int i = 0; i < aColor.Length; i++)
bColor = bColor + aColor[i];
New:
string bColor = aColor.Aggregate(bColor, (current, t) => current + t);
14.  We can reduce the delegate creation by skipping the associated event handler Class
Old:
Master.FamilyRefreshed += new EventHandler(MasterFamilyRefreshed);
New:
Master.FamilyRefreshed += MasterFamilyRefreshed;
15.  Use null-coalescing operator (??) whenever necessary
Ex:
int? x = null;
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
16.  Declare local variables as close as possible to the first time they're used
17.  Try to avoid global variables
18.  Never make redundant “toStrings()” calls
Ex:
string code = Request.QueryString["Code"].ToString();
19.  Don’t comment the trivial statements, but strategically write paragraphs if needed in specific sections
20.  Make sure your code is source safer with tools viz. VSS, SVN, TFS, Git etc.,
21.  Never be in a state of “Probably be ok” w.r.t use-case; Test and Verify each use-case
22.  Communicate with team when in doubt
23.  Never reinvent/rewrite the code from scratch. Always check your existing code base from same or different projects, teams and if nothing stands go for Google
24.  An engineer truly becomes a wiser "professional" only after the software been released only then 80% of blood, sweat and tears in maintenance

Feel free to add tips within the comments section below based on your experience.

Wednesday, January 4, 2012

Converting a DataSet to XML node excluding Schema

In this blog post I'm going to explain you on how to return an object of type "DataSet" from a web service (SOAP) method.
 
In general when we return any type from a web method, it returns XML formatted string which then need to be parsed to get the resultant output. Whether it is a simple or any complex object type like Collections or generic list


However, when we returning a DataSet the resultant output will include table data along with the Schema.

So, if we need data with schema then it is well & good. 
What can we do to get only data and eliminate the schema from the DataSet?

The following code explains how we can achieve this:

DataSet ds = //... Use your logic to get DataSet from some DB/source
string xmlContent = ds.GetXml(); 
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlContent);
System.Xml.XmlNode newNode = doc.DocumentElement;
return newNode;

GetXml method will return all the xml code in string variable for the corresponding DataSet (including schema).
Creating an XmlDocument object and load the Xml string using LoadXml method
Then we need to return DocumentElement of XmlDocument class to get only data excluding schema.

There is another technique to do the same with less effort, using Linq. Although, I never tried this to confirm..
//// When Using LINQ
//XElement newNode = XDocument.Parse(xmlContent).Root;

Try this and let me know if there are any other ways...

Monday, May 16, 2011

Optimized way to check if a dataset has any value

Working with datasets and we should make sure that object contains some data within.
Here is the optimized way to check if a dataset has any data within by using advanced .Net concepts like extension methods and Linq.

public static bool IsEmpty(this DataSet dataSet)
{
return dataSet == null || !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
}

And we can use this extension method as follows:

DataSet dset = ... // Populate dataset by business method or logic
if (!dset.IsEmpty())
{
   ...
}

Extension methods provide a simple mechanism to extend types in the system (value, reference, and interface types) with new methods. These methods extend the original type and can be called like regular, defined instance methods, but they leave the original type and its methods untouched. Extension methods create the illusion that they are defined on a real type, but, in reality, no changes are made to the original types.

.NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language.