Sponsors

Thứ Ba, 18 tháng 12, 2012

MongoDB Developer Course Success

A bit off topic today, just some good news. In an earlier post, I mentioned that I was on a MongoDB developer course (ran by 10gen, the MongoDB company). Last week was the final week of the course with the final exam deadline this Monday. The results have just been published - I received a grade of 85% so have officially passed the course (certificates are awarded from 65% onwards).

The course has given me an excellent grounding in MongoDB and I just wanted to thank 10gen for administrating it. It looks like they are running a Java version of the course next year, so I highly recommend any developers interested in MongoDB to enrol onto it.

It's a nice way to end a busy year. Merry Christmas and Happy New Year.

Thứ Tư, 5 tháng 12, 2012

Run Sql Script file in Asp.net C#

EXECUTE SQL Script file in Asp.net C#


To create SQL Database using Asp.net is quite difficult, Here In this article am writing how to create SQL Database and how to Run the SQL Script File in asp.net. These two dlls you have to import to perform these task


  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Smo.dll
So that it iterates SQL scripts in a directory and executes them with ConnectionContext.ExecuteNonQuery. 

Code : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.IO;
using System.Xml.Linq;

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("YOUR CONNECTIONSTRING");
}

protected void btn_Click(object sender, EventArgs e)
{
string strdbname=txtdbname.text;
string strCreatecmd = "create database " + strdbname + "";
SqlCommand cmd = new SqlCommand(strCreatecmd, con1);
con1.Open();
cmd.ExecuteNonQuery();
con1.Close();
// Code to execute sql script ie(create tables/storedprocedure/views on ms sqlserver)

//generatescript.sql is sql script generated and placed under Add_data folder in my application
FileInfo file = new FileInfo(Server.MapPath("App_Data\\generatescript.sql"));
string strscript = file.OpenText().ReadToEnd();
string strupdatescript = strscript.Replace("[databaseOldnameWhileSriptgenerate]", strdbname);
Server server = new Server(new ServerConnection(con1));
server.ConnectionContext.ExecuteNonQuery(strupdatescript);
con1.Close();
}

Note: 
  • Microsoft.SqlServer.Smo.dll,Microsoft.SqlServer.ConnectionInfo.dll is need
  • You will find these online or check in ur windows ie In c/programfiles/sqlserver/assembly/...
  • Your databasescript contain "GO" if not using smo.dll it will throw error.

Thứ Ba, 4 tháng 12, 2012

Dynamic Typing and Extension Methods

Earlier today I came across an interesting runtime exception of type RuntimeBinderException. The specific exception message was:

'System.DateTime' does not contain a definition for 'ToUKFormat'

'ToUKFormat' is a custom extension method on DateTime that I wrote and was in-scope at compile time when I called it. So what caused the runtime exception? It turns out that you cannot call an extension method on an object/value that is dynamically typed. In my case, I was using the dynamic ViewBag in an ASP.NET MVC application to store a DateTime value - then in my view, I was retrieving that value from the ViewBag and calling a custom written extension method on it ('ToUKFormat'). In razor syntax, I was doing something similar to:


@ViewBag.Foo.Bar.ToUKFormat()
I have given the solution further below but if you want to reproduce the problem in a simple console application, you can use the following code:


namespace DynamicRuntimeIssue
{
class Program
{
static void Main(string[] args)
{
dynamic today = DateTime.Today;

Console.WriteLine(today.ToUKFormat()); // Exception...
Console.ReadLine();
}
}

static class DateTimeExtensions
{
public static string ToUKFormat(this DateTime dateTime)
{
return dateTime.ToString("dd/MM/yyyy");
}
}
}
When you run the code above, you will encounter the aforementioned exception. Of course, if you appropriately type the 'today' variable to a DateTime rather than dynamic, then you'll find that it all works as expected. However, if you cannot avoid the use of dynamic, like for example in my case where I was using ViewBag - then you can overcome this exception by calling your extension method as if it was any normal static method. You call the method and pass-in your object/value through as an actual parameter. Following on from the example above, you would therefore have:


Console.WriteLine(DateTimeExtensions.ToUKFormat(today));
Rather than:


Console.WriteLine(today.ToUKFormat());
If you want to understand why you can't call extension methods on a dynamic type, then go over to this stackoverflow question where someone else has had the same issue - you will particularly want to read Eric Lippert's response dated March 15 2011.

Thứ Bảy, 24 tháng 11, 2012

CRUD against MongoDB via C#

In my previous post, I gave some of my first thoughts about NoSQL in relation to MongoDB. In this post we will look at how you can perform basic CRUD operations against a MongoDB collection using the official C# driver. The purpose of this post is for me to use it as a handy reference when working with MongoDB in the future - hopefully you'll also find it useful. I will assume that the reader has some familiarity with using MongoDB on the shell.

Throughout the post I'll be using a simple collection of documents where each document stores some basic information about an aircraft. If you load the MongoDB shell and execute the following statements then we'll have a common ground to start with:
use mongotest
db.planes.insert({
'Manufacturer':'Lockheed Skunk Works',
'Model':'Blackbird SR-71',
'FirstFlight': new Date('12/22/1964')
})
db.planes.insert({
'Manufacturer':'Lockheed Skunk Works',
'Model':'X-55 ACCA',
'FirstFlight': new Date('06/02/2009')
})
At this point, you should have a database called mongotest with one collection containing two JSON documents. You can verify this by executing:
db.planes.find().pretty()
We'll now access and modify the planes collection using the C# driver. You can download the driver from here or add it to your solution using the NuGet package (it's easy to do using the NuGet package manager in Visual Studio). For this post, I'm using version 1.6.1 of the official MongoDB C# driver. Assuming you now have added references to MongoDB.Bson.dll and MongoDB.Driver.dll, add the following three using statements at the top of your class (FYI, I practiced with a standard console application directly within the Main method):

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
Now we can define a class that will map to a single plane document. We will use this class along with the MongoDB generic C# driver methods to insert, retrieve, update and remove documents from our planes collection.
public class Plane
{
public ObjectId Id { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public DateTime FirstFlight { get; set; }
}
Note how we're using the MongoDB.Bson.ObjectId type for our identifier property (we're relying on MongoDB to add unique id's to newly inserted plane documents). Also note that the Plane class must support a parameterless constructor for the driver to be able to work with it.

Let's now take a look at how you can insert a new plane document into the planes collection using the driver. We'll first get a handle on the planes collection, I have the following four lines at the top of my Main method that gives me the required reference (planesCollection):
var connectionString = "mongodb://localhost/?safe=true";
var server = MongoServer.Create(connectionString);
var mongotestdb = server.GetDatabase("mongotest");
var planesCollection = mongotestdb.GetCollection("planes");
To insert a new document into the planes collection (note that the Id property will be filled-in by the insert method):
planesCollection.Insert(new Plane {
Manufacturer = "Unknown",
Model = "Tornado IDS/ECR",
FirstFlight = new DateTime(1974, 8, 14)
});
To retrieve a list of all the documents in the planes collection:
var planes = planesCollection.FindAll().ToList();
To retrieve a list of filtered documents - let's say we want only the planes that are manufactured by Lockheed:
var lockheedPlanes = planesCollection.Find(
Query.EQ("Manufacturer", "Lockheed Skunk Works"))
.ToList();
To update a document (as a whole block) in the planes collection:

var planeToUpdate = planesCollection.FindOne(
Query.EQ("Manufacturer", "Unknown")
);
planeToUpdate.Manufacturer = "Panavia Aircraft GmbH";
planesCollection.Save(planeToUpdate);
Note that you can also perform a partial update to a document (not as a block), refer to the Update method on the MongoCollection class.

Finally, to remove a set of documents based on a query from the planes collection - in this case we'll remove all planes manufactured by Lockheed from the collection:

planesCollection.Remove(
Query.EQ("Manufacturer", "Lockheed Skunk Works")
);

Thứ Sáu, 9 tháng 11, 2012

Initial thoughts on NoSQL with MongoDB

I have heard about the NoSQL movement for a while now but only recently started to properly look into a NoSQL technology. A few weeks ago I found out that 10gen (the team behind the popular NoSQL database called MongoDB) are starting a free "MongoDB for developers" course. The course runs weekly, with each week containing a number of videos that you watch, take a quiz on and then submit homework for. So far it has been very useful despite some initial hiccups in administrating the course. We're now starting Week 3 and have already covered quite a lot about NoSQL in general and how MongoDB can be used in a CRUD sense.
 
Week 3 of the course dives deeper into schema design in MongoDB and compares this with schema design in the more familiar relational data model. The course also has a project that runs throughout - which is to create a simple blogging engine using MongoDB and Python. It seems like the future weekly homeworks are going to be geared towards extending the blogging engines' functionality. Although the course material is using Python to communicate with MongoDB, there are a number of driver libraries that you can download from the MongoDB website for other programming languages - such as C#. I haven't had a chance to play with the C# driver yet but plan on writing a blog post about my experience with it in the future.
 
My training at university and all of the work experience I have gained so far has been around working with relational database management systems. So it is quite exciting moving away from the relational mindset and thinking about a different way to persist application data. It is weirdly refreshing to work with JSON documents in collections than working with the tables and rows abstraction in relational databases.
 
One thing that the course instructors emphasise about MongoDB is that your schema design should be geared towards how your application will access your data. So unlike in a relational data model, where you typically normalise your model to the third normal form - in MongoDB your data model will reflect the access pattern your application will use to get or update the data. As MongoDB doesn't provide support for joining data, you typically model your data (or JSON documents) so that each document contains all of the necessary information your application will regularly need for a particular use case. This is interesting as I think there is an implicit assumption here that you'd only ever have one particular access pattern for your MongoDB database... for example what if I wanted to build another application that accesses the data for a purpose that is different from when the original MongoDB database was designed? I'm hoping the answer to this question is not along the lines of migrating/copying the data to a schema that's more appropriate for the new application!
 
At this stage of my exploration, another concern with MongoDB is that there doesn't seem to be a quick out-of-the-box method to generate a pretty looking report for the data stored in the collections. In the relational world, SQL with the table and rows abstraction lends itself nicely to generating reports that non-technical users can easily make sense of. With MondoDB, you can query your collections of JSON documents easily enough in the shell using mongo.exe and the find() method on a collection - but the resulting output is in JSON format which probably won't go down too well with a non-technical user. Having said this, there may still be solutions/explanations to these concerns that I haven't come across - so I'm definitely not letting them stop me from diving deeper into the NoSQL MongoDB world.

Thứ Sáu, 5 tháng 10, 2012

Convert Int32 to Base 2, 8, 10 or 16

A few weeks ago I had a requirement to convert an Int32 value (base 10 or decimal) to its binary representation as a string. I encapsulated the logic to convert the decimal number to a binary string in a method. I used the base 10 to base 2 algorithm where the decimal number is continiously divided by two until it becomes zero. Within the iteration, the modulo two of the number is then appended to the output binary string. At the time of writing that code, it seemed like the best way to go about it, and because it was neatly encapsulated in a method, I knew I could swap out the implementation at a later date without much hassle.

Today, I came across an overload of the Convert.ToString method which surprisingly accepted a parameter called toBase. I wish I had come across this earlier... The overload accepts the bases 2, 8, 10 or 16 and throws an ArgumentException if one of these are not passed in. Anyway, I converted the method I wrote to an extension method on Int32 called "InBase" - I think that reads better than Convert.ToString with a base passed in. The implementation is below in case you want to include it in your libraries.


public static string InBase(this int number, int @base)
{
    return Convert.ToString(number, @base);
}
Example usage:

Console.WriteLine("{0}", 10.InBase(2)); // Outputs "1010" (Binary)
Console.WriteLine("{0}", 10.InBase(8)); // Outputs "12" (Octal)
Console.WriteLine("{0}", 10.InBase(10)); // Outputs "10" (Decimal)
Console.WriteLine("{0}", 10.InBase(16)); // Outputs "a" (Hexadecimal)
Console.WriteLine("{0}", 10.InBase(3)); // Throws ArgumentException

Thứ Năm, 4 tháng 10, 2012

The Pragmatic Programmer

When studying for my undergrad degree, one of my lecturers recommended the book The Pragmatic Programmer (by Andrew Hunt and David Thomas). The book is written by a couple of experienced Software Engineers and contains a wealth of useful knowledge for anyone who is considering a serious career in software development.

The topics covered range from general tips that the authors learnt from their experiences, some useful tools you should know about as a programmer, how to think when you're writing code, how to write testable code and much more. It's a mixed bag of eight chapters, with each chapter broken down into smaller digestable sections. It was the perfect companion to someone who commuted into university on the train.

I know this post isn't relevant to C# per se, but thought it may encourage you to get hold of the book and learn some useful practices that you can apply in your projects.

Chủ Nhật, 19 tháng 8, 2012

How to Add / Update record using GridView control (c#)

A Gridview is a control for displaying and manipulating data from different data sources. It shows data from a variety of data sources in a tabular format.

Instead of boundfiled, I prefer to use TemplateField coz of its simplicity. Here in this Artilce i am going to implement how to Add, Update, Delete selected record from GirdView control.
Tested Sample code : Add new record from footer and Update the selected row
Default.aspx:


<asp:gridview allowpaging="True" autogeneratecolumns="False" cellpadding="4" forecolor="#333333" gridlines="None" id="gvstatus" onpageindexchanging="gvstatus_PageIndexChanging" onrowcancelingedit="gvstatus_RowCancelingEdit" onrowcommand="gvstatus_RowCommand" onrowediting="gvstatus_RowEditing" onrowupdating="gvstatus_RowUpdating" onselectedindexchanged="gvstatus_SelectedIndexChanged" runat="server" showfooter="True" width="600px">
            <columns>
 <asp:templatefield headerstyle-horizontalalign="Left" headertext="SrNo ">
            <itemtemplate>
                    &lt;%# Container.DataItemIndex + 1 %&gt;
                </itemtemplate>
 </asp:templatefield>

 <asp:templatefield headertext="ID" visible="false">
      <itemtemplate>
      <asp:label columnname_id="" id="lblid" runat="server" text="&lt;%# Bind(">"&gt; </asp:label>
     </itemtemplate>
</asp:templatefield>
<asp:templatefield headertext="EmpName">
      <itemtemplate>
        <asp:label columnname_empname="" id="lblEmpName" runat="server" text="&lt;%# Bind(">"&gt;</asp:label>
       </itemtemplate>
       <edititemtemplate>
           <asp:textbox id="txtEmpName" runat="server" text="&lt;%# Bind(&quot;columnname_EmpName&quot;) %&gt;"></asp:textbox>
        </edititemtemplate>
        <footertemplate>
              <asp:textbox id="txtfEmpName" runat="server"></asp:textbox>
        </footertemplate>
</asp:templatefield>
 <asp:templatefield headertext="empSalary">
        <itemtemplate>
           <asp:label id="lblempSalary" runat="server" text="&lt;%# Bind(&quot;columnname_EmpSalary&quot;) %&gt;"></asp:label>
        </itemtemplate>
        <edititemtemplate>
             <asp:textbox id="txtempSalary" runat="server" text="&lt;%# Bind(&quot;columnname_EmpSalary&quot;) %&gt;"></asp:textbox>
         </edititemtemplate>
         <footertemplate>
            <asp:textbox id="txtfempSalary" runat="server"></asp:textbox>
         </footertemplate>
</asp:templatefield>
 <asp:templatefield itemstyle-width="190px" showheader="False">
         <itemtemplate>
             <asp:button causesvalidation="False" commandname="Edit" id="btnedit" runat="server" text="Edit"></asp:button>
          </itemtemplate>
          <edititemtemplate>
               <asp:button causesvalidation="True" commandname="Update" id="btnupdate" runat="server" text="Update"></asp:button>
                        &nbsp;<asp:button causesvalidation="False" commandname="Cancel" id="btncancel" runat="server" text="Cancel"></asp:button>
         </edititemtemplate>
        <footertemplate>
            <asp:button commandname="Add" id="btnadd" runat="server" text="Add">
        </asp:button></footertemplate>
 </asp:templatefield>
            </columns>
            <pagerstyle backcolor="#A86E07" forecolor="White" horizontalalign="Center">
            <selectedrowstyle backcolor="#E2DED6" font-bold="True" forecolor="#333333">
          <headerstyle backcolor="#A86E07" font-bold="True" forecolor="White">
        <editrowstyle backcolor="#d9d9d9">
    <alternatingrowstyle backcolor="White" forecolor="#A86E07">
 </alternatingrowstyle></editrowstyle></headerstyle></selectedrowstyle>
</pagerstyle>
</asp:gridview>



CodeBehind:


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
gvBind(); //Bind gridview
}
}

public void gvBind()
{ SqlDataAdapter dap = new SqlDataAdapter("select id, empName,empSalary from myTable", conn);
DataSet ds = new DataSet();
dap.Fill(ds);
gvstatus.DataSource = ds.Tables[0];
gvstatus.DataBind();
}
Update the select row from girdview
protected void gvstatus_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
lblmsg.Text = "";
try
{
GridViewRow row = (GridViewRow)gvstatus.Rows[e.RowIndex];
Label lblid = (Label)gvstatus.Rows[e.RowIndex].FindControl("lblid");
TextBox txtname = (TextBox)gvstatus.Rows[e.RowIndex].FindControl("txtEmpName");
TextBox txtSalary = (TextBox)gvstatus.Rows[e.RowIndex].FindControl("txtempSalary");
string empName = txtname.Text;
string empSalary = txtSalary.Text;
string lblID=lblid.Text;
int result = UpdateQuery(empName, empSalary,lblID);
if (result > 0)
{
lblmsg.Text = "Record is updated successfully.";
}
gvstatus.EditIndex = -1;
gvBind();
}
catch (Exception ae)
{
Response.Write(ae.Message);
}

}
Code to add new record to database form girdview footer
  protected void gvstatus_RowCommand(object sender, GridViewCommandEventArgs e)
{

if (e.CommandName == "Add")
{
string empName = ((TextBox)gvstatus.FooterRow.FindControl("txtfempName")).Text;
string empSalry = ((TextBox)gvstatus.FooterRow.FindControl("txtfempSalary")).Text;
int result = InsertNewRecord(empName, empSalry);
if (result > 0)
{
lblmsg.Text = "Record is added successfully.";
}
gvstatus.EditIndex = -1;
gvBind();

}
}

protected void gvstatus_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvstatus.EditIndex = -1;
gvBind();
}
protected void gvstatus_RowEditing(object sender, GridViewEditEventArgs e)
{
lblmsg.Text = "";
gvstatus.EditIndex = e.NewEditIndex;
gvBind();
}

public void UpdateQuery(string empName, string empSalary, string lblID)
{
SqlCommand cmd = new SqlCommand("update myTable set empName='" + empName + "',empSalary='" + empSalary + "' where id='" + lblID + "'", conn);
conn.Open();
int temp = cmd.ExecuteNonQuery();
conn.Close();
return temp;
}


public void InsertNewRecord(string empName, string empSalary)
{
SqlCommand cmd = new SqlCommand("your insert query ", conn);
conn.Open();
int temp = cmd.ExecuteNonQuery();
conn.Close();
return temp;
}

Thứ Bảy, 18 tháng 8, 2012

How to Resize image while uploading in asp.net using c#

Resize image while uploading in asp.net using c#?

This post will show you how you can resize images in ASP.Net C# during uploading image file.
For we Dotnet Developer in most of our ASP.Net application we have uploaded image facility where will face the performance issue while loading uploaded images to display for the user. In my project their is a similar requiremnt that the user uploaded images will be resized internally through server side while uploading.
I have an .aspx page which will upload images to server harddisk from client pc. And i need to write a program in such a way that it would allow me to resize the image while uploading.

Here's the code:
Firstly, we are going to need the System.Drawing and System.Drawing.Drawing2D namespaces

Design Uploadlogo.aspx:
Upload Logo :


<asp:fileupload id="File1" runat="server">
</asp:fileupload>
 <asp:button id="Button1" onclick="Button1_Click" runat="server" text="Save">
 <asp:label id="lblmsg" runat="server" text=""></asp:label>
</asp:button>



Code Behind: UploadLogo.aspx.cs
  public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public partial class UploadLogo : System.Web.UI.Page
{
public Size OriginalImageSize { get; set; } //Store original image size.
public Size NewImageSize { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
lblmsg.Text="";
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
Guid uid = Guid.NewGuid();
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
string SaveLocation = Server.MapPath("LogoImages") + "\\" + uid+fn;
try
{
string fileExtention = File1.PostedFile.ContentType;
int fileLenght = File1.PostedFile.ContentLength;
if (fileExtention == "image/png" || fileExtention == "image/jpeg" || fileExtention == "image/x-png")
{
if (fileLenght <= 1048576)
{
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
objImage.Save(SaveLocation,ImageFormat.Png);
lblmsg.Text = "The file has been uploaded.";
lblmsg.Style.Add("Color", "Green");
}
else{
lblmsg.Text = "Image size cannot be more then 1 MB.";
lblmsg.Style.Add("Color", "Red");
}
}
else {
lblmsg.Text = "Invaild Format!";
lblmsg.Style.Add("Color", "Red");
}
}
catch (Exception ex)
{
lblmsg.Text= "Error: " + ex.Message;
lblmsg.Style.Add("Color", "Red");
}
}
}

}



Chủ Nhật, 15 tháng 7, 2012

Implementing Convert.ToInt32(string)

Earlier today I used the static helper method System.Convert.ToInt32(string). I thought it would be interesting to have a go at writing my own version of this method.

public static int ConvertToInt32(string integerAsString)
{
var result = 0;
var positiveSigned = integerAsString[0] == '+';
var negativeSigned = integerAsString[0] == '-';

for (var i = (positiveSigned || negativeSigned) ? 1 : 0;
i < integerAsString.Length;
i++)
{
var currentCharAsInt = (int) integerAsString[i] - (int) '0';

if (currentCharAsInt < 0 || currentCharAsInt > 9)
throw new ArgumentException(
string.Format("The String value '{0}' " +
"is not in a recognisable format.",
integerAsString));

result *= 10;
result += currentCharAsInt;
}

return (negativeSigned) ? -result : result;
}

Thứ Hai, 18 tháng 6, 2012

Download .apk from Asp.net website using android phone browser



Here in this article i let you know how to Download .apk file from Asp.net website (WebApplication) by using your android mobile browser. Recently in my project their is one requirement to download .apk file. In my webapplication download page i inserted a button and set path it works fine when you use to download it from your computer, but a problem comes when same i access it from my android phone browser it gives errors (Instead of 605 kb it only download 22kb ie only html content not actual apk file)
So after small research i figured out the solution and it to simple here it is that by adding  mimeType="application/vnd.android.package-archive".

Environment : My Application is hosted under Window server 2008r2 having IIS 7.

Following the steps you can Download .apk file.

Step 1:  In .aspx page add hyperlink set navigateurl as file path

<asp:HyperLink ID="lnkdwnload" runat="server" NavigateUrl="~/Application_Android/MyAndroidAppAame.apk">Download MyApp</asp:HyperLink>



Step 2: Web.config add mimeMap element under staticContent

<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive"/>
    </staticContent>
</system.webServer>

Thứ Ba, 12 tháng 6, 2012

How to create website with multiple languages in asp.net c#

How to make website for multiple languages?

A website which can support Multiple Languages and change according to the culture of a specific geographical location is not a new topic. Websites to support multiple languages can be a challenging and time-consuming process. You find many artilce related on internet and well explained, But i still see that many of them are complicated for "Beginners". I tried to make this article to approach a more dynamic way to manage languages regarding Globalization/ Localization/ Culture concepts.

With standard HTML pages, you may have to create and maintain duplicate versions of each page for each supported language as well as having the language content embedded into the HTML, where content can’t easily be edited.  For those of you who have to develop multi-lingual interfaces and applications, you’ll be glad to know that ASP.NET makes things easier.
ASP.NET and the .NET framework ship with support for multilingual applications, namely in the form of Resource Files, the CultureInfo class, and the System.Globalization and System.Resources.ResourceManager namespaces.

However, we need to understand what is meant by "globalization", "localization" and "culture" in this context.
Globalization:
Globalization is a process of identifying all the parts of your application that need to be different for respective languages and separate them from the core application.

Localization:

Localization is process of creating and configuring your application for a specific language.

Cultures:

A culture is combination of the language that you speak and the geographical location you belong to. It also includes the way you represent dates, times and currencies. It's important to have a good understanding of Cultures since our new code will make use of them - specifically the System.Globalization.CultureInfo class, and the culture name value which follows the RFC 1766 naming standard. Basically, you create a new CultureInfo instance by specifying the culture name in the constructor:
CultureInfo c = new CultureInfo("en-US");

Follow the step to create website for multiple languages:
Step 1:
Create new website -> Solution Explorer -> Select sln right click and Add Asp.Net Folder - App_GlobalResources
Now under App_globalization add resources file (.resx  file), i add three resx file deafult for english, fr for french, de for german haivin key pair values;
Structure look like as in below image:

Step 2:
Add Global.asax file:
Code: write this piece of code
void Application_BeginRequest(Object sender, EventArgs e) 
{
// Code that runs on application startup
HttpCookie cookie = HttpContext.Current.Request.Cookies["CultureInfo"];
if (cookie != null && cookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);
}
else
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
}
}



Step 3:
Add masterPage having a dropdownlist control;
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
if (Session["ddindex"] != null) {
ddlanguage.SelectedValue = Session["ddindex"].ToString();
ddlanguage.SelectedIndex = Convert.ToInt32(Session["ddindex"].ToString());
}
else{
ddlanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
}
}
}
protected void ddlanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["language"] = ddlanguage.SelectedValue;
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlanguage.SelectedValue);

if (cookie.Value == "en"){
Session["ddindex"] = 0;
}
else if (cookie.Value == "fr"){
Session["ddindex"] = 1;
}
else if (cookie.Value == "de"){
Session["ddindex"] = 2;
}
Server.Transfer(Request.Path);
}
}








Add childPage with controls and on dropdownlist selected index it will display respective language content

My sample Childpage desin code :
set text as resoures key; i.e Text="<%$Resources:Resources,FieldName %>"



<table id="Table1">
<tbody>
<tr>
  <td class="style1"><asp:label id="Label2" runat="server" text="&lt;%$Resources:Resources, FirstName %&gt;"></asp:label></td>
  <td><asp:label id="Label3" runat="server" text="&lt;%$Resources:Resources, LastName %&gt;"></asp:label></td>
</tr>
<tr>
  <td class="style1"><asp:label id="Label4" runat="server" text="&lt;%$Resources:Resources, Gender %&gt;"></asp:label></td>
  <td><asp:radiobuttonlist id="RdBtnLtGender" repeatdirection="Horizontal" runat="server">
     <asp:listitem text="&lt;%$Resources:Resources, Male %&gt;" value="1"></asp:listitem>
     <asp:listitem text="&lt;%$Resources:Resources, Female %&gt;" value="0"></asp:listitem>
  </asp:radiobuttonlist></td>
</tr>
<tr><td class="style1"><asp:label id="Label7" runat="server" text="&lt;%$ Resources:Resources, Month %&gt;"></asp:label></td>
  <td><asp:dropdownlist height="20px" id="ddyear" runat="server" width="64px">
  <asp:listitem value="1">Jan</asp:listitem>
  <asp:listitem value="2">Feb</asp:listitem>
  <asp:listitem value="3">Mar</asp:listitem>
  <asp:listitem value="4">Apr</asp:listitem>
  <asp:listitem value="5">May</asp:listitem>
  <asp:listitem value="6">Jun</asp:listitem>
  <asp:listitem value="7">Jul</asp:listitem>
  <asp:listitem value="8">Aug</asp:listitem>
  <asp:listitem value="9">Sep</asp:listitem>
  <asp:listitem value="10">Oct</asp:listitem>
  <asp:listitem value="11">Nov</asp:listitem>
  <asp:listitem value="12">Dec</asp:listitem>
   </asp:dropdownlist>
  </td>

</tr>

</tbody></table>

ScreenShots :OutPut  

1) For English

















2) For French

Thứ Hai, 21 tháng 5, 2012

MVC Model Binding to List of Complex Objects

Recently, I had a requirement to create a form-based partial view in an MVC3 application that permitted a user to select multiple options using standard HTML checkboxes. What this essentially meant was that I needed MVC to automatically bind a complex list of objects to the argument of an action method.

After doing some reading on this, I found that the DefaultModelBinder supports this as long as the form fields are named in such a way that the model can distinguish one complex object from another - this can be achieved by using a unique index when creating the form. The example below shows exactly how this can be done - I'm using MVC3 with the Razor view engine.

Imagine we need to display a list of options to the user, the user can select multiple options from the list and then post the form back to one of your action methods on the server side. In this scenario, we're going to display a list of planes to the user, the user can select their favourite plane(s) and then click a submit button. We'll start by defining our model - a "complex" but self explanatory class called PlaneModel.

public class PlaneModel
{
  public string Manufacturer { get; set; }
  public string Model { get; set; }
  public bool IsFavourite { get; set; }

  public override string ToString()
  {
    return string.Format("{0} - {1}", Manufacturer, Model);
  }
}

For the sake of brevity, I won't use a partial view (but the method should be the same if you want to use a partial view in your case). We'll create a new controller called PlaneController, with one initial action method "Index". In this action method, we'll new-up some instances of PlaneModel, store them in a list-based collection and then pass this collection as a model to a strongly-typed Index view. The Index action method would therefore look like:

[HttpGet]
public ActionResult Index()
{
  var planes = new List<PlaneModel>(); //Model

  planes.Add(new PlaneModel { 
      Manufacturer = "Cessna"
      Model = "C208B Grand Caravan" });
  planes.Add(new PlaneModel { 
      Manufacturer = "Douglas"
      Model = "DC-3" });
  planes.Add(new PlaneModel { 
      Manufacturer = "Piper"
      Model = "J-3 Cub" });
  planes.Add(new PlaneModel { 
      Manufacturer = "Mooney"
      Model = "M20J" });
            
  return View(planes);
}

Notice that the action method maps to our HTTP GET request. So, whilst we're still in our controller, we'll write the POST action. The key thing to remember here is that our post action will accept a list of PlaneModel objects.

[HttpPost]
public ActionResult ProcessFavouritePlanes(List<PlaneModel> model)
{
  foreach (var planeModel in model)
  {
    if (planeModel.IsFavourite)
      Debug.WriteLine("Favourited: {0}", planeModel);
    else
      Debug.WriteLine("Not favourited: {0}", planeModel);
  }
  return View(model);
}

So, all I'm doing in the POST action is iterating through the planes in the model (which will be passed back from the view) - and hopefully the IsFavourite property should have been bound to the correct values that the user selects using checkboxes.

Now onto the important part - the creation of our view. Create a strongly typed Index view (i.e., a generic list of type PlaneModel). If you're using Visual Studio as your IDE, you can right-click within your Index action method and select the option "Add View" - this should bring up a modal dialog. Leave the view name as "Index", check the "Create a strongly-typed view" option and type:

List<PlaneModel>

in the "Model class" text box (note that you will probably need to prefix the PlaneModel class name with its fully qualified namespace as the generic type parameter to List - if you don't do this you'll get a runtime error when navigating to the Index view). You can now click "Add" and the view will get created under the conventional folder structure.

The view logic will be a simple mixture of standard HTML and C# in Razor syntax:

@model List<PlaneModel>
Please select your favourite plane(s):<br />
@using (Html.BeginForm("ProcessFavouritePlanes"
                       "Plane"
                       FormMethod.Post))
{
  for (int i = 0; i < Model.Count; i++)
  {
    @Html.CheckBoxFor(m => m[i].IsFavourite)
    @Model[i].ToString() 
    @Html.HiddenFor(m => m[i].Manufacturer)
    @Html.HiddenFor(m => m[i].Model)
  }
  <input type="submit" value="Go!" />
}

Notice that we're iterating through each PlaneModel object using a C# for-loop. This allows us to use the incrementing index and display each option from the model. Also note the use of the hidden fields for the Manufacturer and Model properties - these are here to ensure that they're passed back to the DefaultModelBinder on the server side - taking these two lines out will mean that we'll get PlaneModel objects with blank values for those two properties when the form is posted to the POST action. You should now be able to test if this is all working by hitting a breakpoint on the POST action, running the application and selecting some options. You'll find that the model binder will automatically bind the selected checkboxes and update the model passed into the action.

To understand why this works, we can take a look at the rendered HTML sent back to the client for our form:

<form action="/Plane/ProcessFavouritePlanes" method="post">
  <input name="[0].IsFavourite" type="checkbox" value="true" />
  <input name="[0].IsFavourite" type="hidden" value="false" />
  Cessna - C208B Grand Caravan 
  <input name="[0].Manufacturer" type="hidden" value="Cessna" />
  <input name="[0].Model" type="hidden" value="C208B Grand Caravan" />
  <br />
  <input name="[1].IsFavourite" type="checkbox" value="true" />
  <input name="[1].IsFavourite" type="hidden" value="false" />
  Douglas - DC-3 
  <input name="[1].Manufacturer" type="hidden" value="Douglas" />
  <input name="[1].Model" type="hidden" value="DC-3" />
  <br />
  <input name="[2].IsFavourite" type="checkbox" value="true" />
  <input name="[2].IsFavourite" type="hidden" value="false" />
  Piper - J-3 Cub 
  <input name="[2].Manufacturer" type="hidden" value="Piper" />
  <input name="[2].Model" type="hidden" value="J-3 Cub" />
  <br />
  <input name="[3].IsFavourite" type="checkbox" value="true" /> 
  <input name="[3].IsFavourite" type="hidden" value="false" />
  Mooney - M20J 
  <input name="[3].Manufacturer" type="hidden" value="Mooney" />
  <input name="[3].Model" type="hidden" value="M20J" />
  <br />
  <input type="submit" value="Go!" />
</form>

Notice how the framework added index prefixes to the name attributes of the input elements. The use of this index-based naming convention for the input elements allows the DefaultModelBinder in MVC to distinguish between each complex object - and therefore seamlessly create a correct representation of our model that is passed to the POST action - very neat!

Chủ Nhật, 15 tháng 4, 2012

Send webrequest with parameter in asp.net c#


Here the below code will generate webrequest and send with parameter in asp.net C#.


Stream objStream;
StreamReader objSR;
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

string str = "http://domaninname.com/YourPage.aspx?name=" + "abc";
HttpWebRequest wrquest = (HttpWebRequest)WebRequest.Create(str);
HttpWebResponse getresponse = null;
getresponse = (HttpWebResponse)wrquest.GetResponse();

objStream = getresponse.GetResponseStream();
objSR = new StreamReader(objStream, encode, true);
string strResponse = objSR.ReadToEnd();
Response.Write(strResponse);

How to convert string into MD5 hash?


MD5 is an acronym for Message-Digest 5-- a fast and powerful method of increasing security to file transfers and message request transfers.
The way it works is the user enters an input string, and the md5 algorithm will generate a 32-character string in hexadecimal characters. The characters will always be hexidecimal, and the string will always be 32 characters in length.
Once a string is hashed into an md5 hash, it cannot be unhashed via any "un-md5" algorithm. The only way is to use an MD5 cracker tool, which queries a large database of strings and their associated md5 hashes.
Once your md5 hash code is generated, you can deliver it to the expected receiver and they can use that hash to match against their result of performing an md5 hash on their own values. If the hashes match, then you can be confident that the data was sent correctly.


CODE :


using System.Text;
using System.Security.Cryptography;
public static string ConvertStringtoMD5(string strword)
{
MD5 md5 = MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strword);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}

Thứ Tư, 11 tháng 4, 2012

ASP.NET MVC3 Attributes

I am currently working on a project where we're porting an existing SharePoint 2010 site to ASP.NET MVC3. Coming from an ASP.NET Web Forms background, this is an interesting experience. ASP.NET MVC is quite different from the Web Forms model, with one of the biggest differences being its emphasis on "convention over configuration".

Having played with MVC2 in the past, the work on this project has been smooth sailing. I'm particularly enjoying the level of control that the MVC development model provides over the resulting HTML sent back to a users browser. The bloated HTML from the Web Forms model (quickly pointing the finger at the ViewState hidden field) is something I don't have to painfully scroll over when inspecting the generated HTML.

I particularly like how MVC makes use of attributes on action methods, things like the AuthorizeAttribute are a nice and clean way of executing repeated functionality without it really getting in the way of your usual controller or action level logic.

The main purpose of this post is therefore just for me to continuously document the useful attributes I come across. My intention is to update the table below whilst working on the project mentioned above.

Attribute Name Notes
System.Web.Mvc.AuthorizeAttribute Applied on actions that require the user to be authenticated. If the user is not authenticated, they are automaticallly redirected to the login page. Can also be used at the controlller (class) level - which applies it on all actions within the controller.
System.Web.Mvc.ChildActionOnlyAttribute Applied on actions that shouldn't be invokable directly through the browser. Use this when the action returns inline HTML markup e.g. partial views. Can only be called via Action or RenderAction HTML extension methods.
System.Web.Mvc.NonActionAttribute Use this when you don't want the MVC framework to treat a method in your controller class as an action. By default, the framework will treat all public methods in a controller as an action method.
System.Web.Mvc.OutputCacheAttribute Used to cache the output of an action. Has a number of useful named parameters, one of which is "Duration" that lets you specify the number of seconds to cache the output for.

Thứ Tư, 7 tháng 3, 2012

Ajax Auto Complete suggestion in asp.net using webservices (Ajax AutocompleteExtender)

AutoCompelete using Ajax in Asp.net 

Ajax a powerfull script on the web,It provides you a lot more functionality to
improve your application Performance.
Heres the article to show how to work with AutoCompleteExtender (Control in AjaxControlToolKIt).


AutoComplete Description
  • AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control,
    and will associate that control with a popup panel to display words that
    begin with the prefix typed into the textbox.
  • The dropdown with candidate words supplied by a web service is
    positioned on the bottom left of the text box
    .

This means that the control will fetch the data from a webservice(sdsd), and it can be attached to a asp.net TextBox control.
Whenever users starts typing in the textbox, it automatically fetches a suggestion list from the configured webservice.


Note: Add latest Ajax dll in your application bin folder.

Step 1: Add  webservices (WebService.asmx)
code:  appcode/WebService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Collections;

/// Summary description for WebService
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string[] GetNames(string prefixText, int count, string contextKey)
{
ArrayList sampleList = new ArrayList();
sampleList.Add("ABC"); sampleList.Add("Hello");
sampleList.Add("Hi"); sampleList.Add("Apple");
sampleList.Add("Hey");
ArrayList filteredList = new ArrayList();
foreach (string s in sampleList){
if (s.ToLower().StartsWith(prefixText.ToLower()))
filteredList.Add(s);
}
return (string[])filteredList.ToArray(typeof(string));
}
}


Step 2: AC.aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ac.aspx.cs" Inherits="Ac" %>

<%@  Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="Ajaxtoolkit"  %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
 <body>

  <form id="form1" runat="server">
    <asp:scriptmanager id="ScriptManager1" runat="server"></asp:scriptmanager>
   <div>
        <asp:textbox id="TextBox1" runat="server"></asp:textbox>
          <ajaxtoolkit:autocompleteextender enabled="true" minimumprefixlength="0" runat="server" servicemethod="GetNames" servicepath="WebService.asmx" targetcontrolid="TextBox1" usecontextkey="true">
        </ajaxtoolkit:autocompleteextender>
    </div>
</form>
</body>
</html>

Thứ Ba, 6 tháng 3, 2012

Save and retrive Binarydata from database into image

How to Save and Retrive BinaryData from Database into Image


This article will demonstrate how to display/store and retrieve image data from an SQL database to aspx page. First we have to add generic handler.

Create an ashx page that you'll target as an image URL.Then you need to write the byte array as response stream in the ProcessRequest method inside that handler as show in below code snippet.

ShowImage.ashx
%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}

public Stream ShowEmpImage(int empno)
{ string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT* FROM table WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}

catch
{ return null; }

finally
{ connection.Close(); }
}
public bool IsReusable
{
get { return false; }
}
}

Default page.aspx.cs


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = "INSERT INTO 
table(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);

// Display the image from the database
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
}
catch
{
lblResult.Text = "There was an error";
}
finally { connection.Close(); }
}
}

Thứ Bảy, 3 tháng 3, 2012

NDataFlow - Open Source .NET Dataflow Library

Last year, a colleague of mine showed me an open source .NET extract, transform and load (ETL) helper library that he's working on. It is called NDataFlow and allows you to annotate methods with attributes to create a dataflow in your application. It's a nice lightweight library that you can use whenever you are developing simple or complex ETL programs. The example below simulates a very simple ETL scenario where a set of people (hard-coded in the example) are filtered based on their location and then output to a file.

class Program : DataflowComponent
{
static void Main(string[] args)
{
new Program().Run();
}

//First method in the flow
[Operation]
public void DataSource(Output output)
{
//Imagine retrieving people from a real data source
//e.g. database, xml file, csv file, etc.
output.Emit(new Person() { Name = "Alice", City = "London" });
output.Emit(new Person() { Name = "Bob", City = "New York" });
output.Emit(new Person() { Name = "Foo", City = "London" });
output.Emit(new Person() { Name = "Bar", City = "Sydney" });
}

[Operation]
public IEnumerable FilterForLondonPeople
([Link("DataSource")] IEnumerable input)
{
return input.Where
(p => p.City.Equals("London",
StringComparison.InvariantCultureIgnoreCase));
}

[Operation]
public void OutputResults
([Link("FilterForLondonPeople")] IEnumerable results)
{
using (var sw = new StreamWriter(@"C:\LondonPeople.txt", false)
{
foreach (var p in results)
sw.WriteLine("{0} {1}", p.Name, p.City);
}
}
}
The example shows that there is little work needed to get a simple dataflow setup and running. You inherit the Run method by deriving from the NDataFlow.DataflowComponent class. Then, if you've setup your method and attributes correctly using the LinkAttribute it's a simple case of calling Run to start your dataflow. In this case, the first method in the dataflow would be DataSource, whose output is sent to FilterForLondonPeople and finally whose output is sent to the OutputResults method.

Thứ Sáu, 10 tháng 2, 2012

Fluent Interface in C#

I've seen a number of API's now that utilise a "fluent" interface (e.g., Fluent NHibernate, Moq etc.). So far, I've had mixed feelings about it. If you're not familiar with what a fluent interface is, then Martin Fowler's post on this subject is a good starting point. By following a fluent design, you get some neat looking "client-side" code that is almost self-describing. The following example models a real-world person and exposes a fluent interface.

public class Person
{
    public string FirstName { get; private set; }
    public string Surname { get; private set; }

    private Person() { }

    public static Person New()
    {
        return new Person();
    }

    public Person SetFirstName(string firstName)
    {
        this.FirstName = firstName;
        return this;
    }

    public Person SetSurname(string surname)
    {
        this.Surname = surname;
        return this;
    }

    public override string ToString()
    {
        return string.Format(
            "I am {0} {1}",
                this.FirstName,
                    this.Surname);
    }
}
As the code snippet shows, each setter method in the Person class returns a reference to the "current" object (think context/state). This is important as it permits users of the class to chain method calls on the object, with each invocation returning an up-to-date state of the original object. For example, we can create an instance of Person and then set its state in one single C# statement:

var person = Person.New()
    .SetFirstName("Ravi")
        .SetSurname("Singh");
This looks neat and is very readable. Without a fluent interface, you may have code that looks somewhat like:

var person = new Person();
person.FirstName = "Ravi";
person.Surname = "Singh";
Of course, you could use the object initialiser syntax or pass the names through to an appropriate constructor, but that's not the point. The point is that you don't get the same readability or fluentness that you get using method chaining. If your methods are named properly, then using the fluent technique makes reading your code closer to reading a sentence in natural language.

I personally prefer the fluent version. Earlier in the post, I mentioned that I had a mixed feeling - this mainly stems from the fact that it becomes difficult to debug code that uses a fluent interface. For example, if you have a statement in which a number of method calls are chained on an object, it's difficult to see the intermediary values returned by each method unless you step into each method call. This can be a bit of a pain when debugging. Other than this one problem, I've enjoyed working with fluent-based API's and will strive to write classes in a more "fluent" way.