Search This Blog

Thursday, January 2, 2014

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

Friday, November 22, 2013

netTcp binding in WCF service hosted in IIS server

WCF nettcp binding with IIS.
Required config
1 Enable  TcpPortSharing from add and remove feature .net advance features of .net 4.5
2 enable tcp communication from services.

use the following config for WCF service

<system.serviceModel>
    <services>
      <service behaviorConfiguration="SampleCalculatorServiceTcpBehavior"
        name="WcfServiceTcpBinding.CalculatorService">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration="portSharingBinding"
          name="SampleCalculatorServiceTcpEndPoint" contract="WcfServiceTcpBinding.ICalculatorService" >
          <identity>
            <dns value="localhost"/>
          </identity>
       
        </endpoint>
        <endpoint address ="mex" binding="mexTcpBinding" bindingConfiguration="" name="SampleCalculatorServiceMexTcpEndPoint"
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:808/CalculatorService.svc" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <standardEndpoints />
    <behaviors>
      <serviceBehaviors>
        <behavior name="SampleCalculatorServiceTcpBehavior">
          <serviceDebug includeExceptionDetailInFaults="false"/>
          <serviceMetadata httpGetEnabled="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <netTcpBinding>
          <binding name="portSharingBinding" portSharingEnabled="true"/>
      </netTcpBinding>
    </bindings>
    <serviceHostingEnvironment
      multipleSiteBindingsEnabled="true" />
  </system.serviceModel>



Monday, October 14, 2013

Create single instance of windows application

public class CSMain
    {
        private CSMain() { }
        static CSMain()
        {
            mUID = "2c81068a-7828-4769-8112-36754b67cdc5";
        }
        [STAThread]
        static void Main()
        {
            try
            {
                bool firstInstance;
                mSingleInstanceLock = new Mutex(true, mUID, out firstInstance);
             

                if (firstInstance == true)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new frmLogin());
                }
            }
            catch (Exception ex)
            {
                string err = ex.ToString();
            }
        }
        private static string mUID;
        private static Mutex mSingleInstanceLock;
    }

Find the idle time of windows application

Find how much time application idle in windows application


 public partial class Form1 : Form,IMessageFilter
    {
        Timer timer;
        private DateTime _wentIdle;
        private int _idleTicks;

        public Form1()
        {
            InitializeComponent();
            Application.AddMessageFilter(this);
            timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            TimeSpan diff = DateTime.Now - _wentIdle;
            if (diff.TotalSeconds >= Settings.Default.IdleTimeout_Sec)
            {
                label1.Text = "Idle From - " + _wentIdle;
            }
            if (++_idleTicks >= Settings.Default.IdleTimeout_Sec)
            {
                label1.Text = "Idle From - " + _idleTicks;
            }
            if (_idleTicks > 100)
            { Application.Exit(); }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
           
            Application.Idle += Application_Idle;
        }

        void Application_Idle(object sender, EventArgs e)
        {
            _wentIdle = DateTime.Now;
        }
        public bool PreFilterMessage(ref Message m)
        {
            if (isUserInput(m))
            {
                _wentIdle = DateTime.MaxValue;
                _idleTicks = 0;

                label1.Text = "We Are NOT idle!";
            }

            return false;
        }
        private bool isUserInput(Message m)
        {
            if (m.Msg == 0x200) { return true; }
            if (m.Msg == 0x020A) { return true; }
            if (m.Msg == 0x100) { return true; }
            if (m.Msg == 0x101) { return true; }
            return false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.Show();
        }
    }

Using statement to connect to database

use using keyword to connect to database.

using System.Data;
using System.Data.SqlClient;
String conString = "Data Source=SERVER;UID=user;PWD=passsword Integrated Security=True;";

using (SqlConnection sqlCon = new SqlConnection (conString))
   {
   sqlCon.Open();
   DataTable tblDatabases = sqlCon.GetSchema ("Databases");
   sqlCon.Close();

   foreach (DataRow row in tblDatabases.Rows)
   {
      Console.WriteLine ("Database: " + row["database_name"]);
   }
}

Tuesday, August 13, 2013

Encryption and Decryption in c#.net

using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;

namespace Encription
{
    class CryptorEngine
    {
        public static string Encrypt(string ToEncrypt, bool useHasing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);
            //System.Configuration.AppSettingsReader settingsReader = new     AppSettingsReader();
           string Key = "Bhagwati";
            if (useHasing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            }
            TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
            tDes.Key = keyArray;
            tDes.Mode = CipherMode.ECB;
            tDes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tDes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,     toEncryptArray.Length);
            tDes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        public static string Decrypt(string cypherString, bool useHasing)
        {
            byte[] keyArray;
            byte[] toDecryptArray = Convert.FromBase64String(cypherString);
            //byte[] toEncryptArray = Convert.FromBase64String(cypherString);
            //System.Configuration.AppSettingsReader settingReader = new     AppSettingsReader();
            string key = "Bhagwati";
            if (useHasing)
            {
                MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
                keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }
            TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
            tDes.Key = keyArray;
            tDes.Mode = CipherMode.ECB;
            tDes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tDes.CreateDecryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0,         toDecryptArray.Length);

                tDes.Clear();
                return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);
            }
            catch (Exception ex)
            {
                throw ex;
             }
        }
    }
}

Indexer in C#.net

Indexer in c#, Indexers allow instances of a class or struct to be indexed just like arrays. for creating indexer we need to inherit System.Collection.CollectionBase.

example-

public class EmployeeCollection:System.Collection.CollectionBase
{
        //adding class to indexer
        public void Add(Employee obEmployee)
        {
                this.InnerList.aAdd(obEmployee);
        }
        //get the data
        public Employee this[int i]
        {
                get
                {
                        return
                                {
                                        this.InnerList[i] as Employee;
                                }
                }
        }
}

for add data into collection create object of collection and call add method. For get data collection[index].

Thursday, October 18, 2012

Upload Large Image Using WCF Services Using RESTFul WCF Services

How to upload large image in WCF service?
By default WCF service allow 64KB data to upload if you want to upload more data then 64K you need to change the configuration settings, need to change the buffer size for incoming and outgoing request size here is an example for upload large image through WCF service,

In IService Interface, declare method.

here Method is POST and we are using stream to upload a image.

[OperationContract]
[WebInvoke(Method = "POST",UriTemplate = "/File")]
bool UploadImage(Stream obStream);

In Service implement interface method.

public bool UploadImage(Stream image)
{

 
if(image != null)
{ 
try
{

string ImageName = DateTime.Now.ToString().Replace(" ","").Replace(":","").Replace("/","") + ".jpeg";//define name of image.

if(!Directory.Exists(@"C:\Images"))//check folder exist or not.
Directory.CreateDirectory(@"C:\Images");
string strFilePath = @"C:\Images\" + ImageName;
FileStream targetStream = null;
Stream sourceStream = image;
string uploadFolder = @"C:\Images\";
string filename = ImageName;

string filePath = Path.Combine(uploadFolder,filename);
///write file using stream.
using(targetStream = new FileStream(filePath,FileMode.Create,FileAccess.Write,FileShare.None))
{

const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
int totalBytes = 0;
while((count = sourceStream.Read(buffer,0,bufferLen)) > 0)
{

totalBytes+=count;

Debug.WriteLine("Bytes Count="+totalBytes.ToString());
targetStream.Write(buffer,0,count);

}

targetStream.Close();

sourceStream.Close();

}

return true;
}

catch(Exception ex)
{

return false;
}

}

return false;
}

private byte[] StreamToByte(Stream stream)
{

   
byte[] buffer = new byte[16 * 1024];
    using(MemoryStream ms = new MemoryStream())
    {

    
int read;

     while((read = stream.Read(buffer,0,buffer.Length)) > 0)
     {

       ms.Write(buffer,0,read);

     }

return ms.ToArray();

}

}



and in Configration use webHttpbinding change the maxReceivedMessageSize.

<webHttpBinding>
<binding name="webHttpBindingStreamed" transferMode="StreamedRequest" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>

the max length for Receive buffer is 2147483647, also add the readerQuotas.
may be this will help you.

Friday, April 6, 2012

Extension Methods in c#

You want to improve the syntax for calling common methods in your C# program, so that function names are shorter and easier to type. Extension methods provide a way to easily represent static methods as instance methods in the syntax of the C# language, which can be more intuitive and recallable for developers.

Here is an example.

using System;
public static class ExtensionMethods
{
    public static string GetFirstThreeLatters(this string value)
    {

  if (value.Length > 0)
 {
        value=value.Substring(0,3);

}
 return value;
    }
}

class Program
{
    static void Main()
    {
 string value = "dot net perls";
 value = value.GetFirstThreeLatters(); // Called like an instance method.
 Console.WriteLine(value);
    }
}

OUTPUT:-

dot.


Description. In the first part of the program text, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code.
The extension method is called like an instance method, but is actually a static method. The instance pointer 'this' is received as a parameter. You must specify the 'this' keyword before the appropriate parameter you want the method to be called upon. In the method, you can refer to this parameter by its declared name.
This-keyword in parameter list. The only difference in the declaration between a regular static method and an extension method is the 'this' keyword in the parameter list. If you want the extension method to received other parameters as well, you can place those in the method signature's parameter list after the 'this' parameter.