Skip to main content

Posts

Showing posts with the label C#

Implementing OAuth2 consumer in C#

Recently I worked on a project that involved integrating with social networking and jobs websites like Elance. These days almost all major services that allow applications to access users' data, perform authorization/authentication using OAuth1.0 or OAuth2. OAuth2 compared to OAuth1 is very easy to implement. OAuth1 involves generating nonce,timestamp,signaturebase and signing the request with any algorithm like HMAC-SHA1 and appending data to query string of URL and passing in Authorization header of HTTP. OAuth2 removed all these requirements. Following is OAuth2 process in a nutshell 1) Redirect user to Authorization url passing client_id and redirect_url in query parameters 2) If user authenticates successfully through service provider it will redirect user to the redirect_url passed with authorization access code in query parameters. 3) After getting authorization access code you exchange this to receive access token. You make a POST HTTP request to a URL passing client_id ...

Truncate/Ignore time part of DateTime column in Entity Framework

There are times when you want to perform query on only date part of the column that has type DateTime in database. Entity framework does not support DateTime.Date property but provides a helper class EntityFunctions . EntityFunctions has a method TruncateTime that can be called in Linq2Entities query and truncates the time part from datetime. Here is how to use it using (AccountEntities dal = new AccountEntities ()) {               DateTime dtStart=DateTime.Now.AddDays(-20).Date;               DateTime dtEnd=DateTime.Now.Date;     transactions = (from t in dal.Transactions                             where                             EntityFunctions.TruncateTime (t.TransactionDate.Value)                     ...

Multithreaded C# TCP server to handle multiple clients

I decided to write a minimal multithreaded TCP based server as a blog post. Following class can serve as a skeleton for any small or large scale multithreaded TCP socket server. It do not contain much error handling , it is only to give an idea that how multithreaded server works and how it can process multiple clients using threading. using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Generic; namespace RandomStuffMine { public class MTServer {     public int Port{get;set;}     public Socket ServerSocket{get;set;}     private List<Client> Clients=new List<Client>();     private bool runServer=true;     public MTServer(int port)     {         Port=port;         ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     }   ...

Indexers in C#

Definition of Indexers from MSDN Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters. Whenever you are accessing individual element from List<T> or Hashtable<T,T> etc you are using Indexers . For example List<string> str=new List<string>(); str.Add("Rameez"); str.Add("Usmani"); string firstName=str[0];  //[0] is implying that you are calling indexer on instance of List class How Indexer is added to a class To add an indexer to a class you have to expose a property named "this(actually a keyword)" followed by "data type of index" in square brackets . Like this public ReturnDataType this[indexDataType] {     get { //logic to return the correct value }     set { //logic to set the correct value } } Lets say you have collection of Students and you want to access Student by name using Indexer , here is h...

Resizing image in C#

In this blog post I will explain in short how to load and re size an image in C# and save the resulting image in a file. Actually the process is very easy. Lets break it in chunks Loading image from a file .NET has multiple ways to load an image. 1) From a file 2) From a Stream object 3) From a GDI Bitmap object For this post we will only load image from a File.Loading image from file is straight forward. It requires calling static method FromFile of Image class , passing the file path as a parameter. Here is how Image myImage=Image.FromFile(sourcePath); Re-sizing image As we now have Image instance we have to re size it. For re-sizing we will use one overload of Bitmap class constructor which takes Image instance and new width and height for scaling. So here is the one liner to do this job Bitmap bmp=new Bitmap(myImage,newWidth,newHeight); Saving the resulting image We have a Bitmap containing scaled version of our original image.Now we will save it to a ...