Sponsors

Thứ Bảy, 28 tháng 1, 2012

JSON serialising/deserialising in .NET

I've started to make an active effort in using JSON over XML, the main reason being that I find JSON formatted data to be easier on the eye than XML formatted data. I found a project in our source control repository at work that used JSON formatted data as input. The project used a neat little JSON library that I'll now be using whenever required. The library is called Json.NET. The following code shows how easy it is to serialise a .NET POCO into JSON, and then reconstruct the object back from JSON using the aforementioned library.

Imagine we have a simple class that models a person:

internal class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
We can create an instance of this class and then serialize the object into a JSON string using the JsonConvert class as follows:

var inputPerson = new Person() 
    { FirstName = "Alan", LastName = "Turing", Age = 41 };

string json = JsonConvert.SerializeObject(inputPerson);
The json string variable now contains the value:

{"FirstName":"Alan","LastName":"Turing","Age":41}

Reconstructing the object back from a JSON string is as simple as:

var outputPerson = JsonConvert.DeserializeObject<Person>(json);

Thứ Ba, 24 tháng 1, 2012

How to add new website into IIS Programatically using Asp.net C#?

Programatically add new website with proper binding info into iis using c#.


Here i am writing an article for Creating website in iis using c#.
For Adding or deleting website from IIS here is this scenareo I must say IIS7 is the best friend for the developers.Because administering websites through code was made very simple by Microsoft.Web.Administration.dll which is present in the %windir%\system32\inetsrv folder.IS 7.0 and above provide a comprehensive managed-code management application programming interface (API) that allows complete manipulation of the XML configuration files and convenience access to server objects.


Intro:
IIS includes Microsoft.Web.Administration, which is a new a management API for the web server that enables editing configuration through complete manipulation of the XML configuration files. It also provides convenience objects to manage the server, its properties and state. The configuration editing aspect of the API provides programmatic access to read and write configuration properties in the IIS configuration file hierarchy and specific configuration files. The object management aspect of this API provides a series of top-level administration objects for direct management of the server (i.e. sites, application pools, worker processes, etc).


The ServerManager is the factory class that contains a set of server convenience objects to which properties and methods are available to use in a strongly-type way. It is the main entry point for managing the server. Managing the server could have been done via other cumbersome routes (accessing raw configuration XML or calling state APIs), but through these objects managing the server is seamless.The most common set of objects are available to use via the server manager include: applications, virtual directories, sites, worker processes and application domains
ServerManager serverManager = new ServerManager();

The sites object enables access to a sites properties and applications. It also contains methods to add a site to the system or get the total site count. The add method also defines the name of the site, the root virtual directory path,
and the port number as integer.

Note: Add Microsoft.web.Administration dll.
Environment: IIS 7

Code : Page Default.apsx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Web.Administration;
using System.Drawing;

namespace AddWebsiteIIS7
{
public partial class _Default : System.Web.UI.Page
{
ServerManager serverMgr = new ServerManager();

protected void Page_Load(object sender, EventArgs e)
{
lblmsg.Text = "";
}

protected void btncreate_Click(object sender, EventArgs e)
{
try
{ string strWebsitename = txtwebsitename.Text; // abc
string strApplicationPool = "DefaultAppPool"; // set your deafultpool :4.0 in IIS
string strhostname = txthostname.Text; //abc.com
string stripaddress = txtipaddress.Text;// ip address
string bindinginfo = stripaddress + ":80:" + strhostname;

//check if website name already exists in IIS
Boolean bWebsite = IsWebsiteExists(strWebsitename);
if (!bWebsite)
{
Site mySite = serverMgr.Sites.Add(strWebsitename.ToString(), "http", bindinginfo, "C:\\inetpub\\wwwroot\\yourWebsite");
mySite.ApplicationDefaults.ApplicationPoolName = strApplicationPool;
mySite.TraceFailedRequestsLogging.Enabled = true;
mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
serverMgr.CommitChanges();
lblmsg.Text = "New website " + strWebsitename + " added sucessfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
else{
lblmsg.Text = "Name should be unique, " + strWebsitename + " is already exists. ";
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}
catch (Exception ae)
{
Response.Redirect(ae.Message);
}
}

public bool IsWebsiteExists(string strWebsitename)
{
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
foreach (Site site in sitecollection)
{
if (site.Name == strWebsitename.ToString())
{
flagset = true;
break;
}
else{
flagset = false;
}
}
return flagset;
}
}
}
Conclusion:

This article demonstrated one of the concepts to create a new website on IIS programmatically using ASP.NET and C#.


Note:
  • Make sure your redirection.config file has Read,Write full Permission.
  • It is just my experienced which is explained in the above article also it doesn’t include additional things like exception handling & web service security. Please feel to modify it according to your requirements.
Location: c:\windows\System32\inetsrv\config\redirection.config;



Thứ Năm, 19 tháng 1, 2012

String.ParseCsvToList Extension Method

A useful extension method to System.String. Given a comma-seperated list in a string, it'll return a generic List of type string, with each value occupying its own index.

public static List<string> ParseCsvToList(this string source)
{
    var valuesArray = source.Split(new char[] {','});
    return valuesArray.Select(value => value.Trim()).ToList();
}

Thứ Tư, 18 tháng 1, 2012

How to send email in asp.net?


Sending Email is a common task of a web application for many purposes like- Error logging, Reporting, Newsletters as well as for many other reasons.Gmail is a good solution for this purpose. Gmail provides SMTP and POP access which can be utilized for sending and receiving E-mails.
Here in this article we demonstrate how to send email  with uisng your Google account.

Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Net.Mail;


// system.net.mail namespace is used for emailing.
protected void btnsubmit_Click(object sender, ImageClickEventArgs e)
{
//Code for send Email
MailMessage sendMailforSA = new MailMessage();
SmtpClient smtpforSA = new SmtpClient();
string subjectforSA = null;
subjectforSA = "Thanks for apply";
System.Net.NetworkCredential credforSA = new System.Net.NetworkCredential("Superman@gmail.com", "password");
sendMailforSA.To.Add(txtemailid.Value);
MailAddress cc = new MailAddress("info@superman.com");
sendMailforSA.CC.Add(cc);

// sendMailforSA.CC("abcxxx@gmail.com");
sendMailforSA.From = new MailAddress("Rajnikant@gmail.com");
sendMailforSA.Subject = subjectforSA.ToString();
sendMailforSA.Body =" Thank you.... your message you can use html tag for style effect";
sendMailforSA.IsBodyHtml = true;
smtpforSA.Host = "smtp.gmail.com";
smtpforSA.Port = 25;
smtpforSA.EnableSsl = false;
smtpforSA.UseDefaultCredentials = false;
smtpforSA.Credentials = credforSA;
smtpforSA.Send(sendMailforSA);
}

Thứ Bảy, 14 tháng 1, 2012

How to execute sql script file in asp.net c#

EXECUTE SQL SCRIPT FROM C#


To create SQL Database using Asp.net is quite difficult, Here I 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.

Debug n get the flow of code.
Enjoy....... 

Thứ Sáu, 13 tháng 1, 2012

Sqldatasource control set dynamic Connectionstring in .aspx page only


Dynamically Set ConnectionString of SqlDataSource ASP.NET Control Inside GridView Template

Intro:
The SqlDataSource control enables you to use a Web server control to access data that is located in a relational database. You can use the SqlDataSource control with data-bound controls such as the GridView, FormView, and DetailsView controls to display and manipulate data on an ASP.NET Web page, using little or no code.


Here in this article i am writting how to set Dynamically ConnectionString Attribute on  SqlDataSource ASP.NET Control. Setting connection string for SqlDataSource control can de done programmatically in the code-behind ie (.aspx.cs) file.

On Page_Load:
SqlDataSource1.ConnectionString = yourconnectionstring;

If the SqlDataSource control is  inside the FooterTemplate of a GridView control then it will not be accessible at Page_Load. Here's the challenging task how to set ConnectionString on SqlDatasource control under Gridview Templates.
By following below steps you can achive this:
Step 1:
Here sample code of gridview templates:

<footertemplate>
<asp:dropdownlist autopostback="True" datasourceid="sqldsWorkcategory" datatextfield="name_wt" datavaluefield="id_wt" id="cmbfWorkCategory" onselectedindexchanged="cmbfWorkCategory_SelectedIndexChanged" runat="server" width="118">
</asp:dropdownlist>
<asp:sqldatasource connectionstring="&lt;%$ RepConnectionString: " getconnection="getconnection">"
id="sqldsWorkcategory" runat="server"
selectcommand="SELECT [id_wt], [name_wt] FROM [yourtablename]"&gt;
</asp:sqldatasource>
</footertemplate>

Step 2:
Now edit your web.config file
As i have many connection so have make a diifernt XML file to store all connections key



<configsource onstring.xml="onstring.xml" pp_data="pp_data">
<!-- Now Add this pieace of code under Compilation as u can see. -->
<compilation debug="true" targetFramework="4.0">
<expressionbuilders>
<add expressionprefix="RepConnectionString" type="RepConnectionStringExpressionBuilder">
</add></expressionbuilders>

</configsource>

Step 3:
Add class file inside App_code.
Have named as CodeExpressionBuilder.cs.

Note: using System.CodeDom; is needed
if u find error then add refference or google for this namespace,

Code of CodeExpressionBuilder.cs
just copy as it is.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Configuration;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml;
using System.CodeDom;

//this is what we set in .aspx page (ie sqldatacource control)
[ExpressionPrefix("RepConnectionString")]
public class RepConnectionStringExpressionBuilder : ExpressionBuilder
{

public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
CodeTypeReferenceExpression thisType = new CodeTypeReferenceExpression(base.GetType());
CodePrimitiveExpression expression = new CodePrimitiveExpression(entry.Expression.Trim().ToString());
string evaluationMethod = "GetConnectionString"; //
return new CodeMethodInvokeExpression(thisType, evaluationMethod, new CodeExpression[] { expression });
}
public static string GetConnectionString(string expression)
{
string getcon1='Some thing lke ur connectionstring... form xml'
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[getcon1].ConnectionString);
string wConnString = conn.ConnectionString;
return wConnString;
}
}

This will set your dynamic ConnectionString for SqlDataCource control on .aspx page.
Debug n get the flow of code.Enjoy.......