Popular Posts

Saturday, October 6, 2012

Overview of WCF


Overview of WCF Service

- Windows Communication Foundation.
- It combines functionalities of Asp.Net Web services, remoting, MSMQ and Enterprise Services.
- It’s more reliable and secured then Web services.
- All the major changes can be done in the configuration file instead of code file.


Differences with Webservices

Hosting
WCF can be hosted on IIS, WAS, of self-hosting.
WS can be hosted on IIS.

Attributes
WCF has [ServiceContract] attribute attached with the class.
WS has [WebService] attribute attached with the class.
WCF has [OperationContract] attribute attached with methods.
WS has [WebMethod] attribute attached with methods.

XML
WCF uses System.Runtime.Serialization namespace for serialization.
WS uses System.Xml.Serialization namespace for serialization.

Encoding
WCF supports XML, MTOM (Messaging Transmission Optimization Mechanizm),Binary.
WS supports XML, MTOM, DIME (Direct Internet Message Encapsulation).

Transports
WCF supports Http, Tcp, Msmq, P2P transport protocols.
WS supports Http protocol.

Security
WCF provides reliable security for messaging and transactions over net.
WS doesn’t provide method level security & message delivery is’t assured & can be lost without acknowledgement.

3 major Points in WCF

Address
WCF service location that client can use to expose its features

Binding
Configuration for Transport protocol, security and encoding mechanism.


Contract
It defines type of data and type of oprtaions, a client application can use from WCF service.

Service Contract in WCF

It has 2 attributes: ServiceContract & OperationContract


Data Contract in WCF

It has 2 attributes: DataContract & DataMember


WCF configurations in config file

It declares information about endpoint name, address, binding and contract.
<system.serviceModel>
    <client>
        <endpoint name = "MyEndpoint"
                  address = "http://localhost:8000/MyService/"
                  binding = "wsHttpBinding"
                  contract = "IMyContract"
        />
    </client>
</system.serviceModel>



WCF proxy

It provides the same operations as that of a Service Contract. There are 2 ways to generate WCF proxies.

In Visual Studio 2008
Right click reference > Add service reference

In Visual Studio - Command Prompt
Using SvcUtil.exe tool 
ex: ScvUtil    http://localhost/MyWCFService/MyService.svc    /out:MyProxy.cs


Fault Contract

It provides the implementation to handle the error raised by WCF
It also propagates the errors to its client applications.

Collection Types Supported by WCF

System.Array
System.Collections.ArrayList
System.Collections.Generics.LinkedList
System.Collections.Generics.List
System.Collections.ObjectModel.Collection
System.ComponentModel.BindingList

Dictionary Collection Types Supported by WCF


System.Collections.Generics.Dictionary
System.Collections.Generics.SortedList
System.Collections.Generics.SortedDictionary
System.Collections.HashTable
System.Collections.ObjectModel.KeyedCollection
System.Collections.SortedList
System.Collections.Specialized.HybridDictionary
System.Collections.Specialized.ListDictionary
System.Collections.Specialized.OrderedDictionary

Collection and Dictionary Collection Types

There are some collection type and Dictionary collection type available in .Net.

Collection Types
System.Array
System.Collections.ArrayList
System.Collections.Generics.LinkedList
System.Collections.Generics.List
System.Collections.ObjectModel.Collection
System.ComponentModel.BindingList


Dictionary Collection Types
System.Collections.Generics.Dictionary
System.Collections.Generics.SortedList
System.Collections.Generics.SortedDictionary
System.Collections.HashTable
System.Collections.ObjectModel.KeyedCollection
System.Collections.SortedList
System.Collections.Specialized.HybridDictionary
System.Collections.Specialized.ListDictionary
System.Collections.Specialized.OrderedDictionary

Friday, September 21, 2012

Arraylist,Hash table,Sorted list and Dictionary C#.Net


In this article we will discuss about Arraylist, Hash table, Sorted list and Dictionary.
Arraylist:
- This is one type of Array whose size can increase and decrease dynamically.
- Arraylist can hold items of different types.
- The base class is System.Collections.ArrrayList.
- An ArrayList uses an array internally and initializes its size with a default value called capacity. As the no of elements increases or decreases , it adjust the capacity of the array by making a new array and copying the old values into it.
ArrayList list = new ArrayList();
To add elements in ArrayList
list.add("Raju");
list.add("biju");

To remove the element from the arraylist
list.Remove("raju");
To remove the element at index 1
list.Remove(1);
To remove three elements starting at index 4
list.RemoveRange(4,3);

Hash table:
- Hash table provides a way of accessing the index using a user identified key value.
- It removes the index problem.
- It stores the items as key value pairs.Each item(value) in the hash table is uniquely identified by its key and its value as an object type.
- Mostly string class is used as the key in hash table but we can also use other class as key.
Hashtable myht = new Hashtable();
myht.Add("one","The");
myht.Add("two","quick");
Here 'two' and 'one' are the keys and 'The' and 'quick' are the values.
PrintKeysAndValues(myht);
To remove elements with the key "two"
myht.Remove("two");

Sorted list:
Simillar to Hash table, the difference is that the values are sorted by keys and acessible by key as well as by index.

SortedList mysl = new SortedList();
mysl.Add("one","The");
mysl.Add("two","quick");

Dictionary:
- A kind of collection that stores items in a key-value pair fashion.
- Each value in the collection is identified by its key.
- All the keys in the collection are unique and there cannot be more than one key with the same name.
- The most common types of dictionary in the system.collection name space are Hash table and the sorted list.

Monday, July 2, 2012

Store Value at Application level in silverlight

we can use isolation level for storing the value at application level similar to session.

Example:

public static void SaveToIsolatedStorage( string fileName, object objectToSave )
{
    using ( IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication() )
    {
        using ( IsolatedStorageFileStream stream = file.OpenFile( fileName, FileMode.Create ) )
        {
            XmlSerializer serializer = new XmlSerializer( objectToSave.GetType() );
            serializer.Serialize( stream, objectToSave );
        }
    }
}
 
public static T LoadFromIsolatedStorage<T>( string fileName ) where T : class
{
    if ( string.IsNullOrEmpty( fileName ) )
    {
        throw new ArgumentNullException( "fileName", "Cannot be null or empty." );
    }
 
    using ( IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication() )
    {
        if ( file.FileExists( fileName ) )
        {
            using ( IsolatedStorageFileStream stream = file.OpenFile( fileName, FileMode.Open ) )
            {
                XmlSerializer serializer = new XmlSerializer( typeof( T ) );
                return serializer.Deserialize( stream ) as T;
            }
        }
 
        return default( T );
    }
}
 
 

Sunday, June 10, 2012

show alert before close the window by javascript


window.onbeforeunload = function (evt) { 
  var showmessage = 'Are you sure you want to leave?'; 
  if (typeof evt == 'undefined') { 
    evt = window.event; 
  } 
  if (evt) { 
    evt.returnValue = showmessage; 
  } 
  return showmessage ; 
}  

Detect the browser by Javascript

by this javascript function we can detect browser .



function BrowserType()
   {
       var brwser;
       var valNavigator = navigator.userAgent.toLowerCase();
       if(valNavigator.indexOf("firefox") > -1)
       {
          brwser="Firefox";
       }
       else if(valNavigator.indexOf("opera") > -1)
       {
          brwser="Opera";
       }
       else if(valNavigator.indexOf("msie") > -1)
       {
          brwser="IE";
       }
       else if(valNavigator.indexOf("safari") > -1)
       {
          brwser="Safari";
      }
}

Wednesday, February 8, 2012

using keyword in C#

                            The most useful advantage of using keyword is that is it calls the Dispose() method automatically to release the resources and also automatically implements the try catch blocks for you.Here it is called a using statement.So the advantage is that we don't have to explicitly write a try-catch block and our code looks small.

Sunday, February 5, 2012

MassageBox in WPF Application with MVVM

Start the visual studio and create a WPF application.

Make a ViewModelBase class and inherite the InotifyPropertyChanged interface.

Create a new method in “ViewModelBase” class for show the message like -

  public void MessageBoxShow(string message)
        {
            MessageBox.Show(message, "", MessageBoxButton.OK, MessageBoxImage.Error);
        }


After create a Helper class in helper folder name is BaseCommand and Inharite/implement the Icommand Interface.

Like-

internal class BaseCommand : ICommand
{
private readonly Action _command;
        private readonly Func<bool> _canExecute;

        public BaseCommand(Action command, Func<bool> canExecute = null)
        {
            if (command == null)
                throw new ArgumentNullException("command");
            _canExecute = canExecute;
            _command = command;
        }

        public void Execute(object parameter)
        {
            _command();
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
                return true;
            return _canExecute();
        }

        public event EventHandler CanExecuteChanged;
    }



After create a class (EmployeViewModel) in ViewModel  folder and inherite the “ViewModelBase” class and add namespace  the Basecommand class.
Like-
using WPF_MVVM_MessageBox.Helper;
Create a private method in “EmployeViewModel” class for save the data and call the MessageBoxShow method.
private void Save()
        {
           
//here code for Save the Data
            MessageBoxShow("Data Save Successfully.");

        }

Create a Icommand  type property in “EmployeViewModel” class and add the Save method for Execute
Like-
public ICommand ClickCommand { get { return new BaseCommand(Save); } }

Finally add the reference of ViewModel directory in XAML window.

Like-

xmlns:me="clr-namespace:WPF_MVVM_MessageBox.ViewModels" Title="Create Employee" Height="400" Width="400"

After create a Window resource in XAML file.

Like-

<Window.Resources>
        <me:EmployeeViewModel x:Key="viewModel" />
</Window.Resources>

Add a button in XAML file.

Like-

<Button Height="50" Width="100"  Content="Click Me" Name="btnnew" Command="{Binding Source={StaticResource viewModel}, Path= ClickCommand}" />

and bind the button command to “ClickCommand” property.
Finally Run the Application and click on button

cheer.






Thursday, January 26, 2012

Download file inASP.Net



 public static void downloadFile(System.Web.UI.Page pg, string filepath)
    {
        pg.Response.AppendHeader("content-disposition", "attachment; filename=" + new FileInfo(filepath).Name);
        pg.Response.ContentType = getContentType(new FileInfo(filepath).Extension);
        pg.Response.WriteFile(filepath);
        pg.Response.End();
    }

Content type:
 public static string getContentType(string Fileext)
    {

        string contenttype = "";
        switch (Fileext)
        {
            case ".xls":
                contenttype = "application/vnd.ms-excel";
                break;
            case ".doc":
                contenttype = "application/msword";
                break;
            case ".ppt":
                contenttype = "application/vnd.ms-powerpoint";
                break;
            case ".pdf":
                contenttype = "application/pdf";
                break;
            case ".jpg":
            case ".jpeg":
                contenttype = "image/jpeg";
                break;
            case ".gif":
                contenttype = "image/gif";
                break;
            case ".ico":
                contenttype = "image/vnd.microsoft.icon";
                break;
            case ".zip":
                contenttype = "application/zip";
                break;
            default: contenttype = "";
                break;
        }
        return contenttype;
    }



calling:

        downloadFile(this.Page, Server.MapPath("~/images/image1.jpg"));

Resizing the Silverlight contents according to screen resolution



private Tuple<int, int> GetScreenResolution()
{
var contents = Application.Current.Host.Content;
bool wasFullScreen = contents.IsFullScreen;

try
{

if (!wasFullScreen)
{
contents.IsFullScreen = true;
}

if (!contents.IsFullScreen)
{
return new Tuple<int, int>(0, 0);
}

int width = (int)Math.Round(contents.ActualWidth);
int height = (int)Math.Round(contents.ActualHeight);

return new Tuple<int, int>(width, height);
}
finally
{
if (contents.IsFullScreen != wasFullScreen)
{
contents.IsFullScreen = wasFullScreen;
}
}


Content position according to your Screen in silverlight


private Tuple<int, int> GetScreenResolution()
{
var contents = Application.Current.Host.Content;
bool wasFullScreen = contents.IsFullScreen;

try
{

if (!wasFullScreen)
{
contents.IsFullScreen = true;
}

if (!contents.IsFullScreen)
{
return new Tuple<int, int>(0, 0);
}

int width = (int)Math.Round(contents.ActualWidth);
int height = (int)Math.Round(contents.ActualHeight);

return new Tuple<int, int>(width, height);
}
finally
{
if (contents.IsFullScreen != wasFullScreen)
{
contents.IsFullScreen = wasFullScreen;
}
}
}

Current Time

<iframe src="http://free.timeanddate.com/clock/i2yc1jom/n176/tlin/fs15/fcf00/ftbu/tt0/tw1" frameborder="0" width="239" height="20"></iframe>

Saturday, January 21, 2012

Load file in the Div

below code is for load file in a Div.

WebClient MyWebClient = new WebClient();

Byte[] PageHTMLBytes;

PageHTMLBytes = MyWebClient.DownloadData("http://abc.html");

UTF8Encoding oUTF8 = new UTF8Encoding();

divName.InnerHtml = oUTF8.GetString(PageHTMLBytes);

Auto scroll the page


string script = "window.scrollTo(0,950);";

ClientScript.RegisterStartupScript(this.GetType(), "scroll", script, true);