Sunday, September 4, 2011

Dance with LINQ

For the first time I saw LINQ syntax I told to myself what the...
How in the world I can understand and write LINQ syntax easily. What is LINQ in first place? Is there any value for me to learn this. Guess what I started to think in ways to use it. Then I found it very handy.
In next posts I will try to teach you LINQ how to use it and how to understand exactly what are you doing and what LINQ can offer you.
Let's start with what is LINQ. after all if you want to start dancing with it you need to know your partner otherwise your dance will not be that much sexy! eventhough you are a good dancer.

LINQ is microsoft solution to query different sources like objects, XML, Dataset, SQL and entities easily with less code. However it is not just to query data. You can use LINQ to iterate items and even change thier types and use it to sort and etc.

at this stage please do not worry about the code in future posts I will talk about C# 3.0 futures so you will understand exactly how LINQ works. in the following example a list of string numbers are changing to int and also they are get sorted. I am sure you see what a nice functionality it it.

string[] mynums = {"34","020","3","16"};
int[] nums = mynums.Select(s=> Int32.Parse(s)).OrderBy(s=>s).ToArray();
foreach (int n in nums)
Console.WriteLine(n);

In next couple of posts I will talk about C# enhancements for LINQ so when we start LINQ then you have a better idea what is going on.

Hopefully you liked the first dance class with LINQ.

Please keep me updated.

Friday, February 20, 2009

WCF Contracts

A contract is at name implies is a standard way of describing what a service can do. Meanwhile, it is platform independent. In WCF we have 4 types of contract:
· Service Contract: It defines what a client can do with the service.
· Data Contract: It defines which data types can be transferred in the service. ( by default you can pass basic types like int, string however for custom types like a custom class you need to define the class as a Data Contract to be able to pass object of that class in the service)
· Fault Contract: It defines what are the errors raised by service.
· Message Contract: It is an extra functionality allows you to send message in a customized way (It means that you need to send a message in a specific way because let’s say there is an existing system that just understands messages in a specific way. As a user of WCF you should not usually use this as you do not need it except you are working with very specific system that needs specific messaging system)

Service Contract:
To allow a WCF Client to understand what they can do with the service you need to use Service Contract which is an attribute you need to add to the class. Also for each method that you wish WCF client to access you need add OperationContract attribute take a look at this sample

[ServiceContract]
Class MyService
{
[OperationContract]
public string MyOperation()
{
return “hello World”;
}
}

As you see in above example we have ServiceContract for the class and we have OperationContract for the methods. Some Points:
· You can apply ServiceContract to a class or interface
· You have to apply OperatoinContract for methods otherwise it will not be accessible to clients
· You can only apply OperationContract to methods
· It is highly recommended first you better create an interface and apply the servicecontract then create a class that implements the interface (the reason will be discussed further)
· Methods accessibility is not important to WCF (public, private or internal) since they are CLR concepts not WCF
· Always the default constructor will be called (avoid parameterized constructors)
· You can define a Namespace for the ServiceContract (and it is suggested to do so) to avoid collision
Please see the same sample by using interface and namespace
[ServiceContract(Namespace=”mycompany.com”)]
interface IMyService
{
[OperationContract]
string MyOperation();
}
Class MyService:IMyService
{
public string MyOperation()
{
return “hello World”;
}
}

Friday, February 13, 2009

WCF Fundamentals

To work with WCF you need to understand these elements in WCF:
1-Addresses
2-Contracts
3-Bindings
4-Hostings
5-Endpoints
6-Metada exchanges
7- Client side Programming

Addresses:
In WCF every service is associated with a unique address. Each address has two specifications. First it has the location of the service and second it has transport protocol. The location has the name of machine, a communication port and an optional specific path called URI. (URI is a unique string). WCF supports these protocols:
· HTTP : we use Http
· TCP : we use net.tcp
· Peer Network : we use net.p2p
· IPC: we use net.pipe
· MSMQ: we use net.msmq

So the address has this format:
[transport protocol]:// [machine name][:optional port number]/[optional URI]
example: Http://myserver:4040/myservice

You use each protocol based on requirement latter on when we talk about binding you will see that there are different bindings and for each binding you need to use one of the protocol then you have different kind of serialization & Interoperable functionality.

WCF & Service Oriented Architecture

Windows Communication Foundation (WCF) is a new technology in .Net 3.0/3.5 helps you to implement Service Oriented Architecture. This new technology not only allows you to work with previous services implemented by .Net Remoting or XML Web Services, but also has extensive functionality like instance management, asynchronous call, transaction management, disconnected queued calls, and security which can be applied through simple configuration.


If you are going to write a service it is better use this technology as it gives lots of flexibility. For those of you who may not work with other technologies like Remoting, COM+ or XML Web Services and may not have experience with Service Oriented Architecture I should say Service Oriented Architecture tries to provide the functionality through services which are components hosted probably in another box. Applications can use these services.

So if you have a code that you think different applications in internet / intranet may use it.You better provide that code as a service then your code centralized in one place while you can use extensive functionality through WCF.

Please read my other posts for WCF comming soon.

Steps to learn SharePoint

SharePoint is a massive product. It is so huge which makes it difficult to know all parts of it. Having said that you need to know the product and be a good user of the product itself then you can try a path to make yourself professional in this product. I believe there are two types of professionalism in SharePoint. The first one is Administration and Configuration of SharePoint. The second one is Development and Customization of SharePoint. These are steps to be a professional programmer in SharePoint:

1- Know the product and the functionality of it and the purpose
2- Be a good user of it (know how to use SharePoint)
3- Know how to install a SharePoint Server
4- Be able to understand differences between MOSS and WSS
5- Know how to use Out of the box features
6- Match the features to your company or a company
7- Understand different types of sites in SharePoint
8- Understand the connection of SharePoint and Office box
9- Be professional on creating Simple InfoPath forms
10- Configure a server farm
11- Create and manage content
12- Create a workflow
13- Manage enterprise search and indexing
14- Do Backup and recovery
15- Create a BDC
16- Develop a security topology
17- Configure other server platform to work with SharePoint
18- Know how to migrate from 2003 to 2007
19- Build collaboration and publish portals
20- Customize and brand your site with MasterPage, PageLayout, CSS, Themes and navigation
21- Customize and Create Workflow
22- How to deploy a workflow across servers
23- How to Use Form servers
24- How to use Excel Services
25- How to create Solution Package
26- How to use VS to Create Solutions

I am sure there are so many items that I missed and I need your help to add more if you think I missed something just send a post and I will add it to the list.

Anyway it is a long way to know SharePoint. At the first step my suggestion is that you can see 32 movies from Microsoft site to help you understand very basic functionalities of SharePoint.Just remember these movies are not covering all the functionalities but just part of them.

This is the list of movies to help you to get an understanding of basic features.

Demo: Configure a SharePoint Server 2007 site to receive e-mail

Demo: Deploy an administrator-approved form template

Demo: Simplify collaboration with a SharePoint team site

Demo: Streamline business processes with forms and workflows

Watch this: Create a presentation from slides in a slide library

Watch this: Create and manage a SharePoint calendar

Watch this: Find your way around a SharePoint team site

Watch this: Customize a site

Watch this: Automate business process with workflows

Watch This: Tour of My Site

Watch this: Use Word 2007 to post to a SharePoint blog

Watch this: Create a recurring meeting with a Meeting Workspace in a SharePoint calendar and then connect it to Outlook 2007

Watch this: Different ways to check documents in and out of a SharePoint site

Watch this: Make it easier to find information with views

Demo: The new SharePoint Server 2007 Fluent interface

Demo: Prepare to back up files on Office SharePoint Server

Demo: Connect people to information with portals

Demo: Enterprise Content Management with SharePoint Server 2007

Demo: Search for information on a SharePoint site

Demo: Add KPIs to your SharePoint site

Demo: Back Up Office SharePoint 2007

Watch this: Using SharePoint to manage your classroom

Demo: Display KPIs in a dashboard

Watch this: Give a user access to a SharePoint site

Watch this: Work with documents offline in Outlook

Watch this: Find just the data you need by using Filter Web Parts in a dashboard

Watch this: Use a Document Workspace to collaborate on a document from a SharePoint library

Demo: Enable Excel Services and data connections for a SharePoint team site

Demo: Make better business decisions with reports and dashboards

Watch this: Manage access to documents on My Site

Watch this: Use an approval workflow in SharePoint Server 2007

Watch this: Create and publish Web pages on a publishing site

Tuesday, February 10, 2009

Preparing a SharePoint Server

To start SharePoint what you need is an environment that is properly setup. You need so many softwares in that machine. It is almost impossible for most of us having a Server 2003 at our PCs. since most of our computers are Notebook. You need a Server 2oo3 to install SharePoint. The best way to solve the issue is that you can install Virtual PC. This Software allows you to install different OS on your computer. What you need is at least 40GB hard and 1GB of RAM then I believe you can have rather well enough machines to install SharePoint. The first step is installing Virtual PC. It is free software and you can download from this link:
http://microsoft-virtual-pc.en.softonic.com/

Then you need to install Windows 2003 in Virtual Machine.Then all you need is following this link and follow 20 Steps to install SharePoint in a virtual PC:

http://www.sharepointblogs.com/mykiep/archive/2007/04/26/step-by-step-guide-for-installing-moss-2007-on-a-vpc.aspx

Then be ready to learn about SharePoint, InfoPath and Workflow.

Monday, July 28, 2008

Command Pattern


This pattern is a behavioural pattern. Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
If you look at the Class diagram you see that client set the receiver for ConcreteCommand. Invoker has a list of commands and translates which command should be executed based on condition. (Do not worry about the class diagram we get back to that in a sample). There are different variation for this pattern for example sometimes there are no receiver.
The Command Pattern encapsulates a single function free of any variables. "It elevates the role of a function to the level of a class" Robert C Martin.

When to use this pattern?
When you need to change a method to a class then you can have a group of function in shape of unique class. You can use this pattern to create Undo and Redo functions. You can use this pattern to decouple two behaviours that are highly coupled like validating and doing behaviour. You can use this pattern to route requests, execute actions or forward actions in a uniform way.
In this post I am going to give you a sample of this pattern in real world also in next post I will show you an example of Undo, Redo using Command Pattern.

A real world Sample
I was assigned a task to implement a part of application. In that application users after selecting product and filling different information at final step had to select the payment method which was Credit Card and Ezi pay. The issue was that this application had many users so this part had to be implemented highly scalable and maintainable. I decided to use Command so users request from UI was changed to objects of requests. Because I was dealing with objects I could use message queuing also I could move this part to another server that do this so in that server the invoker did not have any idea about what sort of request are coming. A command was loaded and the execute method was called. I simplified the code and put it in one application to show you how amazing this pattern is. I made the UI very simple (just providing account number) however in real world it is more complex and each of these payments has its own attributes. Also you can check how many commands are in the queue. You can click on submit multiple times then by checking command numbers you see that there are some command in the queue that should be run. I used a queue list however in real world there are better way to implement. Let’s check the code:

UICode:

protected void butSubmitEzipay_Click(object sender, EventArgs e)

{

EziPayCommand cmd = new EziPayCommand(txtAccountNum.Text);

Invoker.Instance.AddCommand(cmd);

}

protected void butSubmitCredit_Click(object sender, EventArgs e)

{

CreditCardCommand cmd = new CreditCardCommand(txtCreditCardNum.Text);

Invoker.Instance.AddCommand(cmd);

}

protected void butCheck_Click(object sender, EventArgs e)

{

lblComandCount.Text = Invoker.Instance.GetNumberofCommandRunning().ToString();

}


As you see for each submit button I am adding the correct command into Invoker object (a singleton object. Just in my case I decide to use Invoker as singleton the pattern do not suggest this however here I needed just one object to control all the request for command by adding commands in a queue and running them one by one)


Invoker Class:

public class Invoker

{

private static Invoker m_Instance;

private bool InProgress=false;

public static Invoker Instance

{

get

{

if (m_Instance == null)

m_Instance = new Invoker();

return Invoker.m_Instance;

}

}

Queue<ICommand> commandList = new Queue<ICommand>();

public void AddCommand(ICommand cmd)

{

lock (this)

{

commandList.Enqueue(cmd);

}

CheckForExecution();

}

//for testing

public int GetNumberofCommandRunning()

{

return commandList.Count;

}

private void CheckForExecution()

{

if (!InProgress && commandList.Count > 0)

{

ThreadStart ts = new ThreadStart(ExecuteCommand);

Thread t = new Thread(ts);

t.Start();

}

}

private void ExecuteCommand()

{

InProgress = true;

while (commandList.Count > 0)

{

lock (this)

{

ICommand cmd = commandList.Dequeue();

}

cmd.Execute();

}

InProgress = false;

}

}


As you see I used singleton pattern here to have just one Invoker object controlling all the command execution. Invoker puts all the requests in a queue and run them one by one. When a command is added to the queue we check wether execution has been started if it is not started by creating new thread we start the process in a separate thread. In the execution process, a command is loaded and it will be run. As you see In Invoker we do not care about type of Command and Invoker itself has no idea which type of command it is running.

Sunday, July 20, 2008

Design Patterns

A Design pattern is a general reusable solution to a commonly occurring problem in software design. Each pattern has an intention that try to solve a common problem. You need to know the intention of each pattern also the problem they solve then if you come up with that issue you need to apply that pattern to solve the problem. I have seen so many programmers have no idea about design pattern if you are part of those people I should say you are not classified as senior programmer. I believe a senior programmer need to know these patterns. I could find a big gap in terms of design patterns knowledge between Java programmers and C# programmers. Java programmers know design patterns very well however; C# programmers hardly know them and use them. I had a lot of co-workers writing horrible codes just because they do not know how to solve a common problem. I wish I had a chance to convince them apart from technologies like ASP.NET, WCF, WF, and etc you need much more deep understanding about coding and design patterns otherwise you may know amazing technology but you do not have enough capacity to use them correctly!

This is why I decided to start writing about design patterns and give you some idea about them and also share my experiences over some of these patterns.

I hope you can find this useful. Please follow my post about design patterns and help me to correct myself also share your experiences with me.

A sample of Multi Thread programming in Asp.net

Download The Source Code

Please See the clip

Understanding the issue

I was assigned to implement a part of web application that was responsible for calling a java based application. There were some concerns about this part of application as follows:

1. The java based application was supposed to create a file that I had to process that file and show to user

2. A user could run the process from a page but after running he was not able to run it again (since the process took 3 min)

3. When application was running no one else could run application but they were supposed to see that application was run by someone else.

4. Page should be updated every 10 seconds to check whether the process is finished or not

5. When process is finished a file was generated I saved the file output in a temporary table (for simplicity I will save this data in a static variable)

To simulate this let's say we have an application called ExternalApp (a console application) to create a file but creating that file may take 3 min.

class Program

{

static void Main(string[] args)

{

if (args.Length == 1)

{

System.Threading.Thread.Sleep(180000);

StreamWriter w = new StreamWriter(args[0],false);

for(int i=0;i<10;i++)

w.WriteLine(" A Sample Data :"+ i);

w.Close();

}

}

}

Now we should create a web application to call this application by using Multi thread programming.

First I create a library to run the external application in a separate method. We need to check whether the process of running is finished or not. I created two classes one was Director another one was Builder.

Take a look at Director Class:

public class Director

{

Builder builder;

string userName;

public static List<string> Result = new List<string>();

public AlgorithemStatus Constract(Builder builder,string user)

{

this.userName = user;

if (HttpContext.Current.Application["athread"] == null)

{

this.builder = builder;

ThreadStart ts = new ThreadStart(RunThread);

Thread t = new Thread(ts);

t.Start();

HttpContext.Current.Application["athread"] = t;

return AlgorithemStatus.AlgorithemRunSuccessful;

}

else

return AlgorithemStatus.AlgorithemWasRunning;

}

public static bool IsAlgorithemRunning

{

get

{

if (HttpContext.Current.Application["athread"] == null)

return false;

else

{

Thread t = HttpContext.Current.Application["athread"] as Thread;

if (!t.IsAlive)

{

HttpContext.Current.Application.Remove("athread");

return false;

}

else

return true;

}

}

}

private void RunThread()

{

try

{

builder.PrepareHistoryFolder(userName);

builder.RunExternalAll();

Result = builder.LoadResult();

}

catch (Exception ex)

{

System.IO.StreamWriter w = new System.IO.StreamWriter(System.Configuration.ConfigurationManager.AppSettings["HistoryPath"] + "\\err.log", true);

w.WriteLine("Date Time : " + DateTime.Now);

w.WriteLine(ex.ToString());

w.Close();

}

}

}

In This class construct create a new thread and run RunThread method in it. IsAlgorithemRunning Property Check whether the running process has been started. Finally RunThread method calls different method in builder class and retrieve the result.

Check the Builder Class:

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

namespace AlgorithemManagment

{

public class Builder

{

private string pathResultExteranlApp;

private string pathExternalApp;

private StreamWriter statswriter;

internal void PrepareHistoryFolder(string userName)

{

//Check for History folder first

string path = System.Configuration.ConfigurationManager.AppSettings["HistoryPath"];

if (!Directory.Exists(path))

Directory.CreateDirectory(path);

string foldername = string.Format("{0:d4}_{1:d2}_{2:d2}_{3:d2}_{4:d2}_{5:d2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

string HistoryPaht = path + "\\" + foldername;

Directory.CreateDirectory(HistoryPaht);

pathResultExteranlApp = HistoryPaht + "\\Result.CSV";

pathExternalApp = System.Configuration.ConfigurationManager.AppSettings["ExteranlAppPath"];

string pathstats = HistoryPaht + "\\stats.log";

statswriter = new StreamWriter(pathstats, true);

statswriter.WriteLine("User who runned the Algorithem: " + userName);

statswriter.WriteLine("Starting DateTime: " + DateTime.Now.ToString());

}

internal void RunExternalAll()

{

System.Diagnostics.Process prc = new System.Diagnostics.Process();

prc.StartInfo.FileName = pathExternalApp;

prc.StartInfo.Arguments = pathResultExteranlApp;

if (prc.Start())

statswriter.WriteLine("Allocatoin application has just started at " + DateTime.Now.ToString());

prc.WaitForExit();

}

internal List<string> LoadResult()

{

List<string> strs = new List<string>();

StreamReader r = File.OpenText(pathResultExteranlApp);

string data = r.ReadLine();

while (data != null)

{

strs.Add(data);

data = r.ReadLine();

}

statswriter.WriteLine("Temptable was filled successfully DateTime:" + DateTime.Now.ToString());

statswriter.Close();

return strs;

}

}

}

PrepareHistoryFolder creates a history folder to log and also save the result. RunExternalApp runs the External application and wait until it result is generated. LoadResult read the file generated by external app and process it.

Check the Page code:

protected void Page_Load(object sender, EventArgs e)

{

if (Director.IsAlgorithemRunning)

{

PrepareDisableMode();

}

else

{

PrepareEnableMode();

}

}

private void PrepareEnableMode()

{

ButtonRunAlgorithm.Enabled = true;

imgwait.Visible = false;

DataListResult.Visible = true;

if (Director.Result.Count > 0)

{

DataListResult.DataSource = Director.Result;

DataListResult.DataBind();

}

}

private void PrepareDisableMode()

{

ButtonRunAlgorithm.Enabled = false;

imgwait.Visible = true;

ClientScript.RegisterStartupScript(typeof(string), "mykey", "<script>RefreshPageinSecond();</script>");

DataListResult.Visible = false;

}

protected void ButtonRunAlgorithm_Click(object sender, EventArgs e)

{

PrepareDisableMode();

AlgorithemManagment.Director d = new AlgorithemManagment.Director();

AlgorithemManagment.Builder b = new AlgorithemManagment.Builder();

d.Constract(b,"The User Name");

}

When page is load if algorithm is running we are disabling the button and showing an image indicating we are middle of the process. If algorithm is not running we enable the button and also show the result. When button is clicked we disable button and show the image and also run the algorithm.

Please see the clip to understand the code better.
Please download the source code and also go to web.config file and update the ExteranlAppPath which is the address of ExternalApp exe file and update the HistoryPath which is the address of history folder to log information.