Latest Entries »

Model-View-Controller

Model-View-Controller (MVC) :

MVC is an architectural design principle that separates the components of a Web application. This separation gives us more control over the individual parts of the application. MVC is a part of .net Web Application Framework. However, it is straightforward to map these concepts into the domain of multi-tier enterprise applications. By using MVC a software developer can create a web application as a composition of three roles:

1.Model: The model contains the core information for an application. This includes the data and validation rules as well as data access and aggregation logic. The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model. A model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the application.

2.View: The view encapsulates the presentation of the application, and in ASP.NET this is typically the HTML markup. It is the view’s responsibility to maintain consistency in its presentation when the model changes. This can be achieved by using a push model, where the view registers itself with the model for change notifications, or a pull model, where the view is responsible for calling the model when it needs to retrieve the most current data.

3.Controller: The controller translates interactions with the view into actions to be performed by the model. The controller contains the control-flow logic. It interacts with the Model and Views to control the flow of information and execution of the application. This separation of entity allows us to have agility and flexibility in building and maintaining our application. ASP.NET MVC brings the power of this development pattern to ASP.NET development, allowing us to use our .NET development skills to build MVC applications.

Polymorphism

Polymorphism

In programming this word is meant to reuse the single code multiple times. In object oriented programming its a big question that why the Polymorphism is done, what is the purpose of it in our code?

Polymorphism is the 3rd main pillar of OOP without it the object oriented programming is incomplete. Lets go in the depth of Polymorphism. Why Polymorphism Its obvious that when we do inheritance between two classes, all the methods and properties of the first class are derived to the other class so that this becomes the child class which adopts all the functionality of base class. But there is a big problem in inheriting the second class to the first class as it adobpts all the methods same as the base class has,which means that after inheritance both(base class& child class) have the methods of same name and same body as shown in this example:

Base Class public class fish

{

public void eat(){ console.writeline(“fish eat”); }

public void swim(){ console.writeline(“fish swim”); }

}

 

Derived Class class Dolphin:fish{

public void eat(){ console.writeline(“fish eat”); }

public void swim(){ console.writeline(“fish swim”); }

}

 

In this example it is clear that when we Inherit two classes, all the methods with the same name and same body are adopted by the derived class as shown above. Both methods have the same name but if we change the body of the second method then it makes Compiler disturb whether to compile base class method or derived class’s method first.. Lets have a look of this code..

Base Class public class fish{

public void eat(){ console.writeline(“fish eat”); }

public void swim(){ console.writeline(“fish swim”); }

}

Derived Class class Dolphin:fish{

public void eat(){ console.writeline(“Dolphin can eat”); }

public void swim(){ console.writeline(“Dolphin can swim”); }

}

 

In this example we have changed the body of the methods of Derived class. Now this will make the Compiler disturb to compile which method first,because they both have same name but different bodies. To remove this problem and to tell the compiler that which method is to be executed we need to use Polymorphism. How the Polymorphism is done? Polymorphism is used to remove the problem which is shown in the above code. It is done not by changing the name of the methods of both base & derived class. Infect it is done by adding the “virtual” keyword before the base class method, and the “override” keyword before the derived class method.

As shown in this example:

Base Class public class fish{

public virtual void eat(){ Console.WriteLine(“fish eat”); }

public virtual void swim(){ Console.WriteLine(“fish swim”); }

}

Derived Class class Dolphin : fish{

public override void eat(){ Console.WriteLine(“Dolphin can eat”); }

public override void swim(){ Console.WriteLine(“Dolphin can swim”); }

}

 

This is actually the Polymorphism in which we write virtual keyword with the base class method and we write override keyword with the derived class method as we did. It helps the compiler to select the method to be executed. Here is the complete code in which Polymorphism has been applied.

class Program{

public class fish{

public virtual void eat(){ }

public virtual void swim(){ }

public virtual void dive(){ }

}

public class Dolphin : fish{

public override void eat(){Console.WriteLine(“Dolphin eats Plants”); }

public override void swim(){ Console.WriteLine(“Dolphin swims quickly”); }

public override void dive(){ Console.WriteLine(“Dolphin dive deeply “); }

public void dance(){ Console.WriteLine(“Dolphin can Dance”); }

}

public class Shark : fish{

public override void eat(){ Console.WriteLine(“Shark eats dead animal”); }

public override void swim(){ Console.WriteLine(“Sharks swim fastest than Dolphin”); }

public override void dive(){ Console.WriteLine(“Sharks Dive deeper than Dolphin”); }

public void kill(){ Console.WriteLine(“Shark kills Others”); }

}

static void Main(string[] args){

Dolphin D = new Dolphin();

D.dance();

D.dive();

D.eat();

D.swim();

Shark S = new Shark();

S.kill();

S.dive();

S.eat();

S.swim();

Console.ReadLine();

}

}

 

Hope this would help you.

By default, you can sort on the columns of a GridView by clicking on the LinkButton in the header of a column that has a SortExpression defined. This post is going to attempt three things.

  1. Sort the column by clicking anywhere in the header cell
  2. Add a sort indicator to cells that are sortable. Cells that are sortable will have a “neutral” icon. Note in the screen capture below that UnitsInStock does not have a “neutral” icon because it does not have a SortExpression defined.
  3. Highlight the column of data that is being sorted.

gridview_clickable_headers

The idea is to add an onclick attribute that calls a javascript function to all GridView header cells that are sortable.

In the javscript function, we determine which element raised the event. If the element that raised the event is not the LinkButton, we find the LinkButton and invoke its onclick or href attribute method based on the GridView EnableSortingAndPagingCallbacks property. When the EnableSortingAndPagingCallbacks is set to true, we invoke the onclick method otherwise we invoke the method the href attribute points to.

We are checking which element raised the event in the javscript function to prevent the postback or callback from being called twice. This is because, without this check, clicking on the LinkButton will fire the method as well as bubble the event up to its parent cell causing it to be fired again (since we have added an onclick attribute to the cell). The javascript function calls the postback or callback method only if the element that raised the event is not the LinkButton.

public void MakeGridViewHeaderClickable(GridView gridView, GridViewRow gridViewRow) {

if (gridViewRow.RowType == DataControlRowType.Header)
{
for (int i = 0; i < gridView.Columns.Count; i++)
{
string sortExpression = gridView.Columns[i].SortExpression;
TableCell tableCell = gridViewRow.Cells[i];

//Make sure the column we are working with has a sort expression
if (!string.IsNullOrEmpty(sortExpression))
{
System.Web.UI.WebControls.Image sortDirectionImageControl;

//Create an instance of a Image WebControl
sortDirectionImageControl = new System.Web.UI.WebControls.Image();

//Determine the image url based on the SortDirection
string imageUrl = “~/Images/sort_neutral.gif”;

if (sortExpression == gridView.SortExpression)
{
imageUrl = (gridView.SortDirection == SortDirection.Ascending) ? “~/Images/sort_asc.gif” : “~/Images/sort_desc.gif”;
}

//Add the Image Web Control to the cell
sortDirectionImageControl.ImageUrl = imageUrl;
sortDirectionImageControl.Style.Add(HtmlTextWriterStyle.MarginLeft, “10px”);
tableCell.Wrap = false;
tableCell.Controls.Add(sortDirectionImageControl);

//Enumerate the controls within the current cell and find the link button.
foreach (Control gridViewRowCellControl in gridViewRow.Cells[i].Controls)
{
LinkButton linkButton = gridViewRowCellControl as LinkButton;

if ((linkButton != null) && (linkButton.CommandName == “Sort”))
{
//Add an onclick attribute to the current cell
tableCell.Attributes.Add(“onclick”, “RequestData(‘” + linkButton.ClientID + “‘, this, event)”);
tableCell.Style.Add(HtmlTextWriterStyle.Cursor, “hand”);
tableCell.Style.Add(HtmlTextWriterStyle.Cursor, “pointer”);
break;
}
}
}
}

}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {

MakeGridViewHeaderClickable(GridView1, e.Row);

}

The javascript function is shown below

<script language=“javascript” type=“text/javascript”>

function RequestData(linkId, cellElement, evt) {

var evtSource;

evt = (evt)? evt : window.event;

evtSource = (evt.srcElement)? evt.srcElement : evt.target;

//When a hyperlink is clicked, Safari returns the text node as the source element rather

//than the hyperlink. parentNode will give us the hyperlink element.

//ref: http://developer.apple.com/internet/webcontent/eventmodels.html

if (evt.target) {

if (evt.target.nodeType == 3) {

evtSource = evtSource.parentNode;

}

}

//If event was raised from an element other than the LinkButton

if ((evtSource.getAttribute(“id”) != linkId) && (evt.type == “click”)) {

//Get a collection of “a” tags inside the cell

var linkCollection = cellElement.getElementsByTagName(“a”);

for (var i = 0; i < linkCollection.length; i++) {

//If the link button has an onclick attribute, call the onclick.

//The onclick attribute is present when the GridView is using callback

//example: onclick=”java script:__gvGridSort1_GridView1.callback(…); return false;”

var onClickAttribute = linkCollection[i].getAttribute(“onclick”);

if (onClickAttribute != null) {

linkCollection[i].onclick();

break;

}

//If the link button has a href attribute, set the location of the page

//to the href value.

//The href attribute is used when the GridView is not using callbacks

//example: href=”java script:__doPostBack(‘GridSort1$GridView1′,’Sort$UnitsOnOrder’)”

var hrefAttribute = linkCollection[i].getAttribute(“href”);

this.location.href = hrefAttribute;

break;

}

}

}

</script>

You can also use this with HeaderTemplates. Just make sure your HeaderTemplate contains a LinkButton with a CommandName attribute set to “Sort” as shown below:

<asp:TemplateField HeaderText=“ProductID” SortExpression=“ProductID”>

<ItemTemplate>

<asp:Label ID=“Label1″ runat=“server” Text=‘<%# Bind(“ProductID”) %>’></asp:Label>

</ItemTemplate>

<HeaderTemplate>

<asp:LinkButton runat=“server” CommandName=“Sort” CommandArgument=“ProductID”

Text=“ProductID”></asp:LinkButton>

</HeaderTemplate>

</asp:TemplateField>

You can easily make these transparent sort icons by working at the pixel level ( I used Photoshop)
sort_asc sort_desc sort_neutral

The MakeGridViewHeaderClickable method can be placed in a Utility class if you so desire. A reference to the GridView can be obtained by using gridViewRow.Parent.Parent or (GridView) gridViewRow.NamingContainer if you don’t want to pass in a GridView reference to the method.

Ajax ModalPopUpExtender

  • Introduction

This article explains about the Asp.Net AjaxControlToolkit’s ModalPopup with Postback and Focus setting methodology.

  • Description

I have seen in many asp.net forums, the developers post lots of questions on Asp.net’s AjaxControlToolkit’s ModalPopup extender. Actually they want to do postback operations and want to set focus on the controls placed in the ModalPopup window. So I think many web developers who used AjaxControlToolkit will be very much pleased if someone address this issue. May be Ajax Future Release might give the solution for this problem, but what about the current
developments which is already undergone in AjaxControlToolkit.

Guys, I found a trick to solve this issue. So I would like to share it with you all, how I made the ModalPopup extender to postback and perform the code-behind operation. Also how I set the focus to the TextBox control in ModalPopup. Then click when you the OK button on the ModalPopup, it will postback.To achieve this, in your MS Visual Studio, open a new Ajax Enabled Website. Add a Master Page and a Default Page. Set the MasterPageFile property of the Default page to the point to the Master Page. To the Default.aspx page, add a Hyperlink control, a Label and a Panel control. Inside the Panel, add a Textbox and two Buttons, one to OK and another for Cancel.

The actual flow is, when you click on the Hyperlink the ModalPopup has to open, the focus should be on the Textbox. You have to type some text in the Textbox, then click on the OK button. The page will get postback and your typed text will appear in the Label control on the main page. That’s it.

Now we will see how to do it. First set the TargetControlId of the ModalPopup extender to the Hyperlink name. Then set the CancelControlID to the Cancel Button, OkControlID to the OK Button and the PopupControlID to the Panel1 in your Page. Set the BackgroundCssClass property as to the following style class.

.modalBackground
{
 background-color:<Your Desired Color>;
 filter:alpha(opacity=70);
 opacity:0.7;
}

This style sheet class keeps the background effect dull. So now you can run your application. When you click the HyperLink, the ModalPopup comes to action. Sure it will impress you lot. No postback and no focus on your Textbox, only cancel will function. Now we can see how to set focus on the Textbox.

<script>
        var clientid;
        function fnSetFocus(txtClientId)
        {
        	clientid=txtClientId;
        	setTimeout("fnFocus()",1000);

        }

        function fnFocus()
        {
            eval("document.getElementById('"+clientid+"').focus()");
        }

</script>

On your aspx page, copy and paste the above two javascript functions. As we are using the MasterPage, the client id of the TextBox will be changed. So the function fnSetFocus(txtClientId) is used to the assign the ClientId of the Textbox to a local variable. Then the setTimeout calls another function fnFocus(). This function will be called exactly after 1 second, that is after the ModalPopup gets popped up, then this function is responsible to set the focus on the Textbox. And in your code behind’s page load event, you have to add a line of code as follows.

HyperLink1.Attributes.Add(“onclick”, “fnSetFocus(‘”+TextBox1.ClientID+”‘);”);

This line adds the javascript function on the client-side click of the HyperLink. Now run your application, sure after the ModalPopup gets on screen, exactly after a second you can see the focus on the Textbox. Even you can adjust the timings to half second. Next, we will concentrate how to perform postback action when the OK button on the ModalPopup is clicked.First, add a javascript function to call the __dopostback event. The function must look like the below.

function fnClickOK(sender, e) {
__doPostBack(sender,e);
}

Then in your code-behind, you must assign the OnClientClick property of the OK Button on the page load event. The code is
Button2.OnClientClick = String.Format(“fnClickOK(‘{0}’,'{1}’)”, Button2.UniqueID, “”);

When the OK button is clicked, postback should perform some action. So let us assign the Textbox value to the Label control. Add the following piece of code in your OK Button’s onclick event.

Label1.Text = "You Type "+TextBox1.Text;

That’s it. Now run your application. When you click the Hyperlink, the ModalPopup will appear. Next you can see the focus on the TextBox. Type your name in the Textbox and press the OK Button. I’m sure your Name will be assigned in the Label. This I tried based on my knowledge, and its a trick to bring focus and postback. If you find better way to acheive this I welcome you to post that article here. Thanks.

call a javascript within in a button control
btnAdd.Attributes.Add(“onclick”,”return javascriptfunctionname();”);

//javascriptfunctionname name the function u need to call
Set the Body tag in your page/master page to runat=”

server” and an id=”MainBody”.

Put the script tag in your page like you normally would with any HTML file
<script src=”popup.js”  type=”text/javascript”></script>

Then in the code behind attach the onload attribute to the body tag .

protected void Page_Load(object sender, EventArgs e)
{
MasterPageBodyTag = (HtmlGenericControl)Page.Master.FindControl(“MainBody”);
MasterPageBodyTag.Attributes.Add(“Onload”, “Popup()”);
}

The task of sending e-mails has become much easier in ASP.NET. In previous versions of ASP we either used a third party component or the limited functionality of CDONTS component for sending emails. The .NET framework provides simpler but powerful class libraries for sending emails. These classes are in the System.Web.Mail Namespace.

Following are the classes and their use :

  • MailAttachment To construct an email attachment.
  • MailMessage To construct an email message.
  • SmtpMail To send an email attachment using the SMTP mail service.
  • Usage:

    Most feature-rich mailing component, Supports message queueing, embedded images, secure mail, authentication. In order to access these classes we have to import the System.Web.Mail namespace within our ASP.NET page using the import directive as shown :<% @ Import NameSpace = “System.Web.Mail” %>

  • Then we construct an email message by creating an Instance of the MailMessage class as shown :

MailMessage MyMail = new MailMessage();

  • The MailMessage class has various properties which need to be set before sending emails.Following table shows some of the important properties of the MailMessage class :
  • Property Description Attachments List of attachments that is sent with the email. Body Body of the email message. From Email address of the sender. Subject Subject line of the email message. To Email address of the recipient. To send an attachment with email we need to create an instance of the MailAttachment class. We pass the full path of the file to be attached as an argument to the constructor of MailAttachment class as shown :

MailAttachment MyAttachment = new MailAttachment(“C:\\My Folder\\MyFile.txt”);

Note : The file name passed should be valid file which exists on the server.

  • This MailAttachment instance is then attached to the mail by using the Attachment property of the Mail class as shown:

MyMail.Attachments.Add(MyAttachment);

  • Finally we send the email using the Send() method of the SmtpMail Class as shown :

SmtpMail.Send(MyMail);

SQL Helper Class

This article is about SQL Server Helper class in C#. This class contains all the method which can be used to get data from database (using Stored Procedures) and also to insert and update data in database. It contains the methods which return different objects like Dataset, SqlDataReader, Integer etc at the end of the method. It also contains methods for adding parameter to SQL Command with different parameters and contains the method to set the parameter value. Here is the complete code for SQL Helper class. //*************************************

public class SqlHelper

{

private string mstr_ConnectionString;

private SqlConnection mobj_SqlConnection;

private SqlCommand mobj_SqlCommand;

private int mint_CommandTimeout = 30;

public enum ExpectedType

{

StringType = 0, NumberType = 1, DateType = 2, BooleanType = 3, ImageType = 4;

}

public SqlHelper()

{

try

{

mstr_ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); mobj_SqlConnection = new SqlConnection(mstr_ConnectionString); mobj_SqlCommand = new SqlCommand(); mobj_SqlCommand.CommandTimeout = mint_CommandTimeout; mobj_SqlCommand.Connection = mobj_SqlConnection; //ParseConnectionString();

}

catch (Exception ex)

{

throw new Exception(”Error initializing data class.” + Environment.NewLine + ex.Message);

}

}

public void Dispose()

{

try

{

//Clean Up Connection Object

if (mobj_SqlConnection != null)

{

if (mobj_SqlConnection.State != ConnectionState.Closed)

{

mobj_SqlConnection.Close();

}

mobj_SqlConnection.Dispose();

}

//Clean Up Command Object

if (mobj_SqlCommand != null)

{

mobj_SqlCommand.Dispose();

}

}

catch (Exception ex)

{

throw new Exception(”Error disposing data class.” + Environment.NewLine + ex.Message);

}

}

public void CloseConnection()

{

if (mobj_SqlConnection.State != ConnectionState.Closed) mobj_SqlConnection.Close();

}

public int GetExecuteScalarByCommand(string Command)

{

object identity = 0;

try

{

mobj_SqlCommand.CommandText = Command; mobj_SqlCommand.CommandTimeout = mint_CommandTimeout; mobj_SqlCommand.CommandType = CommandType.StoredProcedure; mobj_SqlConnection.Open(); mobj_SqlCommand.Connection = mobj_SqlConnection; identity = mobj_SqlCommand.ExecuteScalar(); CloseConnection();

}

catch (Exception ex)

{

CloseConnection();

throw ex;

}

return Convert.ToInt32(identity);

}

public void GetExecuteNonQueryByCommand(string Command)

{

try

{

mobj_SqlCommand.CommandText = Command; mobj_SqlCommand.CommandTimeout = mint_CommandTimeout; mobj_SqlCommand.CommandType = CommandType.StoredProcedure; mobj_SqlConnection.Open(); mobj_SqlCommand.Connection = mobj_SqlConnection; mobj_SqlCommand.ExecuteNonQuery(); CloseConnection();

}

catch (Exception ex)

{

CloseConnection();

throw ex;

}

}

public DataSet GetDatasetByCommand(string Command)

{

try

{

mobj_SqlCommand.CommandText = Command; mobj_SqlCommand.CommandTimeout = mint_CommandTimeout; mobj_SqlCommand.CommandType = CommandType.StoredProcedure; mobj_SqlConnection.Open(); SqlDataAdapter adpt = new SqlDataAdapter(mobj_SqlCommand); DataSet ds = new DataSet(); adpt.Fill(ds);

return ds;

}

catch (Exception ex)

{

throw ex;

}

finally

{

CloseConnection();

}

}

public SqlDataReader GetReaderBySQL(string strSQL)

{

mobj_SqlConnection.Open();

try

{

SqlCommand myCommand = new SqlCommand(strSQL, mobj_SqlConnection);

return myCommand.ExecuteReader();

}

catch (Exception ex)

{

CloseConnection();

throw ex;

}

}

public SqlDataReader GetReaderByCmd(string Command)

{

SqlDataReader objSqlDataReader = null;

try

{

mobj_SqlCommand.CommandText = Command; mobj_SqlCommand.CommandType = CommandType.StoredProcedure; mobj_SqlCommand.CommandTimeout = mint_CommandTimeout; mobj_SqlConnection.Open();

mobj_SqlCommand.Connection = mobj_SqlConnection;

objSqlDataReader = mobj_SqlCommand.ExecuteReader() ;

return objSqlDataReader;

}

catch (Exception ex)

{

CloseConnection();

throw ex;

}

}

public void AddParameterToSQLCommand(string ParameterName, SqlDbType ParameterType)

{

try

{

mobj_SqlCommand.Parameters.Add(new SqlParameter(ParameterName, ParameterType));

}

catch (Exception ex)

{

throw ex;

}

}

public void AddParameterToSQLCommand(string ParameterName, SqlDbType ParameterType,int ParameterSize)

{

try

{

mobj_SqlCommand.Parameters.Add(new SqlParameter(ParameterName, ParameterType, ParameterSize));

}

catch (Exception ex)

{

throw ex;

}

}

public void SetSQLCommandParameterValue(string ParameterName, object Value)

{

try

{

mobj_SqlCommand.Parameters[ParameterName].Value = Value;

}

catch (Exception ex)

{

throw ex;

}

}

}

//*************************************

Here the AddParameterToSQL Command contains 1 overload method with 3 parameters. The first method is for the datatypes whose parameter size do not require at the time of assigning. Only datatype should be given. This method can be used for DataTypes like Int, Bit, Money, Double, Decimal etc. And the other method contains 3 parameters – ParameterName, DataType and its size. This method can be used for specially VARCHAR kind of datatypes. Also in all the method the string Parameter (Command or strSQL) is the name of the Stored Procedure which you are using to get or insert the data. Hope this article helps you somewhere sometime in your applications.

Ajax Preloader

This script will help to disable your page for a minute when your page is doing processing. and will show a loading message to you until the page processing doesn’t finish.

Complete the following point:

1. Script:-

Write the following java script in the heading tag:

<script language=”javascript” type=”text/javascript”>
var ModalProgress =’<%= ModalProgress.ClientID %>’
</script>

2. Place the following code after the scriptManager code:

<ajaxToolkit:ModalPopupExtender ID=”ModalProgress” PopupControlID=”PNL” TargetControlID=”PNL” runat=”server”>
</ajaxToolkit:ModalPopupExtender>
<script type=”text/javascript” language=”javascript”>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginReq);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endReq);
function beginReq(sender, args)
{ // shows the Popup
$find(ModalProgress).show();

}
function endReq(sender, args)
{ // shows the Popup
$find(ModalProgress).hide();
}

</script>

<asp:Panel ID=”PNL” runat=”server” Style=”border-right: black 2px solid; padding-right: 20px;
border-top: black 2px solid; display: none; padding-left: 20px; padding-bottom: 20px;
border-left: black 2px solid; width: 200px; padding-top: 20px; border-bottom: black 2px solid;
background-color: white”>
&nbsp;&nbsp;
<table style=”width: 100%”>
<tr>
<td style=”width: 12px; height: 23px”>
<img src=”../images/loading.gif” /></td>
<td style=”width: 100px; height: 23px”>
Loading …………………..</td>
</tr>
</table>
</asp:Panel>

Write the 2nd point code top of the page but after the script manager. If u doesn’t have script manager on page. but it is on master page. then u can place the code in master page.

One of the best practices in ASP.NET is to save your database connection strings in the Web.config file instead of hard-coding it in your code. This allows you to change database servers easily, without needing to modify your code. As an additional protection, it is always better to use integrated Windows security to access your database, rather than using SQL Server authentication, and thus including your
SQL server credentials in the connection string. Either way, it’s not such a good idea to save your connection strings as plain text in Web.config — you should ideally encrypt the connection strings so that it leaves no chance for a potential hacker to easily get more information about your database server.

In ASP.NET 2.0, Microsoft has taken this further by allowing you to encrypt the connection strings in Web.config, all without much plumbing on your part.
Using the DataProtectionConfigurationProvider and RSAProtectedConfigurationProvider for Encryption

To see how you can encrypt the connection strings stored in the Web.config file, you will configure a GridView control to bind to an SqlDataSource control. The connection string used by the SqlDataSource control is saved in the Web.config file. You then encrypt the connection strings, using the two Protection Configuration Providers available in .NET 2.0.

The Web.config file will now contain the connection string:

Make a class file or do work in a page code, write the following code:-

using System.Configuration;
using System.Web.Configuration;

public void Encrypt()
{
// Open web.config file
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// indicate the section to protect
ConfigurationSection configSection = config.GetSection(”connectionStrings”);
// specify the protection provider
configSection.SectionInformation.ProtectSection(”RSAProtectedConfigurationProvider”);
// apply the protection and update
config.Save();
}

public void Decrypt()
{
Configuration config=WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection configsection=config.GetSection(”connectionStrings”);
configsection.SectionInformation.UnprotectSection();
config.Save();
}

When your write this code in page code then Once call the encrypt method in the page load and start close the page. and You will now see iin the web.config configrationstring. It is in encrypted form.

And if you want to reverse back then call the decrypt method.

I think this will helpful to encrypt the connection string in web.config file.

Ajax Professional

Overview: Ajax.NET Professional (AjaxPro) is one of the first AJAX frameworks available for Microsoft ASP.NET and is working with .NET 1.1 and 2.0. The framework will create proxy classes that are used on client-side JavaScript to invoke methods on the web server with full data type support working on all common web browsers including mobile devices. Return your own classes, structures, DataSets, enums,… as you are doing directly in .NET.

If you are using Visual Studio .NET 2005 you can install the Visual Studio Project Template (that is included in the download release package). There is a project template for C# and VB.NET.

When using Visual Studio .NET 2003 or any other editor you download the latest release package and extract the files to a temporary folder. You will find following libraries:

  • AjaxPro.dll
  • AjaxPro.2.dll
  • AjaxPro.JSON.dll
  • AjaxPro.JSON.2.dll

The libraries ending with .2.dll are for use with .NET version 2.0. The AjaxPro.JSON DLLs offer only JSON <-> .NET serialization/deserialization, there is no Ajax support included.

Usage

Step 1: Create a new blank website.

Step 2: Add a reference to the AjaxPro.2.dll (for .NET 1.1 Framework use AjaxPro.dll).

Step 3: Add following lines to your web.config:

<?xml version=”1.0″ encoding=”utf-8″ ?>

<configuration>

<system.web>

<httpHandlers>

<add verb=”POST,GET” path=”ajaxpro/*.ashx”/>

</httpHandlers>

[...]

</system.web>

</configuration>

Step 4: Now, you have to mark your .NET methods with an AjaxMethod attribute:

[AjaxPro.AjaxMethod]

public DateTime getTime()

{

return DateTime.Now;

}

Step 5: To use the .NET method on the client-side JavaScript you have to register the methods, this will be done to register a complete class to Ajax.NET:

namespace demo

{

public class democlass

{

protected void Page_Load(object sender, EventArgs e)

{

AjaxPro.Utility.RegisterTypeForAjax(typeof(democlass));

}

[AjaxPro.AjaxMethod]

public DateTime getTime()

{

return DateTime.Now;

}

}

}

Step 6: Now at last, just add the javascript function to your webpage html source.

function getTime()

{

demo.democlass.getTime(otherFunction);  // asynchronous call

}

// This method will be called after the method has been executed

// and the result has been sent to the client.

function otherFunction (res)

{

alert(res.value);

}

Hope this article would help you to use Ajax Professional to your website.

You can return the values pair in dataset object using Ajax.NET Professional (AjaxPro). Ajax.Net
professional capable of Return your data into form of followings:

  • User own classes types,
  • Structures,
  • DataSets,
  • Enums,
  • .. as you are doing directly in .NET.

To return a Dataset object & access it on client side, you have to do some minor changes in client &
server side both.

  • Changes on server side

[AjaxMethod]
public DataSet GetDataSet()
{
DataSet ds = new DataSet();
[..] // fill dataset here
return ds;
}

  • On the client-side JavaScript code you get a new Ajax.Web.DataSet object. Using this object you can get the columns and rows for each table inside the dataset.

function sample()

{

demo.democlass.DataSets.demo.GetDataSet(_callback1);

}

function _callback1(res)

{

var cols = res.value.Tables[0].Columns.length;

var rows = res.value.Tables[0].Rows.length;

alert(“Dataset has following no. of Coloumns ”cols + ” and ” + rows + ” Rows.”);

}

Hope this article would help you.

MS-DOS Commands List

MS-DOS Command Line Overview

Below is a listing of each of the MS-DOS commands currently listed on Computer and a brief explanation of what each of the commands do.

Command Description

append Causes MS-DOS to look in other directories when editing a file or running a command.

assign Assign a drive letter to an alternate letter.

assoc View the file associations.

at Schedule a time to execute commands or programs.

attrib Display and change file attributes.

batch

Recovery console command that executes a series of commands in a file.

bootcfg

Recovery console command that allows a user to view, modify, and rebuild the boot.ini

break

Enable / disable CTRL + C feature.

cacls

View and modify file ACL’s.

call

Calls a batch file from another batch file.

cd

Changes directories.

chdir

Changes directories.

chdsk

Check the hard disk drive running FAT for errors.

chkntfs

Check the hard disk drive running NTFS for errors.

choice

Specify a listing of multiple options within a batch file.

cls

Clears the screen.

cmd

Opens the command interpreter.

color

Easily change the foreground and background color of the MS-DOS window.

command

Opens the command interpreter.

comp

Compares files.

compact

Compresses and uncompress files.

control

Open Control Panel icons from the MS-DOS prompt.

convert

Convert FAT to NTFS.

copy

Copy one or more files to an alternate location.

date

View or change the systems date.

debug

Debug utility to create assembly programs to modify hardware settings.

defrag

Re-arrange the hard disk drive to help with loading programs.

del

Deletes one or more files.

delete

Recovery console command that deletes a file.

deltree

Deletes one or more files and/or directories.

dir

List the contents of one or more directory.

diskcomp

Compare a disk with another disk.

diskcopy

Copy the contents of one disk and place them on another disk.

doskey

Command to view and execute commands that have been run in the past.

dosshell

A GUI to help with early MS-DOS users.

echo

Displays messages and enables and disables echo.

edit

View and edit files.

edlin

View and edit files.

erase

Erase files from computer.

exit

Exit from the command interpreter.

fc

Compare files.

fdisk

Utility used to create partitions on the hard disk drive.

find

Search for text within a file.

findstr

Searches for a string of text within a file.

fixboot

Writes a new boot sector.

fixmbr

Writes a new boot record to a disk drive.

for

Boolean used in batch files.

format

Command to erase and prepare a disk drive.

ftp

Command to connect and operate on a FTP server.

ftype

Displays or modifies file types used in file extension associations.

help

Display a listing of commands and brief explanation.

if

Allows for batch files to perform conditional processing.

ipconfig

Network command to view network adapter settings and assigned values.

keyb

Change layout of keyboard.

label

Change the label of a disk drive.

lh

Load a device driver in to high memory.

listsvc

Recovery console command that displays the services and drivers.

logoff

Logoff the currently profile using the computer.

map

Displays the device name of a drive.

md

Command to create a new directory.

mem

Display memory on system.

mkdir

Command to create a new directory.

mode

Modify the port or display settings.

more

Display one page at a time.

move

Move one or more files from one directory to another directory.

net

Update, fix, or view the network or network settings

netsh

Configure dynamic and static network information from MS-DOS.

netstat

Display the TCP/IP network protocol statistics and information.

nlsfunc

Load country specific information.

nslookup

Look up an IP address of a domain or host on a network.

path

View and modify the computers path location.

ping

Test / send information to another network computer or network device.

print

Prints data to a printer port.

prompt

View and change the MS-DOS prompt.

pushd

Stores a directory or network path in memory so it can be returned to at any time.

rd

Removes an empty directory.

ren

Renames a file or directory.

rename

Renames a file or directory.

rmdir

Removes an empty directory.

scandisk

Run the scandisk utility.

scanreg

Scan registry and recover registry from errors.

shutdown

Shutdown the computer from the MS-DOS prompt.

smartdrv

Create a disk cache in conventional memory or extended memory.

sort

Sorts the input and displays the output to the screen.

start

Start a separate window in Windows from the MS-DOS prompt.

telnet

Telnet to another computer / device from the prompt.

time

View or modify the system time.

title

Change the title of their MS-DOS window.

tracert

Visually view a network packets route across a network.

tree

View a visual tree of the hard disk drive.

type

Display the contents of a file.

undelete

Undelete a file that has been deleted.

unformat

Unformat a hard disk drive.

ver

Display the version information.

vol

Displays the volume information about the designated drive.

xcopy

Copy multiple files, directories, and/or drives from one location to another.

Sql Server Indexes

All SQL Server indexes are B-Trees. There is a single root page at the top of the tree, branching out into N number of pages at each intermediate level until it reaches the bottom, or leaf level, of the index. The index tree is traversed by following pointers from the upper-level pages down through the lower-level pages. In addition, each index level is a separate page chain.There may be many intermediate levels in an index. The number of levels is dependent on the index key width, the type of index, and the number of rows and/or pages in the table. The number of levels is important in relation to index performance.

Nonclustered Indexes: A nonclustered index is analogous to an index in a textbook. The data is stored in one place, the index in another, with pointers to the storage location of the data.

Similar to the way you use an index in a book, Microsoft® SQL Server™ 2000 searches for a data value by searching the nonclustered index to find the location of the data value in the table and then retrieves the data directly from that location. This makes nonclustered indexes the optimal choice for exact match queries because the index contains entries describing the exact location in the table of the data values being searched for in the queries. If the underlying table is sorted using a clustered index, the location is the clustering key value; otherwise, the location is the row ID (RID) comprised of the file number, page number, and slot number of the row

Nonclustered indexes usage:
• Columns that contain a large number of distinct values, such as a combination of last name and first name (if a clustered index is used for other columns). If there are very few distinct values, such as only 1 and 0, most queries will not use the index because a table scan is usually more efficient.
• Queries that do not return large result sets.
• Columns frequently involved in search conditions of a query (WHERE clause) that return exact matches.
• Decision-support-system applications for which joins and grouping are frequently required. Create multiple nonclustered indexes on columns involved in join and grouping operations, and a clustered index on any foreign key columns.
• Covering all columns from one table in a given query. This eliminates accessing the table or clustered index altogether.

Clustered Indexes: A clustered index determines the physical order of data in a table. A clustered index is analogous to a telephone directory, which arranges data by last name. Because the clustered index dictates the physical storage order of the data in the table, a table can contain only one clustered index. However, the index can comprise multiple columns (a composite index), like the way a telephone directory is organized by last name and first name.

A clustered index is particularly efficient on columns that are often searched for ranges of values. After the row with the first value is found using the clustered index, rows with subsequent indexed values are guaranteed to be physically adjacent. Clustered indexes are also efficient for finding a specific row when the indexed value is unique. For example, the fastest way to find a particular employee using the unique employee ID column emp_id is to create a clustered index or PRIMARY KEY constraint on the emp_id column.
Note: PRIMARY KEY constraints create clustered indexes automatically if no clustered index already exists on the table and a nonclustered index is not specified when you create the PRIMARY KEY constraint.

Clustered index usage:
• Columns that contain a large number of distinct values.
• Queries that return a range of values using operators such as BETWEEN, >, >=, <, and <=.
• Columns that are accessed sequentially.
• Queries that return large result sets.
• Columns that are frequently accessed by queries involving join or GROUP BY clauses; typically these are foreign key columns. An index on the column(s) specified in the ORDER BY or GROUP BY clause eliminates the need for SQL Server to sort the data because the rows are already sorted. This improves query performance.

It took me a while to find out how to send email using GoDaddy’s SMTP server. It seems to look for the host name as the credentials and limit 200 emails per day.
view source

static bool SendEmail(string ToAddr,string senderEmail, string Subject, string Body)
{
bool result;

try
{
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress(“info@domain.com”, senderEmail);
Msg.To.Add(ToAddr);

Msg.Subject = “Subject”;
Msg.Body = “Body”;

Msg.BodyEncoding = System.Text.Encoding.UTF8;
Msg.Priority = MailPriority.High;
Msg.IsBodyHtml = true;

SmtpClient SMTP = new SmtpClient(“relay-hosting.secureserver.net”, 25);
SMTP.Send(Msg);

result = true;
}
catch (Exception Err)
{
result = false;
}

return result;
}

Enjoy

AJAX Accordion

I used the AJAX Accordion to bind a dynamic data into the content template. Since the data is dynamically bind, I wish to detect is I find there are empty field at the Guild Information, then I would like the labels and link to be hide. It will be better to hide it so that the users are unable to click the link which will redirect to another page with passing querystrings. The solution given was using the OnItemDataBound. Here is the script.

protected void acdGuild_OnItemDataBound(object sender, AjaxControlToolkit.AccordionItemEventArgs e)

{

if (e.ItemType == AjaxControlToolkit.AccordionItemType.Content)

{

int intGuildId= Convert.ToInt32(((DataRowView)e.AccordionItem.DataItem)["gld_id"].ToString());

if (intGuildId == 0)

{ ((System.Web.UI.HtmlControls.HtmlTableCell)e.AccordionItem.FindControl(”tdGuild”)).Visible = false; ((System.Web.UI.HtmlControls.HtmlTableCell)e.AccordionItem.FindControl(”tdView”)).Visible = false;

}

}

}

Some programmer require to rollback and commit the transaction of the sqlserver according to the coding. That time this code will help you….

Imports System
Imports System.Data
Imports System.Data.SqlClient

public class MainClass
Shared Sub Main()
Dim thisConnection As New SqlConnection(”server=(local)\SQLEXPRESS;” & _
“integrated security=sspi;database=MyDatabase”)

‘ SQL Delete Commands
Dim sql As String = “DELETE FROM Employee ” & _
“WHERE ID = 10″

‘ Create command
Dim thisCommand As New SqlCommand(sql, thisConnection)

‘ Create Transaction
Dim thisTransaction As SqlTransaction

Try
‘ Open Connection
thisConnection.Open()

‘ Begin transaction and attach it to command
thisTransaction = thisConnection.BeginTransaction()
thisCommand.Transaction = thisTransaction

‘ Run delete command
thisCommand.ExecuteNonQuery()

‘ Commit transaction
thisTransaction.Commit()

‘ Display success
Console.WriteLine(”Transaction Committed. Data Deleted”)

Catch ex As Exception
‘ Roll back transaction
thisTransaction.Rollback()

Console.WriteLine(”Transaction rolled back : ” & ex.Message)

Finally
‘ Close Connection
thisConnection.Close()

End Try
End Sub
End Class

This source code is using the javascript to display the textbox when a radiobutton is clicked. This applies when a user clicks the other specify radio button and the javascript is called to display the textbox. Then, the textbox will be validated if empty.

//Javascript

function InterfaceControl1(id)

{

var radioQ1 = document.getElementsByName(id);

for (var ii = 0; ii < radioQ1;i++)

{

if (radioQ1[ii].checked)

{

if (radioQ1[ii].value == “O”)

{

document.getElementById(”txtQ1″).style.display = ‘inline’;

//to show

}

else

{

document.getElementById(”txtQ1″).style.display = ‘none’;

//to hide

}

}

}

}

The design code is as below:
<asp:RadioButtonList ID=”rbtnQ1″ runat=”server” RepeatColumns=”2″ RepeatDirection=”Horizontal” CssClass=”chkBoxList” OnClick=”javascript:InterfaceControl1(’rbtnQ1′);”>
<asp:ListItem Text=”SteelSeries” Value=”SteelSeries”></asp:ListItem>
<asp:ListItem Text=”Razer” Value=”Razer”></asp:ListItem>
<asp:ListItem Text=”Logitech” Value=”Logitech”></asp:ListItem>
<asp:ListItem Text=”Microsoft” Value=”Microsoft”></asp:ListItem>
<asp:ListItem Text=”Others (Please specify)” Value=”O”></asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID=”txtQ1″ runat=”server” style=”display:none;” MaxLength=”50″ ValidationGroup=”vdgSubmit”></asp:TextBox>
<asp:RequiredFieldValidator ID=”rfvQ1″ runat=”server” ControlToValidate=”txtQ1″ ErrorMessage=”Please fill in” ForeColor=”Red” ></asp:RequiredFieldValidator>

Encryption & Decryption in asp.net

/// <summary>
/// This class provide static methods for encryption and decryption.
/// </summary>

public class Encrption
{

/// <summary>
/// Method which does the encryption using Rijndeal algorithm
/// </summary>
/// <param name=”InputText”>Data to be encrypted</param>
/// <param name=”Password”>The string to used for making the key.The same string
/// should be used for making the decrpt key</param>
/// <returns>Encrypted Data</returns>
public static string EncryptString(string InputText, string Password)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();

byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());

//This class uses an extension of the PBKDF1 algorithm defined in the PKCS#5 v2.0
//standard to derive bytes suitable for use as key material from a password.
//The standard is documented in IETF RRC 2898.

PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

//Creates a symmetric encryptor object.
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();

//Defines a stream that links data streams to cryptographic transformations
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(PlainText, 0, PlainText.Length);

//Writes the final state and clears the buffer
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string EncryptedData = Convert.ToBase64String(CipherBytes);
return EncryptedData;
}

/// <summary>
/// Method which does the encryption using Rijndeal algorithm.This is for decrypting the data
/// which has orginally being encrypted using the above method
/// </summary>
/// <param name=”InputText”>The encrypted data which has to be decrypted</param>
/// <param name=”Password”>The string which has been used for encrypting.The same string
/// should be used for making the decrypt key</param>
/// <returns>Decrypted Data</returns>

public static string DecryptString(string InputText, string Password)
{

RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] EncryptedData = Convert.FromBase64String(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());

//Making of the key for decryption
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);

//Creates a symmetric Rijndael decryptor object.
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(EncryptedData);

//Defines the cryptographics stream for decryption.THe stream contains decrpted data
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] PlainText = new byte[EncryptedData.Length];
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();

//Converting to string
string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
return DecryptedData;
}

}

Create,Read,Delete Cookies in Asp.net

A cookie is a small bit of text file that browser creates and stores on your machine (hard drive). Cookie is a small piece of information stored as a string. Web server sends the cookie and browser stores it, next time server returns that cookie.Cookies are mostly used to store the information about the user. Cookies are stores on the client side.

Here i m going to explain you by providing example of Remember me Code :

Step 1 : if check box is checked for “Remember Me” then create cookie else Delete it.

if (chkRememberMe.Checked == true)
{
//Create Cookie to Store AdminInfo
HttpCookie aCookie = new HttpCookie(”AdminInfo”);
aCookie.Values["userName"] = txtUsername.Text;
aCookie.Values["Password"] = txtPassword.Text;
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(aCookie);
}
else
{
//Delete Cookie
HttpCookie aCookie = new HttpCookie(”AdminInfo”);
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie);
}

Step 2 : now check cookie is null or not in page load event & set username & password from cookie

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["AdminInfo"] != null)
{
txtUsername.Text = Request.Cookies["AdminInfo"]["userName"] == null ? null : Request.Cookies["AdminInfo"]["userName"].ToString();
string pwd = Request.Cookies["AdminInfo"]["Password"] == null ? null : Request.Cookies["AdminInfo"]["Password"].ToString();
txtPassword.Attributes.Add(”value”, pwd);
}
}

}

In this article, I am explaining how to use Google Map API with ASP.Net. First you need to register with the Google Maps API here and get your key from Google.

Once you get the key. You can display Google Maps on you Website using the following script that you get from Google.

<head id=”Head1″ runat=”server”>

<title>Google Maps Example</title>

<script type=”text/javascript”

src=”http://www.google.com/jsapi?key=xxxxxxx”></script>

<script type=”text/javascript”>

google.load(”maps”, “2″);

// Call this function when the page has been loaded

function initialize() {

var map = new google.maps.Map2(document.getElementById(”map”));

map.setCenter(new google.maps.LatLng(”<%=lat%>”, “<%=lon%>”), 5);

var point = new GPoint(”<%=lon%>”, “<%=lat%>”);

var marker = new GMarker(point);

map.addOverlay(marker);

map.addControl(new GLargeMapControl());

}

google.setOnLoadCallback(initialize);

</script>

</head>

<body>

<form id=”form1″ runat=”server”>

<div>

<div id=”map” style=”width: 400px; height: 400px”></div>

</div>

</form>

</body>

As you can see I have placed the script in the Head section of the HTML page. The above script gives your location on the map based on latitude and longitude. The map is loaded in the div with id map

Now to get Latitude and Longitude we will take help of my previous article Find Visitor’s Geographic Location using IP Address in ASP.Net. You’ll notice I have used to server variables lat (latitude) and lon (longitude) whose values come from server.

Based on the IP address the web service returns the latitude and longitude refer the XML below

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<Response>

<Status>true</Status>

<Ip>122.169.8.137</Ip>

<CountryCode>IN</CountryCode>

<CountryName>India</CountryName>

<RegionCode>16</RegionCode>

<RegionName>Maharashtra</RegionName>

<City>Bombay</City>

<ZipCode />

<Latitude>18.975</Latitude>

<Longitude>72.8258</Longitude>

</Response>

code for vb page

Protected lat As String, lon As String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)  Handles Me.Load

Dim ipaddress As String

ipaddress = Request.ServerVariables(”HTTP_X_FORWARDED_FOR”)

If ipaddress = “” OrElse ipaddress Is Nothing Then

ipaddress = Request.ServerVariables(”REMOTE_ADDR”)

End If

Dim dt As DataTable = GetLocation(ipaddress)

If dt IsNot Nothing Then

If dt.Rows.Count > 0 Then

lat = dt.Rows(0)(”Latitude”).ToString()

lon = dt.Rows(0)(”Longitude”).ToString()

End If

End If

End Sub

Private Function GetLocation(ByVal ipaddress As String) As DataTable

‘Create a WebRequest

Dim rssReq As WebRequest = WebRequest. _

Create(”http://freegeoip.appspot.com/xml/” & ipaddress)

‘Create a Proxy

Dim px As New WebProxy(”http://freegeoip.appspot.com/xml/” _

& ipaddress, True)

‘Assign the proxy to the WebRequest

rssReq.Proxy = px

‘Set the timeout in Seconds for the WebRequest

rssReq.Timeout = 2000

Try

‘Get the WebResponse

Dim rep As WebResponse = rssReq.GetResponse()

‘Read the Response in a XMLTextReader

Dim xtr As New XmlTextReader(rep.GetResponseStream())

‘Create a new DataSet

Dim ds As New DataSet()

‘Read the Response into the DataSet

ds.ReadXml(xtr)

Return ds.Tables(0)

Catch

Return Nothing

End Try

End Function

As you can see in the above code snippet I get the latitude and longitude from the XML Response in the variables lat and lon which I’ll used to pass values to the JavaScript function of the Google API.

Replace First Occurrence of a String in C#

I had a need to replace the first occurrence of a substring within a string, and C# doesn’t seem to have a way of doing this with String methods.

So, I wrote my own code:

 

public static string ReplaceStringFirstOccurrance(string original, string oldValue, string newValue){

if (String.IsNullOrEmpty(original)) return String.Empty;
if (String.IsNullOrEmpty(oldValue)) return original;
if (String.IsNullOrEmpty(newValue)) return original;

int loc = original.IndexOf(oldValue);

return loc == -1 ? original : original.Remove(loc, oldValue.Length).Insert(loc, newValue);

}

 

Hope this would be beneficial for you all. Cheer’s !!!   happy coding.

In this post, I’ll tell you how to display row number in asp:gridview control

Take a look:-

<asp:GridView ID=”GridView1″ runat=”server”>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Sr.#
</HeaderTemplate>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”Name” HeaderText=”Name” />
<asp:BoundField DataField=”Email” HeaderText=”Email” />
</Columns>
</asp:GridView>

In your code behind file:-

protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = fetchData().ToList<clsData>();
GridView1.DataBind();
}


public List<clsData> fetchData()
{
return new List<clsData>()
{
new clsData{ Name=“Aamir Hasan”,Email=“abc@abc.com”,},
new clsData{ Name=“Awais Ahmed”,Email=“bcd@bcd.com”},
new clsData{ Name=“Mahwish khan”,Email=“cde@cde.com”},
new clsData{ Name=“Gill”,Email=“def@def.com”},
new clsData{ Name=“Saba khan”,Email=“efg@efg.com”},
new clsData{ Name=“adnan”,Name=“fgh@fgh.com”},
};
}

public class clsData
{
public String Name { get; set; }
public String Name { get; set; }
}

 

Now run your webpage. I think this will help you.

Q. Whats is Parallel Computing?

Ans. To take advantage of multiple cores (that is, CPUs or processors) you can parallelize your code so that it will be distributed across multiple processors. In the past, parallelization required low-level manipulation of threads and locks, but Visual Studio 2010 and the .NET Framework 4 enhances the support for parallel programming by providing a new runtime, new class library types, and new diagnostic tools. These features simplify parallel development so that you can write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool.

The new System.Threading.Tasks namespace and other related types support this new model.

Q. What is BigInteger and When would you use that?

Ans. BigInteger, which is a part of System.Numerics Namespace is a great enhancement over Byte and Int32 datatypes. It is a nonprimitive integral type that supports arbitrarily large signed integers. Unlike Byte and Int32 types, BigInteger does not include a Minvalue and MaxValue property, so can be used to store large integer values.

Q. What other than BigInteger has been introduced in System.Numerics Namespace?

Ans.Complex types,which represents a complex number has been Introduced. a complex number is a number in the form a + bi, where a is the real part, and b is the imaginary part.

Q. How do you assign a Value to a Complex Number.

Ans.You can assign a value to a complex number in few different ways.
1. By passing two Double values to its constructor. The first value represents the real part of the complex number, and the second value represents its imaginary part.
2. By assigning a Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, or Double value to a Complex object. The value becomes the real part of the complex number, and its imaginary part equals 0.

E.g Complex c1 = new Complex(12, 6);
Console.WriteLine(c1);
OutPut – (12, 6)

Q. How has exception hand changed in .Net Framework 4.0

Ans.A New Namespace System.Runtime.ExceptionServices has been introduced which provides classes for advanced exception handling. It has introduced the following classes
1. HandleProcessCorruptedStateExceptionsAttribute Class - Enables managed code to handle exceptions that indicate a corrupted process state.So,If you want to compile an application in the .NET Framework 4 and handle corrupted state exceptions, you can apply this attribute to the method that handles the corrupted state exception.
2.FirstChanceExceptionEventArgs Class -Provides data for the notification event that is raised when a managed exception first occurs, before the common language runtime begins searching for event handlers.

 

Q. What is new with ASP.Net 4 WebForms ?

Ans.Some of the Features are:

. Ability to Set Metatags.
. More control over view state.
. Added and Updated browser definition files.
. ASP.Net Routing.
. The ability to Persist Selected rows in data Control.
. More control over rendered HTML in FormView and ListView Controls.
. Filtering Support for datasource Controls.

Q. What is machine.config file and how do you use it in ASP.Net 4.0?

Ans. Machine.Config file is found in the “CONFIG” subfolder of your .NET Framework install directory (c:\WINNT\.NET\Framework\{Version Number}\CONFIG on Windows 2000 installations). It contains configuration settings for machine-wide assembly binding, built-in remoting channels, and ASP.NET.

In .the NET Framework 4.0, the major configuration elements(that use to be in web.config) have been moved to the machine.config file, and the applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications either to be empty or to contain just the following lines.

Q. What is RedirectPermanent in ASP.Net 4.0?

Ans. In earlier Versions of .Net, Response.Redirect was used, which issues an HTTP 302 Found or temporary redirect response to the browser (meaning that asked resource is temporarily moved to other location) which inturn results in an extra HTTP round trip. ASP.NET 4.0 however, adds a new RedirectPermanent that Performs a permanent redirection from the requested URL to the specified URL. and returns 301 Moved Permanently responses.
e.g. RedirectPermanent(“/newpath/foroldcontent.aspx”);

Q. How will you specify what version of the framework your application is targeting?

Ans.In Asp.Net 4 a new element “targetFramework” of compilation(in Web.config file) lets you specify the framework version in the webconfig file as

<?xml version=”1.0″?>
<configuration>
<system.web>
<compilation targetFramework=”4.0″ />
</system.web>
</configuration>

It only lets you the .NET Framework 4.0 and later verisons.

Q. What is the use of MetaKeywords and MetaDescription properties.

Ans.MetaKeywords and MetaDescription are the new properties added to the Page class of ASP.NET 4.0 Web Forms. The two properties are used to set the keywords and description meta tags in your page.
For e.g.
<meta name=”keywords” content=”These, are, my, keywords” />
<meta name=”description” content=”This is the description of my page” />

You can set these properties at run time, which lets you get the content from a database or other source, and which lets you set the tags dynamically to describe what a particular page is for.

You can also set the Keywords and Description properties in the @ Page directive at the top of the Web Forms page markup like,
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs”
Inherits=”_Default” Keywords=”ASP,4.0,are keywords” Description=”blah blah” %>

Q. What is Ajax Library.

Ans.Ajax Library is a client-only JavaScript library that is compatible with all modern browsers, including Internet Explorer, Chrome, Apple Safari, and Mozilla Firefox.Because the  Ajax Library is a client-only JavaScript library, you can use the library with both ASP.NET Web Forms and ASP.NET MVC applications. You can also create Ajax pages that consist only of HTML.

Q. What are the Changes in CheckBoxList and RadioButtonList Control ?

Ans. In ASP.NET 4, the CheckBoxList and RadioButtonList controls support two new values for the RepeatLayout property, OrderedList(The content is rendered as li elements within an ol element) and UnorderedList(The content is rendered as li elements within a ul element.)

Q. Whats Application Warm-Up Module?

Ans. We can set-up a Warm-Up module for warming up your applications before they serve their first request.Instead of writing custom code, you specify the URLs of resources to execute before the Web application accepts requests from the network. This warm-up occurs during startup of the IIS service (if you configured the IIS application pool as AlwaysRunning) and when an IIS worker process recycles. During recycle, the old IIS worker process continues to execute requests until the newly spawned worker process is fully warmed up, so that applications experience no interruptions or other issues due to unprimed caches.

List of common Sql Server Interview Questions


What is normalization?

Well a relational database is basically composed of tables that contain related data. So the Process of organizing this data into tables is actually referred to as normalization.

 

What is a Stored Procedure?

Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements.

 

Can you give an example of Stored Procedure?

sp_helpdb , sp_who2, sp_renamedb are a set of system defined stored procedures.

We can also have user defined stored procedures which can be called in similar way.

 

What is a trigger?

Triggers are basically used to implement business rules. Triggers is also similar to stored procedures.

The difference is that it can be activated when data is added or edited or deleted from a table in a database.

 

What is a view?

If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.

 

What is an Index?

When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.

 

What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered.

 

What is the basic difference between clustered and a non-clustered index?

The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.

 

What are cursors?

Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values.

 

When do we use the UPDATE_STATISTICS command?

This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

 

Which TCP/IP port does SQL Server run on?

SQL Server runs on port 1433 but we can also change it for better security.

 

From where can you change the default port?

From the Network Utility TCP/IP properties > Port number.both on client and the server.

 

Can you tell me the difference between DELETE & TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

 

Can we use Truncate command on a table which is referenced by FOREIGN KEY?

No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.

 

What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.

 

Can you give me some DBCC command options?(Database consistency check)

DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC – To check that all pages in a db are correctly allocated. DBCC SQLPERF – It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP – Checks all tables file group for any damage.

 

What command do we use to rename a db?

sp_renamedb oldname newname

 

Well sometimes sp_renamedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases?

In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.

 

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

Having Clause is basically used only with the GROUP BY function in a query.

WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

 

What do you mean by COLLATION?

Collation is basically the sort order.

There are three types of sort order

Dictionary case sensitive, Dictonary – case insensitive and Binary.

 

What is a Join in SQL Server?

Join actually puts data from two or more tables into a single result set.

 

Can you explain the types of Joins that we can have with Sql Server?

There are three types of joins: Inner Join, Outer Join, Cross Join

 

When do you use SQL Profiler? -

SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc..

 

What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements.

 

Can you link only other SQL Servers or any database servers such as Oracle?

We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group.

 

Which stored procedure will you be running to add a linked server?

sp_addlinkedserver, sp_addlinkedsrvlogin

 

What are the OS services that the SQL Server installation adds?

MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)

 

Can you explain the role of each service?

SQL SERVER – is for running the databases SQL AGENT – is for automation such as Jobs, DB Maintanance, Backups

DTC – Is for linking and connecting to other SQL Servers

 

How do you troubleshoot SQL Server if its running very slow?

First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes

 

Lets say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot?

First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly configured at client end for connection ”Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues.

 

What are the authentication modes in SQL Server?

Windows mode and mixed mode (SQL & Windows).

 

Where do you think the users names and passwords will be stored in sql server?

They get stored in master db in the sysxlogins table.

 

What is log shipping? Can we do logshipping with SQL Server 7.0

Logshipping is a new feature of SQL Server 2000. We should have two SQL Server – Enterprise Editions. From Enterprise Manager we can configure the logshipping. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and we can use this as the DR (disaster recovery) plan.

 

Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow?

For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER m which will basically bring it into the maintenance mode after which we can restore the master db.

 

What is BCP? When do we use it?

BulkCopy is a tool used to copy huge amount of data from tables and views. But it won’t copy the structures of the same.

 

What should we do to copy the tables, schema and views from one SQL Server to another?

We have to write some DTS packages for it.

 

 

 

Hope this would help you.

How to get Processor Serial Number using C#.net?

First of all include the namespace as below:

using System.Management;

 

now place the asp:button & asp:label in your code behind file, as given below:

<asp:Label ID=”Label5″ runat=”server” Text=”"></asp:Label>

<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click1″ Text=”Button” />

 

finally goto code behind of your aspx file. Now in button click event write something like this:-

ManagementObjectSearcher mo = new ManagementObjectSearcher(“select * from Win32_Processor”);

foreach (ManagementObject mob in mo.Get()){

try{

Label5.Text += mob["ProcessorId"].ToString();

}

catch (Exception ex){

// handle exception

}

}

 

now try to run your application. After runing just click on button, this will show you your processor serial number in label.

Hope this would be beneficial to you.

Regular expressions are a good way to validate text fields such as names, addresses, phone numbers, and other user information. You can use them to constrain input, apply formatting rules, and check lengths. To validate input captured with server controls, you can use the System.Text.RegularExpressions.Regex class.

Use the Regex class to constrain and validate input.

Regular expression support is available to ASP.NET applications through theRegularExpressionValidator control and the Regex class in the System.Text.RegularExpressionsnamespace.

Using the Regex Class

If you are not using server controls (which means you cannot use the validation controls) or if you need to validate input from sources other than form fields, such as query string parameters or cookies, you can use the Regex class within the System.Text.RegularExpressions namespace.

To use the Regex class

  1. Add a using statement to reference the System.Text.RegularExpressions namespace.
  2. Call the IsMatch method of the Regex class, as shown in the following example.
    // Instance method:
    Regex reg = new Regex(@"^[a-zA-Z'.]{1,40}$");
    Response.Write(reg.IsMatch(txtName.Text));
    
    // Static method:
    if (!Regex.IsMatch(txtName.Text,
                       @"^[a-zA-Z'.]{1,40}$"))
    {
      // Name does not match schema
    }
    
    For performance reasons, you should use the static IsMatch method where possible to avoid unnecessary object creation

Use Regular Expression Comments

Regular expressions are much easier to understand if you use the following syntax and comment each component of the expression by using a number sign (#). To enable comments, you must also specifyRegexOptions.IgnorePatternWhitespace, which means that non-escaped white space is ignored.

Regex regex = new Regex(@"
                        ^           # anchor at the start
                       (?=.*\d)     # must contain at least one numeric character
                       (?=.*[a-z])  # must contain one lowercase character
                       (?=.*[A-Z])  # must contain one uppercase character
                       .{8,10}      # From 8 to 10 characters in length
                       \s           # allows a space
                       $            # anchor at the end",
                       RegexOptions.IgnorePatternWhitespace);

Basic things to be understood in RegEx: 

"*" matches 0 or more patterns
"?" matches single character
"^" for ignoring matches.
"[]" for searching range patterns.

I am giving You some Pattern Samples For Validations

Pattern 1 For alpha

You Can make these in class or can acces on your page directly

I am providing you example with class with  a static method

Namspace Patterns {
Public Class OrientExpressions{
public static bool IsAlpha(String s){
if(Regx.IsMatch(s,"^[A-Za-z]$"))
return true;
else
return falsel;
}
}
}

Now You can acces this method your page on button click with class name without create object of class
Here are sampe pattern Samples which will very usefull for you

Pattern 1 For Numerics
"0*[1-9][0-9]*"

Pattern 2 For Alphas
"[^0-9]"

Pattern 3 For Password
"^(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})\\w{8,}$"


. Match any character except newline
\w Match any alphanumeric character
\s Match any whitespace character
\d Match any digit
\b Match the beginning or end of a word
^ Match the beginning of the string
$ Match the end of the string

Be happy and enjoy in Programming !!!!

ASP.NET PAGE LIFE-CYCLE

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle

  • General Page Life-cycle Stages
  • Life-cycle Events
  • Additional Page Life Cycle Considerations
  • Catch-Up Events for Added Controls
  • Data Binding Events for Data-Bound Controls
  • Login Control EventsIn general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page.

    Some parts of the life cycle occur only when a page is processed as a postback. For postbacks, the page life cycle is the same during a partial-page postback (as when you use an UpdatePanel control) as it is during a full-page postback.

    1) Page request

    The page request occurs before the page life cycle begins. When the page is requested by a user,

    2) Start

    In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

    3) Initialization

    During page initialization, controls on the page are available and each control’s UniqueIDproperty is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

    4) Load

    During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

    5) Postback event handling

    If the request is a postback, control event handlers are called. After that, the Validatemethod of all validator controls is called, which sets the IsValid property of individual validator controls and of the page

    6) Rendering

    Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render(HtmlTextWriter) method for each control, providing a text writer that writes its output to the OutputStream object of the page’s Responseproperty.

    7) Unload

    The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

    LIFE CYLE EVENTS

    The processing sequence in which a page is processed during a postback event is:

    Initializing: During this phase, the server creates an instance of the server control

    Loading view state: During this phase, the view state of the control posted by the client is reloaded into the new instance of the control.

    Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.

    Loading the postback data: During this phase, the server searches any data corresponding to the control that is loaded in the data posted by the client.

    PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.

    Saving state: During this phase, the change in the state of control between the current request and the previous request of the page is saved. For each change, the corresponding event is raised. For example, if the text of a textbox is changed, the new text is saved and a text_change event is raised.

    Rendering: During this phase, the server creates the corresponding HTML tag for the control.

    Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.

    Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control

    The events associated with the relevant page cycle phases are:

    • Page Initialization: Page_Init
    • View State Loading:LoadViewState
    • Postback data processing: LoadPostData
    • Page Loading: Page_Load
    • PostBack Change Notification: RaisePostDataChangedEvent
    • PostBack Event Handling: RaisePostBackEvent
    • Page Pre Rendering Phase: Page_PreRender
    • View State Saving: SaveViewState
    • Page Rendering: Page_Render
    • Page Unloading: Page_UnLoad

step 1: create New Database As Given Below In picture.

Step 2: When Your New Database will be created ,Use to him with Given Command or Querey

for example –USE DBEMPLOYEE

STEP 3: Now Make a Sql Function and Given Him name split with two arguments .which will return a Table with a variable whose datatype is table

STEP 4: NOW RUN YOUR FUNCTION WITH VALUES

i hope you will enjoy with this article and your logic problem will be solved .

Be Happy In programming World and Enjoy!!!

Follow

Get every new post delivered to your Inbox.