Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, March 3, 2014

C# - Declaring Events

Events are closely related to delegates, but they are not the same thing. An event allows code to subscribe and unsubscribe using delegate instances as event handlers. The idea is that when an event is raised all the event handlers which have subscribed to the event are called. Just as a property is logically just two operations get and set, an event is also logically just two operations: subscribe and unsubscribe.


To declare an event and explicitly write these operations, you use syntax which looks like a property declaration but with add and remove instead of get and set:

Public event EventHandler CustomEvent
{
          Add
          {
                   //Implementation goes here: “Value” variable is the handler being
//subscribed to the event
          }
          Remove
          {
                   //Implementation goes here: “Value” variable is the handler being
//unsubscribed to the event
          }
}

Many events are implemented using a simple variable to store the subscribed handlers.

C# allows these events to be created simply, as field-like events:
          Public event EventHandler SimpleEvent;
This declares both the event and a variable at the same time.
It’s roughly equivalent to this:

            private EventHandler_hiddenField;
public event EventHandler SimpleEvent
{
          add
          {
                   lock(this)
                   {
                             _hiddenField += value;
                             }
                   }
                   remove
                   {
                   lock(this)
                   {
                             _hiddenField -= value;
                             }
                   }
          }

Everywhere you refer to SimpleEvent within the declaring type, the compiler actually reference _hiddenField, which is why you’re able to raise the event by calling SimpleEvent(). Outside the type declaration, however, SimpleEvent only refers to the event. This duality has caused confusion for many developers – you just need to remember that fields and events really are very different things, and field, like events are just the compiler doing some work for you.

C# - String Literals

C# has two kinds of string literals – the regular ones, and verbatim string literals which are of the form @”text”. Regular string literals have to start and end on the same line of source code. A backslash within a string literal is interpreted as an escape sequence as per shown below.

Escape Sequence
Result in string
\’
Single quote (This is usually used in character literals. Character literals use the same escape sequence as string literals.)
\”
Double quote
\\
Backslash
\0
Unicode character 0
(the “null” character used to terminate C-style string)
\a
Alert (Unicode Character 7)
\b
Backspace (Unicode character 8)
\t
Horizontal tab (Unicode character 9)
\n
New line (Unicode Character 10 = 0xa)
\v
Vertical quote (Unicode character 11 = 0xb)
\f
Form feed (Unicode character 12 = 0xc)
\r
Carriage return (Unicode character 13 = 0xd)


Verbatim string literals can span multiple lines (the whitespace is preserved in the string itself), and backslashes are not interpreted as escape sequences. The only pseudo-escape sequence is for double quotes- you need to include the double quotes twice.

Sunday, February 16, 2014

C# - Delegates

What is Delegates?
In a simple language, as we use in C and C++, a pointer which points to the functions. In C# there is no pointer, but delegates are working as a pointer to function.
A delegate is a reference type variable that holds the reference to a method. The reference can be changed at run-time.

Use of Delegates
When we want to use functionality of Events and Call-backs at that time delegates comes to the picture.
Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs.

Declaration of Delegates
Declaration of delegates determines the methods that can be referenced by the delegate.
All methods which are refers to delegate must have same signature as delegate.


          delegate   <return type>   <delegate-name>    <parameter list>
public    delegate       int            MyDelegate         (string s);

Example
 

using System;

delegate int Calc(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 0;
      public static int AddNum(int p, int q)
      {
         num = p + q;
         return num;
      }

      public static int MultNum(int p, int q)
      {
         num = p * q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         //create delegate instances
         Calc c1 = new Calc(AddNum);
         Calc c2 = new Calc(MultNum);
         //calling the methods using the delegate objects
         c1(25,30);
         Console.WriteLine("Value of Num: {0}", getNum());
         c2(5,6);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}


Output:
Value of Num: 55
Value of Num: 30
  



Friday, February 14, 2014

Create Simple Web Service in Visual Studio

STEP 1 : Create a simple Web service

When creating a New Project, under the language of your choice, select "Web" and then change to .NET Framework to your choice and you will get the option to create an ASP.NET WEB Service Application.



I am naming my WEB Service as MyWebService.
 
Now you can see the "Service1.asmx.cs" file and also a "[WebMethod] HelloWorld()" in it.

You can add your methods as I show below.


Service1.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Myservice
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public string CheckOddandEvenMethods(int a)
        {
            string results;
            if (a % 2 == 0)
            {
                return results = a + "_" + "Is a Even Number";
            }
            else
            {
                return results = a + "_" + "Is a odd Number";
            }
        }
    }

}

After add WebMethods of your choice, you can run your Service.

STEP 2 : Create Client Program

To create client program select NewProject and select "Console Application" in "Windows" Tab.




I am naming my client "ClientAccess".
Now you need to add a Service Reference so that you can access your web service.
To add service reference:
  1. In Solution Explorer, right-click the name of the project that you want to add the service to, and then click Add Service Reference.
    The Add Service Reference dialog box appears.
  2. Click Discover.
    All services in the current solution are added to the Service list. If not available then manually add them by clicking Advance Tab.
  3. In the Service list, expand the node for the service that you want to use and select a service contract.
  4. In the Namespace box, enter the namespace that you want to use for the reference.
  5. Click OK to add the reference to the project.
  6. A service client (proxy) is generated, and metadata describing the service is added to the app.config file.
After adding service reference write program to use service.


Program.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

using ClientAccess.Mytestapp; // Here you need to write namespace Name and its WebReference Name //

namespace ClientAccess
{
    class Program
    {
        static void Main(string[] args)
        {
            // To call Webservice Here
            Service1 Myapp = new Service1();
            string Result = Myapp.CheckOddandEvenMethods(10);
            Console.WriteLine(Result2);
            Console.ReadLine();
        }
    }
} 

Finally Build Project and Run the Project.
Now you can publish your WebApplication in IIS.

For any query regarding this page Comment below.

Freemarket.com Marketplace