This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Working with Windows Workflow Foundation in ASP.NET

In September of 2005, Microsoft unleashed Windows Workflow Foundation (Windows WF) at its semi-annual Professional Developer's Conference. As one of the pillars of the WinFX APIs, Windows WF provides developers with a common framework on which to develop process driven and workflow-centric applications.
Currently, when organizations wish to automate business processes the standard answer is to assemble a team of developers to write the appropriate code. While this approach has generally served organizations well, it has some inherent problems. To understand why, you need to understand some fundamental characteristics of a workflow.
A workflow is essentially a way of documenting the activities involved in completing a unit of work. Typically, work "flows" through one or more activities during processing. These activities can be performed by either machines or by people, and can be as simple as defining the sequence of pages in an Internet application, or as complex as managing documents or products that must be seen, altered, and approved by any number of people.

Because so many workflows must allow for human involvement, they can take long periods of time to complete, ranging from hours to months or longer. For example, people involved in the process may be unavailable, out-of-town, or busy with other tasks; therefore, workflows must be able to persist themselves during periods of inactivity. Furthermore, processes implemented solely using code can be difficult for non-technical people to understand and for developers to change. This and other factors are the target of generic workflow frameworks such as Windows WF, which aim to make creating, altering, and managing workflows easier, both by giving them a visual interface and by defining a common API
You can host Windows WF workflows in any type of .NET application, including Windows Forms, console applications, Windows Services, and ASP.NET Web applications. Each type requires special considerations. While examples that showcase hosting workflows in Windows Forms and console applications are already plentiful, this article focuses on issues facing ASP.NET developers who wish to integrate workflow into their applications.
Windows WF and the MVC Pattern
One common way in which you might use Windows WF in an ASP.NET application is to implement a Model-View-Controller (MVC) approach. Essentially, the goal of MVC is to separate the presentation layer, application logic, and application flow logic from each other.

To illustrate how this would be useful in an ASP.NET application, consider a help desk ticket workflow scenario. A business user starts the workflow by filling out an ASP.NET Web form and clicking a submit button. Next, a server notifies a help desk employee using a Windows Forms application that a new ticket is available. The help desk employee would then work on the problem, and eventually close the ticket. If this workflow scenario were developed using Windows WF, all the process logic and flow could be contained in the workflow itself, and the ASP.NET application would need to know nothing about the logic.

This scenario provides some solid evidence that separating presentation from logic is a good thing. Because the process of handling help desk requests is common, if the logic were implemented using C# or VB.NET code in several different .NET applications, you'd run the risk of duplicate code or worse, different implementations of the same business process in completely different code. But if you implement the process in Windows WF, the developers of applications that need the process would need to modify the steps in only one place—the workflow itself—without worrying about changing logic in their applications. Code duplication and the ambiguity of where to implement process can be mitigated with Windows WF.

When implementing the MVC architecture in ASP.NET using Windows WF, developers should attempt to build workflows independent of the applications in which they will be hosted. This will assist in keeping logic separate from presentationand maintain a high degree of independence between the order of workflow steps and page flow in the Web application.

A novice Windows WF developer might be tempted to develop a workflow with a set number of activities in a certain order and afterward, develop a set of ASP.NET Web forms that flow from one to another in the same order. Unfortunately, while that seems logical, it's counterproductive, because you would be implementing the workflow logic twice. Web page X should not need to know whether it needs to go to Page Y or Page Z to implement the workflow steps correctly. Instead, the workflow (the model) should tell ASP.NET (the controller) what the next step is, and then ASP.NET should determine which page (the view) to display. In this way, each page requires little knowledge of the overall process; it only needs to know how to complete one distinct activity and let the workflow worry about how the pages flow from one to the next. This separation provides developers with a great deal of flexibility related to the order of page flow. For example, if you decided to change the page display sequence, you could easily do that in the workflow, without changing one line of code in the ASP.NET application.

For Sample Application and Code ....> next Article

Bind Radio Button in Grid View.

Introduction

             Sometimes, we will have requirements to have a RadioButton control in every row of the GridView control to select one row at a time. If we have a TemplateColumn with a RadioButton control, it will allow selection of multiple rows by default. This is because, the RadioButton will have different ID for every row and hence it will allow multiple selections. So, we should add some sort of client side functionality that prevents selection of multiple Radio Buttons but one. In this article, we will call a Javascript function on click of RadioButton that checks if there is some other RadioButton in the GridView is already selected to uncheck it leaving the current selection.

Steps

Declare a GridView control with a TemplateColumn as the first column to include Radio control. Include BoundField for other fields to display in the GridView.  

<asp:GridView ID="MyUserGrid" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4" OnRowCommand="gvUsers_RowCommand">
         <Columns>
            <asp:TemplateField HeaderText="Select">
                  <ItemTemplate>
                     <asp:RadioButton ID="rdbGVRow" onclick="javascript:CheckOtherIsCheckedByGVID(this);"  runat="server" /> 
                  </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />
            <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />
            <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />
          </Columns>
   <FooterStyle BackColor="White" ForeColor="#330099" />
   <RowStyle BackColor="White" ForeColor="#330099" />
  <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
   <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
  <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindUsers();
    }
    public void BindUsers()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
        con.Open();
        SqlDataAdapter ada = new SqlDataAdapter("select EmployeeId, TitleOfCourtesy, FirstName,BirthDate from employees",con);
        DataSet DS = new DataSet();
        ada.Fill(DS);
        gvUsers.DataSource = DS;
        gvUsers.DataBind();
    }
 
 
WebConfig
 
under  configuration :
 
<
connectionStrings>
 <add name="ConString" connectionString="uid=sa;pwd=;database=NorthWind;server=RajeshI" providerName="System.Data.SqlClient"/>
</connectionStrings>

Execute the page. You can see the GridView with RadioButton.

Adding Client Side Functionality

To check if there is some other row selected and to uncheck it by keeping the current row selection we will call a JavaScript function called CheckOtherIsCheckedByGVID(). This function is called by the OnClick event of the RadioButton, Refer the above code.

The below JavaScript function will do our client side functionality.

function
CheckOtherIsCheckedByGVID(spanChk)
{
      var IsChecked = spanChk.checked;
      var CurrentRdbID = spanChk.id;
      var Chk = spanChk;
      Parent = document.getElementById('<%=MyUserGrid.ClientID %>');
      var items = Parent.getElementsByTagName('input');
      for(i=0;i<items.length;i++)
      {
         if(items[i].id != CurrentRdbID && items[i].type=="radio")
         {
           if(items[i].checked)
          { 
             items[i].checked = false;
           }
         }
     }
}

 
 

Execute the page and see it in action.

 Since, we are getting all the elements with tag name as "input", the above code will uncheck if there are any other RadioButton control is present in any other column for a different purpose. To understand it better, include one more TemplateField with RadioButton control at the last in the GridView columns list and test it.

To handle the above scenario with multiple RadioButton in a Row, we will change the code a bit to access the RadioButton based on the column location. If we see the rendered table in the HTML output, we will have the RadioButton at every first TD. The below code will clear the selection of RadioButton that is found only in the first column.

function CheckOtherIsCheckedByGVIDMore(spanChk)

       {

           var IsChecked = spanChk.checked;

           if(IsChecked)

              {

               spanChk.parentElement.parentElement.style.backgroundColor='#228b22'; 

               spanChk.parentElement.parentElement.style.color='white';

              }                   

           var CurrentRdbID = spanChk.id;   

           var Chk = spanChk;           

              Parent = document.getElementById('<%=MyUserGrid.ClientID %>');

              for(i=0;i< Parent.rows.length;i++)

              {

                  var tr = Parent.rows[i];

                  var td = tr.childNodes[0];             

                  var item =  td.firstChild;            

                  if(item.id != CurrentRdbID && item.type=="radio")

                  {           

                      if(item.checked)

                      {    

                          item.checked = false;

                          item.parentElement.parentElement.style.backgroundColor='white';

                          item.parentElement.parentElement.style.color='black';

                      }

                  }

              }

       }

     The above code assumes the RadioButton will be the first column of every row in the GridView.This code will work perfectly even if there are RadioButton present in any other column of the GridView control.

Conclusion

Using CheckBox control to enable selection of a single row and selection of all the rows is a common task that we will do GridView control. This article will help you doing the same with JavaScript in client side.

Javascript working fine in IE But not Some time in firfox .To work in firefox, IE, Chrome, change the property parentElement to parentNode.

Inserting Dynamic Text Box Data Into A Database

Generally Every one can create daynamic text box and they want to store the text which has been entered in to the textbox by the user and they feel its very hard to read the data from the text boxes which are created dynamically.
This blog explains you how to insert daynamic text box data into a SQL Server database.
here I have text boxes that are being generated dynamically . text boxes will be generated while user clicks on Add new Row button and as well as textbox will be removed when the user click on the remove Row button. and I have explained each of those values inserted into the database that hold the results.
The Text boxs will be generated number of times. Here I've wrote you a sample code. It can dynamcially create rows of textboxes and add those values into database. I hope my example will help you to figure out what you should do next.

i have took one hidden control to hold the number of dynamic controls. and i am creating the text box befor the page is post backing. Client side javascript call will help to to increase the
hidden feild value. place below java script in header tag. (click on the code to view enlarged..)


once increment script done. creat a hiddent control with a value as "0" (zero) . and create a asp.net table to hold the dynamic controls. as well s create a button to call the client side script to add new row. and creat one more button to save the data which has entered in to dynamic controls. (click on the code to view enlarged..)




Once we added the controls we need to add the code snippet to create the dynamic controls for each and every time when the user click on the Add new Row button. here if we write the code in page is post back the dynamic controlls will not create for each client side click . to hold the the control view state and creating the dynamic controll i am writing the code in Page Load event.


if (HiddenField1.Value != "")
{
rows = int.Parse(HiddenField1.Value);
for (int i = 0; i <>

{

TableRow tr = new TableRow();

TableCell tc = new TableCell();

TextBox tb = new TextBox();

tb.ID = "FORM" + i.ToString();

tc.Controls.Add(tb);

CheckBox tb2 = new CheckBox();

tb2.Text = "Check if it is a Report";

tb2.ID = "RChk" + i.ToString();

TableCell tc2 = new TableCell();

tc2.Controls.Add(tb2);

tr.Cells.Add(tc); tr.Cells.Add(tc2);

Table1.Rows.Add(tr);

}

if (rows <>

{

btnRemove.Visible = false;

frmname.Visible = false;

}

else

{

frmname.Visible = true; btnRemove.Visible = true;

}

}

here i am making the form name Title visible true only when atleast one row is crated.

How to Retrive the dynamic Control data:

So far we have seen how the dynamic controll will be created while user clicks on a button controll now i am going to give a clear picture how to retive the data from the dynamic control.

as we have took hidden control and assigend the number for ID as prefix of the perticular control.

so using a small for loop we can get back the perticular dynamic controll data. for more inoformation look below code.


for (int i = 0; i <>

{

TextBox Form = Table1.Rows[i].Cells[0].FindControl("FORM" + i.ToString()) as TextBox;

CheckBox F_type = Table1.Rows[i].Cells[1].FindControl("RChk" + i.ToString()) as CheckBox;

if (F_type.Checked)

{

string _F_Type= "REPORT Checked";

}

string _Form_name = Form.Text;

if (Form.Text.Length > 0)
{
result = SaveFormName(_F_Type,_Form_name);
}
}
HiddenField1.Value = Convert.ToString(0);
Table1.Rows.Clear();

Here Save formname will have the dyanamic control data as function arguments to be saved in data base. Hope you enjoyed with the above code.

Asp .net Web.config Configuration File

What is Web.Config File?

Web.config file, as it sounds like is a configuration file for the Asp .net web application. An Asp .net application has one web.config file which keeps the configurations required for the corresponding application. Web.config file is written in XML with specific tags having specific meanings.

What is Machine.config File?

As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.

What can be stored in Web.config file?

There are number of important settings that can be stored in the configuration file. Here are some of the most frequently used configurations, stored conveniently inside Web.config file..
1. Database connections
2. Session States
3. Error Handling
4. Security
Database Connections:
The most important configuration data that can be stored inside the web.config file is the database connection string. Storing the connection string in the web.config file makes sense, since any modifications to the database configurations can be maintained at a single location. As otherwise we'll have to keep it either as a class level variable in all the associated source files or probably keep it in another class as a public static variable.
But it this is stored in the Web.config file, it can be read and used anywhere in the program. This will certainly save us a lot of alteration in different files where we used the old connection.
Lets see a small example of the connection string which is stored in the web.config file.


[configuration]
[appsettings]
[configuration]
[appsettings]
[add value="server=localhost;uid=sa;pwd=;database=DBPerson" key="ConnectionString"]
[/appsettings]
[/configuration]
[configuration]
[appsettings]
[add value="server=localhost;uid=sa;pwd=;database=DBPerson" key="ConnectionString"]
[/appsettings]
[/configuration]
[add value="server=localhost;uid=sa;pwd=;database=DBPerson" key="ConnectionString"]
[/appsettings]
[/configuration]

As you can see it is really simple to store the connection string in the web.config file. The connection string is referenced by a key which in this case is "ConnectionString". The value attribute of the configuration file denotes the information about the database. Here we can see that if has database name, userid and password. You can define more options if you want.
There is a very good website that deals with all sorts of connection strings. Its called http://www.connectionstrings.com/ , in the website you will find the connection strings for most of the databases.
Lets see how we access the connection string from our Asp .net web application.

using System.Configuration;
string connectionString = (string )ConfigurationSettings.AppSettings["ConnectionString"];

The small code snippet above is all that is needed to access the value stored inside the Web.config file.
Session States:
Session in Asp .net web application is very important. As we know that HTTP is a stateless protocol and we needs session to keep the state alive. Asp .net stores the sessions in different ways. By default the session is stored in the asp .net process. You can always configure the application so that the session will be stored in one of the following ways.
1) Session State Service
There are two main advantages of using the State Service. First the state service is not running in the same process as the asp .net application. So even if the asp .net application crashes the sessions will not be destroyed. Any advantage is sharing the state information across a Web garden (Multiple processors for the same computer).
Lets see a small example of the Session State Service.

[sessionstate timeout="20" sqlconnectionstring="data source=127.0.0.1;user id=sa;password='' cookieless=" stateconnectionstring="tcpip=127.0.0.1:55455" mode="StateServer"]

[sessionstate timeout="20" sqlconnectionstring="data source=127.0.0.1;user id=sa;password='' cookieless=" stateconnectionstring="tcpip=127.0.0.1:55455" mode="StateServer"]

The attributes are self explanatory but I will go over them.
mode: This can be StateServer or SqlServer. Since we are using StateServer we set the mode to StateServer.
stateConnectionString: connectionString that is used to locate the State Service.
sqlConnectionString: The connection String of the sql server database.
cookieless: Cookieless equal to false means that we will be using cookies to store the session on the client side.

2) SQL Server
The final choice to save the session information is using the Sql Server 2000 database. To use Sql Server for storing session state you need to do the following:
1) Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store the session.
You web.config settings will look something like this:


[sessionstate id="sa;password=" timeout="20" sqlconnectionstring="data source=" stateconnectionstring="tcpip=127.0.0.1:45565" mode="SqlServer" cookiesless="false"]

[sessionstate id="sa;password=" timeout="20" sqlconnectionstring="data source=" stateconnectionstring="tcpip=127.0.0.1:45565" mode="SqlServer" cookiesless="false"]


SQL Server lets you share session state among the processors in a Web garden or the servers in a Web farm. Apart from that you also get additional space to store the session. And after that you can take various actions on the session stored.
The downside is SQL Server is slow as compared to storing session in the state in process. And also SQL Server cost too much for a small company.
3) InProc:
This is another Session State. This one is mostly used for development purposes. The biggest advantage of using this approach is the applications will run faster when compared to other Session state types. But the disadvantage is Sessions are not stored when there is any problem that occurs with the application, when there is a small change in the files etc., Also there could be frequent loss of session data experienced..
Error Handling:
Error handling is one of the most important part of any web application. Each error has to be caught and suitable action has to be taken to resolve that problem. Asp.net web.config file lets us configure, what to do when an error occurs in our application.
Check the following xml tag in the web.config file that deals with errors:

[customerrors mode="On"]
[error redirect="errorPage.aspx" statuscode="404"]
[customerrors mode="On"]
[error redirect="errorPage.aspx" statuscode="404"]
[/customerrors]
[/customerrors]


This tells the Asp.net to display custom errors from a remote client or a local client and to display a page named errorPage.aspx. Error "404" is "Page not found" error.
If custom error mode is turned "off" than you will see Asp.net default error message. This error messages are good for debugging purposes but should never be exposed to the users. The users should always be presented with friendly errors if any.
Security:
The most critical aspect of any application is the security. Asp.net offers many different types of security method which can be used depending upon the condition and type of security you need.
1) No Authentication:
No Authentication means "No Authentication" :) , meaning that Asp.net will not implement any type of security.
2) Windows Authentication:
The Windows authentication allows us to use the windows user accounts. This provider uses IIS to perform the actual authentication, and then passes the authenticated identity to your code. If you like to see that what windows user is using the Asp.net application you can use:
User.Identity.Name;
This returns the DOMAIN\UserName of the current user of the local machine.
3) Passport Authentication:
Passport Authentication provider uses Microsoft's Passport service to authenticate users. You need to purchase this service in order to use it.
4) Forms Authentication:
Forms Authentication uses HTML forms to collect the user information and than it takes required actions on those HTML collected values.
In order to use Forms Authentication you must set the Anonymous Access checkbox checked. Now we need that whenever user tries to run the application he/she will be redirected to the login page.

[authentication mode="Forms"]
[forms name="3345C" timeout="1" loginurl="frmLogin.aspx"]
[/authentication]
[authorization]
[authentication mode="Forms"]
[forms name="3345C" timeout="1" loginurl="frmLogin.aspx"]
[/authentication]
[authorization]
[deny users="?"]
[/authorization]
[deny users="?"]
[/authorization]

As you can see we set the Authentication mode to "Forms". The forms loginUrl is the first page being displayed when the application is run by any user.
The authorization tags has the deny users element which contains "?", this means that full access will be given to the authenticated users and none access will be given to the unauthenticated users. You can replace "?" with "*" meaning that all access is given to all the users no matter what.
Final Words:
As you have seen that Web.config file plays a very important role in the over all Asp.net application. There are a lot more features that I have not discussed which includes caching. Try using web.config file when you need to configure the overall application.

Sealed Classes And Methods In C#

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.
The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.
In C# structs are implicitly sealed; therefore, they cannot be inherited.
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:
class MyDerivedC: MyClass {} // Error
You will get the error message:'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.
In C# a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method. using System;class MyClass1 { public int x; public int y;
public virtual void Method()
{
Console.WriteLine("virtual method");
}
}
class MyClass : MyClass1
{
public override sealed void Method()
{
Console.WriteLine("sealed method");
}
}
class MainClass
{
public static void Main()
{
MyClass1 mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
mC.Method();
}
}

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites