Rashim's Blog


There is a special data type in .Net which is called string and it is a reference type, isn’t it? Of course it is but it also behaves much like a value type. That means it can directly accept values and does not require creating an instance. Have we ever thought for a single time how could we incorporate such a feature in our own class? Well, if we really need such type of feature we can easily implement it since operator overloading gives us the planetary for these purposes.

Operator overloading is a way to implement user-defined operator to be specified for operations where one or both of the operands are of a user-defined class or struct type. It also consents us to outline how the operators work with our class and struct. There are mainly three types of overload operators called unary, binary, and conversion. But not all operators of each type can be overloaded. According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to our C# class, which can accept any reasonably convertible data type without type casting. And such a kind of class can also be assigned to any convertible object or variable.  By using this operator we can design our class which can take a value as well. Let’s move to the code.

public class StringManipulationHelper
{
private string _value;
private static StringManipulationHelper _stringManipulationHelper;

public StringManipulationHelper()
{
_value = string.Empty;
}

public StringManipulationHelper(string submittedValue)
{
_value = submittedValue;
}

public static implicit operator StringManipulationHelper(string submittedValue)
{
_stringManipulationHelper = new StringManipulationHelper(submittedValue);
return _stringManipulationHelper;
}

public static implicit operator string(StringManipulationHelper objHelper)
{
return objHelper._value;
}
}

Now you can use in any way like this,

StringManipulationHelper helper = null;
or
StringManipulationHelper helper = "This is test";
or
var helper = new StringManipulationHelper();
or
var helper = new StringManipulationHelper("This is a Test");

Easy enough right? But it will help us a lot when we are in need such kinds of features.


As a series of article, this time, I am going to introduce you with Event-based asynchronous communication. I have used here same service operation of IAsyncResult asynchronous operation that I have mentioned earlier. Service implementation and hosting are also same with IAsyncResult asynchronous. So, in this case I will not go to explain service section again as well as will not go for in details all parts as i have discussed it clearly in other two posts. I would suggest you to have a look on the given links first.

To develop a client is just straight forward. Here I have shown you a console app as a client,

public class Program
 {
 static void Main(string[] args)
 {
 var proxy = new MessageServiceProxy("MessageServiceEndpoint");
 proxy.GetMessageCompleted += GetMessageCompleted;
 proxy.GetMessageAsync("HI");
 Console.WriteLine("waiting");
 Console.ReadLine();
 }
 static void GetMessageCompleted(object sender, GetMessageCompletedEventArgs e)
 {
 Console.WriteLine(e.Result.ToString(CultureInfo.InvariantCulture));
 }
 }

And its corresponding configuration has been given below,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.serviceModel>
 <bindings />
 <client>
 <endpoint address="http://localhost/Rashim.Rnd.WCF.Asynchronous.Services/"
 binding="basicHttpBinding" contract="Rashim.Rnd.WCF.Asynchronous.Services.IMessageService"
 name="MessageServiceEndpoint">
 <identity>
 <dns value="ServerCertificate" />
 </identity>
 </endpoint>
 </client>
 </system.serviceModel>
</configuration>

Now the important thing is how we develop our ServiceProxy which in our case is MessageServiceProxy .

public class MessageServiceProxy : ClientBase<IMessageService>, IMessageService
 {
 public event EventHandler<GetMessageCompletedEventArgs> GetMessageCompleted;
 private BeginOperationDelegate _onBeginGetMessage;

private EndOperationDelegate _onEndGetMessage;

private SendOrPostCallback _onGetMessageCompleted;

public MessageServiceProxy()
 {
 }

public MessageServiceProxy(string endpointConfigurationName) :
 base(endpointConfigurationName)
 {
 }

public IAsyncResult BeginGetMessage(string message, AsyncCallback callback, object asyncState)
 {
 return Channel.BeginGetMessage(message, callback, asyncState);
 }

public string EndGetMessage(IAsyncResult result)
 {
 return Channel.EndGetMessage(result);
 }

private IAsyncResult OnBeginGetMessage(object[] inValues, AsyncCallback callback, object asyncState)
 {
 var message = ((string)(inValues[0]));
 return BeginGetMessage(message, callback, asyncState);
 }

private object[] OnEndGetMessage(IAsyncResult result)
 {
 string retVal = Channel.EndGetMessage(result);
 return new object[] {
 retVal};
 }

private void OnGetMessageCompleted(object state)
 {
 if ((GetMessageCompleted != null))
 {
 var e = ((InvokeAsyncCompletedEventArgs)(state));
 GetMessageCompleted(this, new GetMessageCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
 }
 }

public void GetMessageAsync(string message)
 {
 GetMessageAsync(message, null);
 }

private void GetMessageAsync(string message, object userState)
 {
 if ((_onBeginGetMessage == null))
 {
 _onBeginGetMessage = OnBeginGetMessage;
 }
 if ((_onEndGetMessage == null))
 {
 _onEndGetMessage = OnEndGetMessage;
 }
 if ((_onGetMessageCompleted == null))
 {
 _onGetMessageCompleted = OnGetMessageCompleted;
 }
 InvokeAsync(_onBeginGetMessage, new object[] {
 message}, _onEndGetMessage, _onGetMessageCompleted, userState);
 }
 }

Here I have used three delegates namely onBeginGetMessage, onEndGetMessage and onGetMessageCompleted and these three delegates will register when we first call GetMessageAsync() method. onGetMessageCompleted  is a SendOrPostCallback which represents a callback method that we want to execute when a message is to be dispatched to a synchronization context.

Finally the GetMessageCompletedEventArgs,

public class GetMessageCompletedEventArgs : AsyncCompletedEventArgs
 {
 private readonly object[] _results;

public GetMessageCompletedEventArgs(object[] results, Exception exception, bool cancelled, object userState) :
 base(exception, cancelled, userState)
 {
 _results = results;
 }

public string Result
 {
 get
 {
 RaiseExceptionIfNecessary();
 return ((string)(_results[0]));
 }
 }
 }

Download Source code


We are very well-versed that WCF service operations can be implemented asynchronously or synchronously .And the clients can call service operations synchronously or asynchronously since asynchronous service operations can be calling synchronously and vice versa. There are three ways to implement asynchronous operations

As a series of sequence, in this post, I am going to use IAsyncResult asynchronous operation but we should keep in mind that this pattern is no longer recommended for further development. If we know these three mechanisms of asynchronous operation it would be easier for us to architect our large distributed system based on asynchronous service. Before going to our implementation I would recommend you to have a look on APM Model first. I would like to Organize todays article in three steps; Service Implementation, Service Hosting and Client

Service Implementation

In IAsyncResult asynchronous system asynchronous operations require Begin and End methods.


[ServiceContract]
 public interface IMessageService
 {
 [OperationContract(AsyncPattern = true)]
 IAsyncResult BeginGetMessage(string message, AsyncCallback callback, object state);

string EndGetMessage(IAsyncResult asyncResult);
 }

In the service contract, I declare an asynchronous method pair according to the APM. The BeginGetMessage method takes a parameter, a callback object, and a state object, and returns an IAsyncResult while EndGetMessage method takes an IAsyncResult and returns the value. Since the service operation returns IAsyncResult we have to implement it first. And the implementation has been given below,


public class AsyncResult : IAsyncResult,IDisposable
 {
 private AsyncCallback _callback;
 private object _state;
 private ManualResetEvent _manualResetEvent;

public AsyncResult(AsyncCallback callback, object state)
 {
 _callback = callback;
 _state = state;
 _manualResetEvent = new ManualResetEvent(false);
 }

public bool IsCompleted
 {
 get { return _manualResetEvent.WaitOne(0, false); }
 }

public WaitHandle AsyncWaitHandle
 {
 get { return _manualResetEvent; }
 }

public object AsyncState
 {
 get { return _state; }
 }
 public ManualResetEvent AsyncWait
 {
 get { return _manualResetEvent; }

 }
 public bool CompletedSynchronously
 {
 get { return false; }
 }

public void Completed()
 {
 _manualResetEvent.Set();
 if (_callback != null)
 _callback(this);
 }

 public void Dispose()
 {
 _manualResetEvent.Close();
 _manualResetEvent = null;
 _state = null;
 _callback = null;
 }
 }

AsyncResult implements IAsyncResult that has some properties like AsyncCallback, state object and a ManualResetEvent, which handle waiting for asynchronous operation. IsCompleted is used to specify that the operation is completed asynchronously. In the Complete() method ManualResetEvent has been set, which means that the event is signaled now and any other awaiting thread can follow.

Now for our MessageServiceOperation I create MessageAsyncResult which just inherit from AsyncResult to add a Message property.


public class MessageAsyncResult : AsyncResult
 {
 public string Message { get; private set; }
 public MessageAsyncResult(string message, AsyncCallback callback, object state)
 : base(callback, state)
 {
 Message = message;
 }
 }

Now implementing the service operations.


public class MessageService : IMessageService
 {
 public IAsyncResult BeginGetMessage(string message, AsyncCallback callback, object state)
 {
 var replyMessage = string.Format("{0}{1}","Server says :",message);
 var messageAsyncResult = new MessageAsyncResult(replyMessage, callback, state);
 ThreadPool.QueueUserWorkItem(CompleteProcess, messageAsyncResult);

return messageAsyncResult;
 }

private void CompleteProcess(object state)
 {
 var messageAsyncResult = state as MessageAsyncResult;
 messageAsyncResult.Completed();
 }

public string EndGetMessage(IAsyncResult asyncResult)
 {
 var messageAsyncResult = asyncResult as MessageAsyncResult;
 messageAsyncResult.AsyncWait.WaitOne();
 return messageAsyncResult.Message;
 }
 }

In the BeginGetMessage () method I create an instance of MessageAsyncResult by passing appropriate parameters to it then call ThreadPool.QueueUserWorkItem() method to add a method to waiting queue for execution. The method CompleteProcess() will run whenever a thread becomes available and it finally call the Completed() method to release the thread and allow the other operations to execute. In the EndGetMessage () method, I call the WaitOne() method of its ManualResetEvent to wait until the current execution ends then return the Result property.

Service Hosting

This is also very simple. Here I have used a console app which will be used as a server,


class Program
 {
 static void Main(string[] args)
 {
 var svcHost = new ServiceHost(typeof(MessageService));
 Console.WriteLine("Available Endpoints :\n");
 svcHost.Description.Endpoints.ToList().ForEach(endpoints => Console.WriteLine(endpoints.Address.ToString()));
 svcHost.Open();
 Console.ReadLine();
 }
 }

And the configuration for that,


<configuration>
 <system.serviceModel>
 <behaviors>
 <serviceBehaviors>
 <behavior name="">
 <serviceMetadata httpGetEnabled="true" />
 <serviceDebug includeExceptionDetailInFaults="false" />
 </behavior>
 </serviceBehaviors>
 </behaviors>
 <services>
 <service name="Rashim.Rnd.WCF.Asynchronous.Services.MessageService">
 <endpoint address="" binding="basicHttpBinding" contract="Rashim.Rnd.WCF.Asynchronous.Services.IMessageService">
 <identity>
 <dns value="localhost" />
 </identity>
 </endpoint>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
 <host>
 <baseAddresses>
 <add baseAddress="http://localhost/Rashim.Rnd.WCF.Asynchronous.Services/" />
 </baseAddresses>
 </host>
 </service>
 </services>
 </system.serviceModel>
</configuration>

Client

Now how client could consume this service.? Here I have given a simple console app to consume this service,


public class Program
 {
 static void Main(string[] args)
 {
 var channelFactory = new ChannelFactory<IMessageService>("MessageServiceEndpoint");
 var proxy = channelFactory.CreateChannel();
 var message = Console.ReadLine();
 while (message.Equals("exit",StringComparison.CurrentCultureIgnoreCase)==false)
 {
 proxy.BeginGetMessage(message, ClientCallBack, proxy);
 message = Console.ReadLine();
 }
 }

private static void ClientCallBack(IAsyncResult ar)
 {
 var res = ar.AsyncState as IMessageService;
 if (res != null)
 {
 var message = res.EndGetMessage(ar);
 Console.WriteLine(message);
 }
 }
 }

And the configuration file for this is,


<configuration>
 <system.serviceModel>
 <bindings />
 <client>
 <endpoint address="http://localhost/Rashim.Rnd.WCF.Asynchronous.Services/"
 binding="basicHttpBinding" contract="Rashim.Rnd.WCF.Asynchronous.Services.IMessageService"
 name="MessageServiceEndpoint">
 <identity>
 <dns value="ServerCertificate" />
 </identity>
 </endpoint>
 </client>
 </system.serviceModel>
</configuration>

That’s it. Download Source code.


Last couple of months, I was in rush and could not contribute to the community as much as I have been expected, but regularly I have been answering the questions and giving solutions of different technical problems that I have got through e-mail from different know-how guys.  Solving and replying those critical problems engage me 2-3 hours a day and at the same time I have to spend 8-9 hours a day in my office, so it is really tough to allocate time for writing about something new. But, then again, it is all about our part of  life; I would come up writing with new and cutting edge technologies very soon again.

Today I would like to give a solution of a weird problem that I had confronted for deploying SQLite.

”Could not load file or assembly ‘System.Data.SQLite.dll’ or one of its dependencies.”

For solving this issue I had tried a whole variety of ways but had not got my problem solved. What I had done to solve this issue was that I installed   the version sqlite-netFx40-setup-bundle-x86-2010-1.0.89.0 and then copy the System.Data.SQLite.dll to my project folder and refer this dll to my project. It solved the problem in my development PC but when I had gone for deployment I had got another error which is like that,

“Unable to load DLL ‘SQLite.Interop.dll’: The specified module could not be found. (Exception from HRESULT: 0x8007007E)”

It shows that the native interop assembly is required either for x86 or x64 architecture. As  ‘System.Data.SQLite.dll’  is a mixed mode assembly, I suspected it would automatically loads its native code. But I had got no luck really!! The reason behind this is might be that a particular mixed mode assembly is either for x86 or x64 not for both. Anyway I really don’t know what was the exact reason inside for this issue. After trying in many different ways I had come across the solution finally. Here it is.

First we need to install SQLite and in my case I installed it from NuGet gallery.To do that you can follow the steps that have been given below:

Go to the TOOLS->Library Package Manager->Package Manager Console of the Visual studio.

Image 

  Then run the command Install-Package System.Data.SQLite

Image

Now in your project you have got two folders x86 and x64, underneath this folder you will find those SQLite.Interop.dll’. 

Image

Now go to the properties windows of those dlls and set build action is content and Copy to output directory is Copy always.

Image

Like the way you also need to change the property settings for  ‘System.Data.SQLite.dll’.

That’s it. Now build your app. You are ready to deploy and see it is working perfectly in your client machine too.


WebSocket, like as TCP, is a bi-directional, full-duplex communication channel over a single TCP connection but it shortens abundant complications close to bi-directional communication as well as connection management which we typically comprehend while using TCP. WebSocket channels start as normal HTTP channels which then upgraded to WebSocket channels by using handshaking, allowing cooperative TCP communication between client and server.

WCF hosts provision for WebSockets over the standard HTTP ports 80 and 443. The standard HTTP port allows WebSockets to communicate across the web through mediators. WCF introduces two standard bindings to support communication over a WebSocket transport.

  • NetHttpBinding
  • NetHttpsBinding

These bindings are designed for consuming WebSocket services and will perceive whether they are used with a request-reply contract or duplex contract and change their behavior according to it. They will use HTTP/HTTPS for request-reply contracts and WebSockets for duplex contracts. We can override this behavior by using WebSocketTransportUsage setting

  • Always – Enforce to use WebSockets.
  • Never – Stops to use WebSockets.
  • WhenDuplex – This is the default value.

Let’s move into the code to see how we could implement WCF service and clients that will communicate over WebSockets.

Define callback Contract

    public interface INotificationServiceCallback
    {
        [OperationContract(IsOneWay = true)]
        void OnNotificationSend(Notification notification);
    }

Clients will implement this contract through which the service can send messages back to the clients. To have a better understanding how duplex channel works I would recommend you to have a look on this link.

Define the service contract

    [ServiceContract(CallbackContract = typeof(INotificationServiceCallback))]
    public interface INotificationService
    {
        [OperationContract]
        void SendNotification(Notification notification);

        [OperationContract]
        void SubscribeForNotification(List<NotificationType> notificationTypes);

        [OperationContract]
        void UnsubscribeForNotification(List<NotificationType> notificationTypes);
    }

Here INotificationServiceCallback has been specified as the callback contract.

Implement the service contract

    public class NotificationServiceService : INotificationService
    {
        private INotificationServiceCallback Subscriber
        {
            get { return OperationContext.Current.GetCallbackChannel<INotificationServiceCallback>();  }
        }

        public void SendNotification(Notification notification)
        {
            NotificationManager.Instance.SendNotification(notification, Subscriber);
        }

        public void SubscribeForNotification(List<NotificationType> notificationTypes)
        {
            NotificationManager.Instance.AddSubscriber(Subscriber, notificationTypes);
        }

        public void UnsubscribeForNotification(List<NotificationType> notificationTypes)
        {
            NotificationManager.Instance.RemoveSubscriber(Subscriber, notificationTypes);
        }
    }

In the implementation, we retain the callback channel using the OperationContext which has been passed to the NotificationManager and finally NotificationManager does the rest of the Jobs.

Implement Notification Manager

    public class NotificationManager
    {
        private volatile static NotificationManager _notificationManager = null;
        private static readonly object SyncLock = new object();
        private NotificationManager()
        {
            Subscribers = new Dictionary<INotificationServiceCallback, List<NotificationType>>();
            Notifications = new List<Notification>();
        }

        public Dictionary<INotificationServiceCallback, List<NotificationType>> Subscribers { get; private set; }
        public List<Notification> Notifications { get; private set; }
        public static NotificationManager Instance
        {
            get
            {
                lock (SyncLock)
                {
                    if (_notificationManager == null)
                    {
                        lock (SyncLock)
                        {
                            _notificationManager = new NotificationManager();
                        }
                    }
                }
                return _notificationManager;
            }
        }

        public void AddSubscriber(INotificationServiceCallback subscriber, List<NotificationType> notificationType)
        {
            if (!Subscribers.ContainsKey(subscriber))
                Subscribers.Add(subscriber, notificationType);
            else
            {
                var newNotificationType = notificationType.Where(n => Subscribers[subscriber].Any(n1 => n1 != n));
                Subscribers[subscriber].AddRange(newNotificationType);
            }
        }

        public void RemoveSubscriber(INotificationServiceCallback subscriber, List<NotificationType> notificationTypes)
        {
            if (Subscribers.ContainsKey(subscriber))
            {
                notificationTypes.ForEach(notificationType => Subscribers[subscriber].Remove(notificationType));

                if (Subscribers[subscriber].Count < 1)
                    Subscribers.Remove(subscriber);
            }
        }

        public void AddNotification(Notification notification)
        {
            if (!Notifications.Contains(notification))
                Notifications.Add(notification);
        }

        public void RemoveNotification(Notification notification)
        {
            if (Notifications.Contains(notification))
                Notifications.Remove(notification);

        }

        public void SendNotification(Notification notification, INotificationServiceCallback sender)
        {
            foreach (var existingSubscriber in Subscribers)
            {
                if (existingSubscriber.Value.Any(n => n == notification.NotificationType) && existingSubscriber.Key != sender)
                {
                    if (((ICommunicationObject)existingSubscriber.Key).State == CommunicationState.Opened)
                    {
                        existingSubscriber.Key.OnNotificationSend(notification);
                    }
                }
            }
        }
    }

As we see, NotificationManager maintains a dictionary to hold the client list whose have been subscribed for getting the notifications for different notification types. If any client broadcast messages with Notification types, the subscribers who only subscribe to get the notification for these notification types will get these messages. The code is itself self-explanatory. If you go through on the code portion you will easily have an idea about that.

Service configuration

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.web>
     <compilation debug="true" targetFramework="4.5" />
     <httpRuntime targetFramework="4.5" />
  </system.web>
   <system.serviceModel>
        <protocolMapping>
          <add scheme="http" binding="netHttpBinding" />
        </protocolMapping>
        <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <directoryBrowse enabled="true" />
    </system.webServer>
</configuration>

NetHttpBinding has been used for the default endpoints. If you want to acquaint a bit more about the configuration updates, I would suggest having a look on that.

Okay Service Portion has been done. Now, lets move to client portions,

Implement callback contract and Define Client

    class Program : INotificationServiceCallback
    {
        private NotificationServiceClient _notificationServiceClient;
        private InstanceContext _instanceContext;
        private readonly List<NotificationType> _notificationTypes = Enum.GetValues(typeof(NotificationType)).Cast<NotificationType>().ToList();

        public NotificationServiceClient NotificationServiceClient
        {
            get
            {
                return _notificationServiceClient ??
                       (_notificationServiceClient = new NotificationServiceClient(CallbackInstance,
                                                                                   "netHttpBinding_INotificationService"));
            }
        }

        public InstanceContext CallbackInstance
        {
            get { return _instanceContext ?? (_instanceContext = new InstanceContext(this)); }
        }

        static void Main(string[] args)
        {
            var objProgram = new Program();
            Console.WriteLine("Write exit to shut down....\n");
            Console.WriteLine("Wait...Subscribing for notifications\n");
            objProgram.SubscribeForNotification();
            Console.WriteLine("Subscription done...Now you can send notifacation\n");
            var readMsg = Console.ReadLine();

            while (readMsg.ToString(CultureInfo.InvariantCulture).ToLower().Equals("exit") == false)
            {
                objProgram.SendNotification(readMsg);
                Console.WriteLine("Notification has been send......\n");
                readMsg = Console.ReadLine();
            }
            objProgram.UnsubscribeForNotification();
        }

        public void OnNotificationSend(Notification notification)
        {
            Console.WriteLine(string.Format("New Notification Received\n\nMessage :{0}\nTime :{1}\n\n", notification.NotificationMsg, notification.PostingTime));
        }

        private void SubscribeForNotification()
        {
            NotificationServiceClient.SubscribeForNotification(_notificationTypes);
        }

        private void UnsubscribeForNotification()
        {
            NotificationServiceClient.UnsubscribeForNotification(_notificationTypes);
        }

        private void SendNotification(string msg)
        {
            NotificationServiceClient.SendNotification(new Notification()
            {
                NotificationMsg = msg,
                PostingTime = DateTime.Now
            });
        }
    }

The client application has a property of InstanceContext and NotificationServiceClient, also it specifies the implementation of the INotificationServiceCallback interface. When a client subscribes for the notifications to the service, the service will send the notifications to the client using the callback contract specified.

Implement NotificationServiceClient

    public class NotificationServiceClient : DuplexClientBase<INotificationService>, INotificationService
    {
        public NotificationServiceClient(InstanceContext callbackInstance) :
            base(callbackInstance)
        {
        }

        public NotificationServiceClient(InstanceContext callbackInstance, string endpointConfigurationName) :
            base(callbackInstance, endpointConfigurationName)
        {
        }

        public void SendNotification(Notification notification)
        {
            Channel.SendNotification(notification);
        }

        public void SubscribeForNotification(List<NotificationType> notificationTypes)
        {
            Channel.SubscribeForNotification(notificationTypes);
        }

        public void UnsubscribeForNotification(List<NotificationType> notificationTypes)
        {
            Channel.UnsubscribeForNotification(notificationTypes);
        }
    }

Client Configuration

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <netHttpBinding>
        <binding name="NetHttpBinding_INotificationService">
          <webSocketSettings transportUsage="Always" />
        </binding>
      </netHttpBinding>
    </bindings>
    <client>
      <endpoint address="ws://localhost/websocket/NotificationService.svc"
          binding="netHttpBinding"
          contract="Rashim.RND.WCF.WebSockect.Interfaces.INotificationService"
             bindingConfiguration="NetHttpBinding_INotificationService"
          name="netHttpBinding_INotificationService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>

This is as usual and not any special, what you need to do in the client configuration is to specify the client side endpoint using the NetHttpBinding.

Finally DataContracts

    [DataContract]
    public class Notification
    {
        [DataMember]
        public string NotificationMsg { get; set; }
        [DataMember]
        public DateTime PostingTime { get; set; }
        [DataMember]
        public NotificationType NotificationType { get; set; }
    }
    [DataContract]
    public enum NotificationType
    {
        [EnumMember]
        General,
        [EnumMember]
        Greetings
    }

Using Source code

You need to host the Rashim.RND.WCF.WebSockect.Services in IIS8 and then put the appropriate endpoint address to the client configuration file. After completing the Service hosting, you need to run the two instances of Rashim.RND.WCF.WebSockect.Clients then you can send message from instance to another one just like the given figure below.

WebSocketDemo
 References: 

Download SourceCode.

 

Sometimes client applications need to retrieve different types of file (.doc, .xls, .zip…etc.) from web application to do some of their internal works or even just for the users. So, if we could make such web application which provides the facility to the client applications to download different files from the server, we don’t need to change or modify the code of the web application each time we upload the different types of file to the server.

This can be easily achieved by using an HTTP Handler for download operation. We can use normal asp.net web page for this purposes, but the reason behind to choose an HTTP Handler is only for performance issues. Firstly, we get benefit of scalability as we don’t need to show any output value to the page. Secondly, an HTTP handler doesn’t go through the full page events which ultimately improve performance.

The handler code has given below which is self-descriptive and requires no more description,

public class Download : IHttpHandler
{
 public bool IsReusable
 {
    get
    {
     return false;
    }
 }

 public void ProcessRequest(HttpContext context)
 {
    var request = context.Request;
    Stream stream = null;
    var buffer = new byte[2048];
    var fileName = request["FileName"];

    if (string.IsNullOrEmpty(fileName))
       throw new Exception("File name is Empty");

    var fullFileName = Path.Combine(string.Format("{0}", request.PhysicalApplicationPath), "DownloadFiles",fileName);
    try
    {
       stream = new FileStream(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
       var dataToRead = stream.Length;
       while (dataToRead > 0)
       {
          if (context.Response.IsClientConnected)
          {
             var length = stream.Read(buffer, 0, 2048);
             context.Response.OutputStream.Write(buffer, 0, length);
             context.Response.Flush();
             buffer = new byte[2048];
             dataToRead = dataToRead - length;
          }
          else
          {
             dataToRead = -1;
          }
       }
    }
    catch (Exception ex)
    {
       context.Response.Write(ex);
    }
    finally
    {
       if (stream != null)
       {
          stream.Close();
       }
    }
  }
}

The client applications need to send a request to the download handler appending the Filename variable in the QueryString. This is also a laid-back substance. I am giving a sample code for that,

 var fileName = string.Format("{0}","Install.zip");
 var queryString = string.Format("{0}{1}{2}", "FileName", "=", fileName);
 var downloadUrl = URL of Download.ashx;
 var url = string.Format("{0}{1}{2}", downloadUrl,"?", queryString);
 var downBuffer = new byte[2048];

 var webRequest = (HttpWebRequest)WebRequest.Create(url);
 webRequest.KeepAlive = false;
 webRequest.UnsafeAuthenticatedConnectionSharing = true;
 webRequest.Credentials = CredentialCache.DefaultCredentials;
 var webResponse = (HttpWebResponse)webRequest.GetResponse();
 var streamResponse = webResponse.GetResponseStream();
 var fileStream = new FileStream(string.Format("{0}{1}", "D:\\", fileName), FileMode.Create, FileAccess.Write);

 if (streamResponse != null)
 {
     int bytesRead;
     while ((bytesRead = streamResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
     {
         fileStream.Write(downBuffer, 0, bytesRead);
     }
 }

 fileStream.Close();

Here, I host the web application to the local IIS and the URL for download handler is ‘…/Download.ashx’. WebRequest is for making a request to a URI and HttpWebRequest offers an HTTP specific operation of WebRequest where HttpWebResponse delivers a response from a URI.

Download SourceCode


Generally, I don’t write about anything else except the technical stuffs until unless I am impressed with, which has a factual value on our work or livelihood. This time I am going to write the things which really fascinated me more and hence can’t resist myself without sharing.

We, all, distinguish that Individuals in a corporate (here I especially mean software company), who want to make their career path in a different angle, always try to be inventive, creative and self-motivated. To know the easiest and effective way of achieving these qualities, sometimes we study huge books, articles and blogs as well as attend to the seminar which is in a sense good and certainly it also makes a good impact on us. But is this the only or right way to be innovative or is this the good pathway to make a vision for mission?

Well, company culture also plays the vital role for the novelty. A great software company culture, which has proper mentors to guide us in the right direction as well as has a good learning environment from which we can easily learn a lot not only our technical stuffs but also the things that we need in our daily lives, can give us the space to share and put our ideas without any hesitation whatever the ideas are. Think of this way, we usually spend almost 8-9 hours a day in our office, and if the office structure is not well enough, we might not feel comfort to work or to stay there for a longer period of time. And if the people, we are working with, are not matured and logical enough how do we expect good ideas from them or share our views to them. In fact, those types of people (who are not matured and logical enough) do not have such personality to provide values of our thoughts as well as concepts, besides they can put us in frustration over our capabilities. If we continue with such folks, over the period of time we might go to dust. At the same time, if we are very much engaged with our work without involving in other fun activities (playing tournament, treats, gossiping…), we might be bored at work, and in this situation, we should never presume that our brain will deliver good things. So, I think in a good custom software company, there must have a well decorated office related to the work, way of entertainment, good mentors and cool environment to learn and to teach so that we, all, one day shall be good assets for us and for the company as well which eventually leads to increase the productivity.

Fortunately, I have got the opportunity and have been working in such a cool and attractive environment where I spend each and every day by learning at least a single new thing by following the way of problem solving tactics and the approach to face complex difficulties of our mentors which ultimately have changed my way of problem solving skills and strategies. I think you have already caught up in which company I am working currently, yes this is KAZ Software. You will get an idea about how much fun we do while we are at our office if you go through our company website mainly in company & culture section.

Follow

Get every new post delivered to your Inbox.

Join 37 other followers

%d bloggers like this: