Search This Blog

Friday, January 3, 2014

action and func delegate

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value.

Example for Action and Func:

class Program
{
    static void Main(string[] args)
    {
        Action<int,int> testAction = new Action<int,int>(Add);
        testAction.Invoke(123,234);           

        Func<int,int, double> testFunc = new Func<int,int, double>(Multiply);
        Console.WriteLine(testFunc(5,6));   
    }

    static void Add(int i,int j)
    {
        Console.WriteLine(i+j);
    }

    static double Multiply(int i,int j)
    {
        return (double)i*j;
    }
}
 

Create a snippet in visual studio




To create snippet  add a xml file into project and the add the following code.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>Insert</Title>
    <Author>Bhagwati</Author>
    <Shortcut>insert</Shortcut>
    <Description>description</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>conStraing</ID>
        <Default>YouConnectionString</Default>
        <ToolTip>Connection String</ToolTip>
      </Literal>
      <Literal>
        <ID>sqlCommand</ID>
        <Default>Query</Default>
        <ToolTip>YourQuery</ToolTip>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[SqlConnection con=null;
      SqlCommand cmd=null;
      try
      {
        con=new SqlConnection($conStraing$);
        con.Open();
        cmd=new SqlCommand($sqlCommand$,con);
        cmd.ExecuteNonQuery();
      }
      catch(Exception ex)
      {
     
      }
      finally
      {
        if(con.State!=ConnectionState.Close)
        {
          con.close();
        }
      }
      ]]>
    </Code>
  </Snippet>
</CodeSnippet>

Change the file extension .xml to .snippet.
Then we need to register this snippet file into snippet manager, for that open snippet manager in tool menu, then click on import select your file that’s done.

Get the Universal/Global Path/ Get the network path

This Class is used to fine the global path on network.
here is the code

class Pathing
    {
        [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int WNetGetConnection(
            [MarshalAs(UnmanagedType.LPTStr)] string localName,
            [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
            ref int length);
        /// <summary>
        /// Given a path, returns the UNC path or the original.
        /// </summary>
        /// <param name="originalPath">The path to convert to a UNC Path</param>
        /// <returns>A UNC path. If a network drive letter is specified, the
        /// drive letter is converted to a UNC or network path. If the
        /// originalPath cannot be converted, it is returned unchanged.</returns>
        public static string GetUNCPath(string originalPath)
        {
            StringBuilder sb = new StringBuilder(512);
            int size = sb.Capacity;

            // look for the {LETTER}: combination ...
            if (originalPath.Length > 2 && originalPath[1] == ':')
            {
                // don't use char.IsLetter here - as that can be misleading
                // the only valid drive letters are a-z && A-Z.
                char c = originalPath[0];
                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
                {
                    int error = WNetGetConnection(originalPath.Substring(0, 2),
                        sb, ref size);
                    if (error == 0)
                    {
                        DirectoryInfo dir = new DirectoryInfo(originalPath);
                        string path = Path.GetFullPath(originalPath)
                            .Substring(Path.GetPathRoot(originalPath).Length);
                        return Path.Combine(sb.ToString().TrimEnd(), path);
                    }
                }
            }

            return originalPath;
        }

        public static string GetUniversalName(string sFilePath)
        {
            if (sFilePath == string.Empty || sFilePath.IndexOf(":") > 1)
                return sFilePath;
            if (sFilePath.StartsWith("\\"))
            {
                return (new Uri(sFilePath)).ToString();
            }
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT RemoteName FROM win32_NetworkConnection WHERE LocalName = '" + sFilePath.Substring(0, 2) + "'");
            foreach (ManagementObject managementObject in searcher.Get())
            {
                string sRemoteName = managementObject["RemoteName"] as string;
                sRemoteName += sFilePath.Substring(2);
                //return (new Uri(sRemoteName)).ToString();
                return sRemoteName;
            }
            return sFilePath;
        }
    }

if you need to do some operation on network then use this class for finding the network path.

Tracing in Application

The easiest  way to trace the application is Add the trace listner in web/app config file.
here is sample code to add trace in application.

<configuration>
  <system.diagnostics>
    <trace autoflush ="true" indentsize="4">
      <listeners>
        <add name ="TestListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="application.log" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>
 
use Trace.Write to write into log file.
it will create a log file in application, trace is the easiest why to track the bug/exception in application.

Thursday, January 2, 2014

Difference between String.Empty and ""?

The difference between string.Empty and "" is very small. String.empty will not create any object while "" will create a new object in the memory for the checking. Hence string.empty is better in memory management.

Example
string s1=String.Empty;
string s2="";

C# Params keyword

Params enables methods to receive variable numbers of parameters. With params, the arguments passed to a method are changed by the compiler to elements in a temporary array. This array is then used in the receiving method.
Example

class Program
{
    static void Main()
    {
 //
 // Call params method with different parameters.
 //
 int sum1 = SumParameters(1);
 int sum2 = SumParameters(1, 2);
 int sum3 = SumParameters(3, 3, 3);
 int sum4 = SumParameters(2, 2, 2, 2);
 
 Console.WriteLine(sum1);
 Console.WriteLine(sum2);
 Console.WriteLine(sum3);
 Console.WriteLine(sum4);
    }

    static int SumParameters(params int[] values)
    {
 
 // Loop through and sum the integers in the array and add to total.
 
 int total = 0;
 foreach (int value in values)
 {
     total += value;
 }
 return total;
    }
}

Split Sentence by string

If you want to split String based on some string pattern use  Regex split method example.

// Here text is input string and pattern is string to split.
String[] sentences = Regex.Split(text, pattern);

?? Operator

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

 // Set y to the value of x if x is NOT null; otherwise, 
 // if x = null, then set y to -1. 
 int y = x ?? -1;

Enable Help In WCF Service

Help will provide the all the input and output parameter information of service method. to enable help in WCF service add following code into web.config.
<endpointBehaviors>
        <behavior name="WebHttpBehavior">
          <webHttp automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"
                   defaultBodyStyle="Bare" helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
After address put "/" then help for information about the method. for example http://localhost:51013/TestService/Service.svc/help

Fault Contract In WCF Service

Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.

By default when we throw any exception from service, it will not reach the client side.
WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.
To use Fault contract Create a class like WCFException.

[DataContract]
public class WCFException
{
        [DataMember]
        public string Title
        { get; set; }
        [DataMember]
        public string Message
        { get; set; }
        [DataMember]
        public string StackTrace
        { get; set; }
}

then add into the service interface

[OperationContract]
[FaultContract(typeof(WCFException))]
int Multiply(int a, int b);


and in last throw fault exception

try
{
    return a * b;
}
catch (Exception ex)
{
    WCFException wcfex = new WCFException();
    wcfex.Title = ex.Source;
    wcfex.Message = ex.Message;
    wcfex.StackTrace = ex.StackTrace;
    throw new FaultException<WCFException>(wcfex);
}