Search This Blog

Tuesday, January 7, 2014

Sample Applicaion in WCF

Windows Communication Foundation is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML or send as JSON. A few sample scenarios include:
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.
While creating such applications was possible prior to the existence of WCF, WCF makes the development of endpoints easier than ever. In summary, WCF is designed to manege Web services and Web service clients.


Steps to create WCF Service with IIS host in visual studio
  1. Open visual studio(run as administrator), click on file ->website
  2. Select Wcf service template. provide the name of service below, I created as http://localhost/FirstWcf then click ok.
  3. Visual studio will generate a solution in that solution you will get the service.svc file.
  4. in App_Code it will generate one Interface IService.cs and one class Service.cs which inherits IService.
  5. your services created press f5 to run the application.

Monday, January 6, 2014

LINQ Query on DataSet

If we want to filter some data from dataset we can use LINQ query to dataset.

here is code snippet.

var  Employees= from Employees in ds.Tables["Employee"].AsEnumerable()
                                        where Employees.Field<int>("Empid") == Convert.ToInt32(empid)
                                        select Employees;

//Here empid is variable from which we are comparing the employee dataset.


Output Sql Parameter in C#

output parameter is used to get the value from store procedure, if you want to return any value from store procedure then we are using output parameter.
to use output parameter we need to define the direction of the parameter to output.
example the simple example of output parameter is when we are registering any user after registration return the userid and login user into our website.

here is code snippet to change the direction of sqlparameter.

SqlParameter sqlParameter = new SqlParameter(_parameterName, _parameterValue);
sqlParameter.Direction = ParameterDirection.Output;

//then attach parameter to our command object.

String outParameter = Convert.ToString(sqlCommand.Parameters[outParameter].Value);

//here outParameter is the output parameter of store procedure.


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);