Friday, May 13, 2011

Reverse a String in C#

private void gridView1_CustomUnboundColumnData(object sender,
                      DevExpress.XtraGrid.Views.Base.
CustomColumnDataEventArgs e)
{
GridView view = sender as GridView;
if (e.Column.FieldName == "Reversed" && e.IsGetData)
{

char [] charArray=((InDirectContacts)view.GetRow(e.RowHandle)).Name.ToCharArray();
Array.Reverse(charArray);
string reversedContactName = new string(charArray);
e.Value = reversedContactName;
}
}

Tuesday, May 10, 2011

Selecting Row from XtraGrid with Object type DataBinding.

private void gridView1_FocusedRowChanged(object sender, |
              DevExpress.XtraGrid.Views.Base.
FocusedRowChangedEventArgs e)
{
GridView view = sender as GridView;
if (view.SelectedRowsCount > 0) // i there a selected Row?
{
    Contacts indirectContact = (Contacts)view.GetRow(e.FocusedRowHandle);
    currentSelectedContactId =
Convert.ToString(Contact.ContactID);
}

 

Friday, May 6, 2011

How to make XtraGrid GridControl Columns ReadOnly

Here are several possible solutions.
1. The first solution is to set the Editable option of the GridView.OptionsBehavior property
    to False. In this case, the whole grid becomes read-only.
    Select GridControl and click on the arrow on right-top select Run Designer. In the Properties
    List go to Options->OptionsBehaviour->Editable= False.. set this property to false.

2. Another solution is to cahnge the ReadOnly or AllowEdit option of your columns.
3. The last solution is to use the ShowingEditor event of the view and disable cell editing via
    code using the event handler's e.Cancel parameter.
The OptionsColumn property is part of the GridColumn class.

Open the designer for a GridControl, select a GridView, then click on the Columns icon in the Main section of the NavBar shown at
the left of the designer. This is where you manage your GridColumn objects for the selected GridView. Near the bottom of the
property list on the right side of the designer will be shown the options for a selected column.

Programmatically, you may do the following to make all columns read-only (C#):

foreach( GridColumn gridColumn in gridView1.Columns )
gridColumn.OptionsColumn.ReadOnly = true;

Thursday, May 5, 2011

BindingList save to database

     /// <summary>
      /// Saves the customer properties back to the database.
      /// </summary>
      public override Boolean SaveItem()
      {
        Boolean success = false;

        // If the entity state is added, need to get the CustomerId back.
        bool isOutput = EntityState == EntityStateType.Added ? true : false;

        // Pass the properties back to the DAC
        // This would not be needed if the base class had code to use Reflection to build
        // the parameters from the object properties.
        int retVal = Dac.ExecuteNonQuery("CustomerSave_sp",
                Dac.Parameter(cnCustomerID, CustomerId, isOutput),
                Dac.Parameter(cnLastName, LastName),
                Dac.Parameter(cnFirstName, FirstName),
                Dac.Parameter(cnAddress, Address),
                Dac.Parameter(cnCity, City),
                Dac.Parameter(cnState, State),
                Dac.Parameter(cnZip, Zip),
                Dac.Parameter(cnPhone, Phone),
                Dac.Parameter(cnLastUpdateUser, System.Environment.UserName),
                Dac.Parameter(cnRowState, EntityState.ToString()));

        // If it was an add, update the product ID
        if (EntityState == EntityStateType.Added)
          CustomerId = retVal;

        // Reset the entity's state
        this.SetEntityState(EntityStateType.Unchanged);

        // Assume success
        success = true;

        return success;
      }
The DAC component is my data access layer. The ExecuteNonQuery method looks like this:
    /// <summary> 
   /// Executes a stored procedure that does not return a dataTable 
  /// and returns the     /// first output parameter. 
/// </summary>     /// <param name="storedProcedureName">Name of the stored procedure 
/// to execute</param>     /// <param name="arrParam">Parameters required by the stored 
/// procedure</param>     /// <returns>First output parameter</returns> 
public static int ExecuteNonQuery(string storedProcedureName, params SqlParameter[] arrParam) 
 {
       int retVal=0;
       SqlParameter firstOutputParameter = null;
       DataTable dt = new DataTable();
        // Open the connection 
       using (SqlConnection cnn = new SqlConnection(Properties.SettingsDefault.PTConnectionString)) 
       {
         cnn.Open();
           // Define the command
          using (SqlCommand cmd= new SqlCommand() )
         {
           cmd.Connection = cnn;
           cmd.CommandType = CommandType.StoredProcedure;
           cmd.CommandText = storedProcedureName;
            // Handle the parameters 
           if (arrParam != null)
           {
             foreach (SqlParameter param in arrParam)
             {
               cmd.Parameters.Add(param);
               if (firstOutputParameter == null && param.Direction==ParameterDirection.Output 
                                                             && param.SqlDbType == SqlDbType.Int)
               {
                 firstOutputParameter = param;
               }
             }
           }
            // Execute the stored procedure 
           cmd.ExecuteNonQuery();
            // Return the first output parameter value 
           if (firstOutputParameter != null)
             retVal = (int)firstOutputParameter.Value;
         }
       }
       return retVal;
     }  

Tuesday, April 26, 2011

Remoting in .NET

.NET Remoting is an enabler for application communication. It is a generic system for different applications to use to
communicate with one another. .NET objects are exposed to remote processes, thus allowing interprocess communication.
The applications can be located on the same computer, different computers on the same network, or even computers across
separate networks.
Independent Devices

Rules of Remoting:

  1. There must be 2 independent devices. 
  2. One have functionality and another will access that functionality. 
  3. Functionality must be in running or active mode e.g. Television must be in running mode to work with remote
    An Example of remoting is that we have have SQL Server and SQL Server client edition. Here Client edition tool work as
    remote. Same with Oracle also.

    If we implement such functionality then we use Remoting. It could be 1-tier or other architec
    tures.
Remoting process


When a call is made from the Client a Marshall object is created at the server.
Marshall Object: This is special type of object that catch request, analyze, execute functionality and reply Data/
Information back.

There are two type of Communication between Server and Client.
Singleton-    if SMO(Single Marshall Object) handles MR(Multiple Request).
Single Call- if MMO( Multiple Marshall Object)s Handles MR(Multiple Request).
In communication Server do not know about that where is client and same with client. this also do not know about
the server location. communication is not done directly it is done by proxy.

Proxy contain two parts
Stub- This implement the Skelton.
Skeleton- Contains Rules of Communication.

Server contain Skelton and Client contain Stub. Stub communicate with the Skeleton.

Three things required to implement the Remoting
Business Login – Marshall Object./
Skeleton at Server
Stub at Client

First Create Business Logic that served to the client:
create a class that inherits Class MarshalRefObject. To do this create new project and select class library as in Fig below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BusinessLogic
{
    public class BL:MarshalByRefObject
    {
        public string Greet(string strName)
        {
            return ("Hello" + strName);
        }
    }
}
Build the solution. after this it will create a library file (.dll) that you have to use in next step; in creation of the server.
2.  Server Code...
Create New project ..Select Console Application and Reference System.Runtime.Remoting as in Fig 2.


Now add BusinessLogic dll to your solution using add reference.
and write the following code:
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpChannel tc = new TcpChannel(8030);
            ChannelServices.RegisterChannel(tc, false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(BusinessLogic.BL), "xyz", WellKnownObjectMode.SingleCall);
            Console.Write("Server is Ready!");
            Console.ReadKey();
        }
    }
}
.. Here you have to register the channel and get the type of information that travel on the channel is BusinessLogic's object.
Now move to the client's working.
Step 3: Client
Create a new project and select Windows Form Application with two text boxes and one Button as in Figure  6.
Here you have add a interface with the same name space as in the Business Logic and specify all the methods name
as it is in the Business Logic.
Here is code of that class file that contains the Interface.
namespace BusinessLogic
{
    public interface BL
    {
        string Greet(string strName);
    }
}

figure 6
and now write following code to communicate with the server.
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        BusinessLogic.BL obj;
        private void Form1_Load(object sender, EventArgs e)
        {
            TcpChannel tc = new TcpChannel();
            ChannelServices.RegisterChannel(tc, false);
            object o = Activator.GetObject(typeof(BusinessLogic.BL), "tcp://Niranjan-PC:8030/xyz");
            obj = (BusinessLogic.BL)o;
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            txtReceivedMessage.Text = obj.Greet(txtMessage.Text);
        }
    }
}
here it get the object type of our interface structure and the server name is also specified and with there service
that we have placed on server named as xyz.

.NET Remoting versus Distributed COM

In the past interprocess communication between applications was handled through Distributed COM, or DCOM. DCOM
works well and the performance is adequate when applications exist on computers of similar type on the same network.
However, DCOM has its drawbacks in the Internet connected world. DCOM relies on a proprietary binary protocol that
not all object models support, which hinders interoperability across platforms. In addition, have you tried to get DCOM to
work through a firewall? DCOM wants to communicate over a range of ports that are typically blocked by firewalls. There
are a ways to get it to work, but they either decrease the effectiveness of the firewall (why bother to even have the firewall
if you open up a ton of ports on it), or require you to get a firewall that allows support for binary traffic over port 80.
.NET Remoting eliminates the difficulties of DCOM by supporting different transport protocol formats and communication
protocols. This allows .NET Remoting to be adaptable to the network environment in which it is being used.

.NET Remoting versus Web Services


Unless you have been living in a cave, or are way behind in your reading, you have probably read something about Web
services. When you read the description of .NET Remoting it may remind you a lot of what you're read about Web services.
That is because Web services fall under the umbrella of .NET Remoting, but have a simplified programming model and are
intended for a wide target audience.
Web services involve allowing applications to exchange messages in a way that is platform, object model, and programming
language independent. Web services are stateless and know nothing about the client that is making the request. The clients
communicate by transferring messages back and forth in a specific format known as the Simple Object Access Protocol, or
SOAP. (Want to get some funny looks in the hallway? Stand around in the hallway near the marketing department with your
colleagues and discuss the benefits of using SOAP).

The following list outlines some of the major differences between .NET Remoting and Web services that will help you to
decide when to use one or the other:
  • ASP.NET based Web services can only be accessed over HTTP. .NET Remoting can be used across any protocol.

  • Web services work in a stateless environment where each request results in a new object created to service the request.
    .NET Remoting supports state management options and can correlate multiple calls from the same client and support
    callbacks.

  • Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can
    be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that
    contain information about data types. This limits the information that must be passed about an object and allows objects
    to be passed by value or by reference.

  • Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting
    requires the clients be built using .NET, or another framework that supports .NET Remoting, which means a
    homogeneous environment

Wednesday, April 20, 2011

jQuery Rocks

This is a basic tutorial, designed to help you get started using jQuery. If you don't have a test page setup yet, start by creating
a new HTML page with the following contents:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
</script>
</body>
</html> 
Edit the src attribute in the script tag to point to your copy of jquery.js. For example, if jquery.js is in the same directory as
your HTML file, you can use:

<script src="jquery.js"></script> 
You can download your own copy of jQuery from the Downloading jQuery page


Launching Code on Document Ready

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:
window.onload = function(){ alert("welcome"); } 
Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code
isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first
place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be
manipulated.

$(document).ready(function(){    // Your code here  }); 
Inside the ready event, add a click handler to the link:
$(document).ready(function(){     
               $("a").click(function(event){ 
                      alert("Thanks for visiting!"); 
                 }); 
}); 
Save your HTML file and reload the test page in your browser. Clicking the link on the page should make a browser's alert
pop-up, before leaving to go to the main jQuery page.

For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling
event.preventDefault() in the event handler:

$(document).ready(function(){
$("a").click(function(event){
alert("As you can see, the link no longer 
took you to jquery.com");
event.preventDefault();
     });
}); 
 
use this code and see the smaller part of JQuery capabilities:
create a html file and run it.
<!--
<head>
    <title></title>
    <script src="scripts/jquery-1.5.2.min.js" ></script>
</head>
<body>
<!--<script type="text/javascript" language="javascript" >
    window.onload = function () { alert("Welcome"); }
</script>-->
<!-- this JQuery onload equivalent-->
<!--
<script>
    $(document).ready(function () { alert("welcome"); })
</script> -->
<!-- JQuery script for links click event action -->
<script >
    $(document).ready(function () {
        $("a").click(function (event) {
            //            event.preventDefault();
            //            alert("Thanks for visiting!");
            event.preventDefault();
            $(this).hide("slow");
        });
        $("#jai").mouseenter(function (event) {
            event.preventDefault();
            $(this).hide("slow");
        });
    });
    </script>
<div id="jai" style="width:200px; height:200px; margin:0px auto; background-color:Blue;"></div>
<a href="#" id="ram" >Ram</a>
</body>
</html>
-->

Thursday, April 14, 2011

Session - State Management in ASP.net


To manage information at server side Session is best method. It Provides
* Security
* Reliability
* it can store any type of data
How Session works and it created on Server
When Browser send request to your website then server generates a UID called sessionid and
this 'Sessionid' is managed in Session Table. A table is created on the server for managing the
session id for various web clients( Browsers).
This session id is sent to the client. after this session is also sent to the server after first request.
Figure 1
When Server assign session id then event iss also fired called 'Session_Start'.
The generated session id is stored in the cooked. server send session id to client and client send
this session id every time and this cookie  mechanism based on cookies working.Cookie is created
at client side with then name 'aspnet_sessionid'. It is a Non-persistent cookies.
A simple program that demonstrate the working of Session Management.
1. create a empty web application
2. Add a webpage and name them a.aspx
3. Add Global.asax- Global Application Class
4. add a button on a.aspx
and write code this code.
protected void Page_Load(object sender, EventArgs e)
   {
       Response.Write("No of cookies: " + Request.Cookies.Count.ToString());
   }
   protected void btnSend_Click(object sender, EventArgs e)
   {
       Response.Write("No of cookies: " + Request.Cookies.Count.ToString());
   }
when you first time run it will show no of cookies =0 , but when you click on button then
it will show count =1. session id is sent by server after the first request and when you click on button
then it have cookies that store the information of the session id.
Transferring on page information to another page:
1. add a text box on a.aspx and add a new page named b.aspx
2. write below code at button's click event.
Figure 2 Form a.aspx

protected void btnSend_Click(object sender, EventArgs e)
   {
      Session.Add("msg",txtMessage.Text);
       Response.Redirect("b.aspx");
   }
3.  now write following code at b.aspx Page_Load event.
protected void Page_Load(object sender, EventArgs e)
   {
       Response.Write("Message From A:- " +Session["msg"].ToString());
       Response.Write("<br/>Cookie Name:- "+Request.Cookies[0].Name);
       Response.Write("<br/>Session Id:- "+Request.Cookies[0].Value);
   }
output will be after clicking on send button with a message in textbox.

Figure 3 Output on another page

Case
if someone directly access the b.aspx, what will happen.

Figure 4 Error Message: if some one access b.aspx directly

it will give error because we have not assed value to the msg in session. To avoid this set any
default value to the msg at the start of the Session as:
Go to Global.asax and find event named Session_Start and here you should initialize the session
using add method.
as:
Session.Add("msg", "null");
and at the click of the button you just update the value of the session except adding value to the
session as:
Session[]=txtMessage.Text;
Response.Redirect("b.aspx");
Some Session Methods and Properties :
Abandon()- Used to kill the session by force as Session.Abandon();
CookieMode –Property have two options Cookie or CookieLess
IsCookieLess- check the client that cookie is supported or not.
IsNewSessoin- checks that is it your first request to the server from client.
Mode- InProc and OutProc
           Inproc – at server cookies etc.
           outproc- information saved in external application like state server, SQL server db.
SessionId- returns SessionId
timeout – Specifies the number of minutes that a session can remain idle before the server terminates it
automatically. The default is 10 minutes. Session.Timeout has no hard-coded limit. It should not be set
higher than 20 minutes (except in special cases) because every open session is holding onto memory. It
should also not be set lower than 4 minutes because clients rarely respond within that time resulting in a
loss of session state. Most of the books tell this 20 minutes. according to me it depends upon IIS.

IIS 6.0: The minimum allowed value is 1 minute and the maximum is 1440 minutes.
Changing Session Related Information
if you want to change the session related information then go to Web.config and use following Session
tag to specify Session values as in the <System.Web> section.
<sessionState timeout="1" cookieName="Niranjan" regenerateExpiredSessionId ="true"  />
if you want to regenerate new session id if your session expire after 20 minutes or fix time. it will not work
on local machine if you request from remote then it will work.
To Implement CookieLess
use cookieless attribute in SessionState for implementing this.
it have 5 options:
1. AutoDetect- Detech first that Browser support cookie then cookie else cookieless
2. Use Cookies- Use cookies
3. UseDeviceProfile- Use Device Information
4. UseUri- session id is managed in url not good, if you use this url in another browser then it will get same
    value. it is not good in case of online transactions.
Session Mode -
InProc
OutProc
If you want that info is save either sever close or anything happen with the web application then
use the OutProc Mode of Session State.
you can store information in two external application
1. StateServer
To use State Server do the following:
<sessionState timeout="1" cookieName="Niranjan" regenerateExpiredSessionId ="true"  mode=
"StateServer" stateConnectionString ="tcpip=localhost:42424" stateNetworkTimeout="5"/>


if you running a web application just restart your IIS. your session information will be lost. if you have done
done above settings then it will not loose your session values either your app reset or anything happen.
one thing if you run your website after doing these setting and you have already restarted the IIS just now.
then it will give error. because we have not started the state server. To start state server go to control panel
and open services then start the ASP.NET State  Service.
Figure 5- Enabling ASP.NET State Service
now it will work fine.
2. SQLServer
To use State Server do the following:
<sessionState  mode="SQLServer" sqlConnectionString="datasource=.; integrated security=true"
sqlCommandTimeout="5"/>
To manage session information in SQL Server, you have to create some Database, table in the SQL Server.
If you want to use temporary storage in  tempdb to provide tables for storing information, then you have to
create table there
using .net framework specified SQL Script.
these scripts are stored in the  directory C:\Windows\Microsoft.NET\Framework\v2.0.50727.
to create table in the tempdb, the script file name is InstallSqlState.sql.
If you want to save State Information Permanently then use another Script InstallPersistSqlState.sql.
it will crate a  new database with the required table to store the state information.
open query Analyzer and run these script in the database.
Remember:
if tempdb files are installed then iwill not save to the ASPState_db (permanent Storage database that
will be create after running the InstallPersistSqlState.sql.
*first it check tempdb data table then your permanent storage database.
*your connection string dost not specify db name because .net know the DB name.