Tuesday, December 22, 2009

How to add CheckedListBox Items Programmatically in windows application?

C#
         ArrayList US = new ArrayList();
            US.Add(new country("India", "Ind"));
            US.Add(new country("Austria", "Ans"));
            US.Add(new country("Malaysia", "Mal"));

            checkedListBox1.DataSource = US;
            checkedListBox1.DisplayMember = "County";
            checkedListBox1.ValueMember = "SCode";

   public class country
        {
            private string Contry;
            private string code;

            public country(string strLongName, string strShortName)
            {

                this.Contry = strShortName;
                this.code = strLongName;
            }

            public string SCode
            {
                get
                {
                    return Contry;
                }
            }

            public string County
            {

                get
                {
                    return code;
                }
            }

        }
 String str=checkedListBox1.SelectedValue.ToString();

Sunday, December 20, 2009

BusinessLayer and Presentation Layer - C#

Business Layer
using System;
using System.Data;
using System.Data.SqlClient;
using AcPro.DataLayer;

namespace AcPro.BusinessLayer
{
    ///
    /// Summary description for loging.
    ///

    public class login
    {
        public login()
        {
           
        }
        private string P_orgname;
        public string orgname
        {
            set
            {
                P_orgname=value;
            }
            get
            {
                return P_orgname;
            }
        }
        private string P_username;
        public string username
        {
            set
            {
                P_username=value;
            }
            get
            {
                return P_username;
            }
        }
        private string P_pwd;
        public string pwd
        {
            set
            {
                P_pwd=value;
             }
            get
            {
                return P_pwd;
            }
        }
        public DataSet Executesp()
        {
            string strsql="loginsuccess";
            SqlParameter[] prms;
            prms=new SqlParameter[3];
            prms[0]=new SqlParameter("@orgname",orgname);
            prms[1]=new SqlParameter("@username",username);
            prms[2]=new SqlParameter("@pwd",pwd);
            DataSet ds=DataAccess.ExecuteSql(strsql,prms);
            return ds;
        }
    }
}


Presentation Layer -C#


           Login is  Business Layer File Name
            login ln=new login();
            ln.orgname=Ddl_OrgName.SelectedItem.Text.Trim();
            Session["OrgName"]=Ddl_OrgName.SelectedItem.Text.Trim(); // For Display purpose -Muhil
            ln.username=txt_UserName.Text.Trim();
            Session["UserName"]=txt_UserName.Text.Trim(); //For Display purpose -Muhil
            ln.pwd=txt_Password.Text.Trim();
            DataSet ds=ln.Executesp();

DataLayer - C#


using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace AcPro.DataLayer
{
    ///
    /// Summary description for DataAccess.
    ///

   
    public class DataAccess
    {
        protected static SqlConnection Conn;
        protected static SqlTransaction sqlTrans;
        public DataAccess()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public static void OpenConnection()
        {
            string strConnectionString=ConfigurationSettings.AppSettings["ConnectionString"];
            Conn=new SqlConnection();
            if(Conn.State==ConnectionState.Open)
            {
                Conn.Close();
            }
            else
            {
                Conn.ConnectionString=strConnectionString;
                Conn.Open();
            }
        }
        public static void CloseConnection()
        {
            if(Conn!=null)
            {
                if(Conn.State==ConnectionState.Open)
                {
                    Conn.Close();
                }
                Conn=null;
            }
        }
        public static void BeginTransaction()
        {
            OpenConnection();

            //Begin the transaction
            sqlTrans=Conn.BeginTransaction();
        }

        ///
        /// Commits the Transaction
        ///

        public static void CommitTransaction()
        {
            sqlTrans.Commit();
            sqlTrans.Dispose();
            CloseConnection();
        }

        ///
        /// Rolls Back the Transaction
        ///

        public static void RollBackTransaction()
        {
            sqlTrans.Rollback();
            sqlTrans.Dispose();
            CloseConnection();
        }
        public static int ExecuteNonQuery(string CommandText,SqlParameter[] Params)
        {
            int intRecordsAffected;
            OpenConnection();
            SqlCommand cmdObj=new SqlCommand();
            sqlTrans=Conn.BeginTransaction();
            cmdObj.CommandType=CommandType.StoredProcedure;
            cmdObj.Connection=Conn;
            cmdObj.CommandText=CommandText;
            cmdObj.Transaction=sqlTrans;
            if (Params.Length>0)
            {
                for (int i=0;i
                {
                    cmdObj.Parameters.Add(Params[i]);
                }
            }           
                try
                {
                    intRecordsAffected=cmdObj.ExecuteNonQuery();
                    sqlTrans.Commit();                   
               
                }
                catch(SqlException e)
                {
                    sqlTrans.Rollback();
                    throw e;
                }
           
            cmdObj.Dispose();
            CloseConnection();
            return intRecordsAffected;
        }
        public static int ExecutiveSclar(string CommandText, SqlParameter[] Params)
        {
            OpenConnection();
            SqlCommand cmdObj=new SqlCommand(CommandText,Conn);
            cmdObj.CommandType=CommandType.StoredProcedure;
            if(Params.Length>0)
            {
                for(int i=0;i
                {
                    cmdObj.Parameters.Add(Params[i]);
                }
            }
            int HeadPk=Convert.ToInt32(cmdObj.ExecuteScalar());
            cmdObj.Dispose();
            CloseConnection();
            return HeadPk;
        }
        ///
        ///  return values in dataset
        ///

        ///


        ///
        ///
        public static DataSet ExecuteSql(string CommandText, SqlParameter[] Params)
        {
            OpenConnection();
            SqlCommand cmdObj=new SqlCommand(CommandText,Conn);
            cmdObj.CommandType=CommandType.StoredProcedure;
            if(Params.Length>0)
            {
                for(int i=0;i
                {
                    cmdObj.Parameters.Add(Params[i]);
                }
            }
            SqlDataAdapter mySDA=new SqlDataAdapter(cmdObj);
            DataSet myDS=new DataSet();
            mySDA.Fill(myDS);
            //cmdObj.Dispose();
            CloseConnection();
            return myDS;

        }
        public static DataTable populateledger(String CommandText,SqlParameter[] Params)
              {
                 
                  OpenConnection();
                  SqlCommand cmdObj=new SqlCommand(CommandText,Conn);
                  cmdObj.CommandType=CommandType.StoredProcedure;      
                  if (Params.Length>0)
                  {
                      for (int i=0;i
                      {
                          cmdObj.Parameters.Add(Params[i]);
                      }
                  }
                  SqlDataAdapter mySDA=new SqlDataAdapter(cmdObj);
                  DataTable myDT=new DataTable();
                    myDT.Clear();
                  mySDA.Fill(myDT);   
                  mySDA.Dispose();
                 // cmdObj.Dispose();
            CloseConnection();
                  return myDT;
              }
        public static DataTable ExecuteTable(string strsql)
        {OpenConnection();
            DataTable dt=new DataTable();
            try
            {
                SqlDataAdapter da=new SqlDataAdapter(strsql,Conn);
                da.Fill(dt);
            }
            catch(Exception e)
            {
                throw e;
            }
            return dt;
        }
    }
}

Javascript Stuff

How to Clear Controls in Web-Page using JavaScript?
    function clearFormTextElements(Form)
    {  
        if( typeof( Form ) == "object" )
        {
            for(var i = 0; i <  Form.elements.length; i ++ )
            {
                if( Form.elements[i].type == "text" )
                    Form.elements[i].value = "" ;
                else
                Form.elements[i].selectedIndex=-1;
            }
        }
    }

Analog Clock

fCol='white';
sCol='FF00FF';
mCol='red';
hCol='green';
Ybase=50;
Xbase=50;
H='...';
H=H.split('');
M='... ';
M=M.split('');
S='....';
S=S.split('');
NS4=(document.layers);
NS6=(document.getElementById&&!document.all);
IE4=(document.all);
Ypos=0;
Xpos=0;
dots=12;
Split=360/dots;


document.write('div Style="position:absolute;top:0px;left:0px">

for (i=1; i less than dots+1; i++){
document.write('div id="ieDigits" style="position:absolute;top:0px;left:0px;width:30px;height:30px;font-family:Arial;font-size:10px;color:'+fCol+';text-align:center;padding-top:10px">'+i+'
');
}
document.write('/div>')
document.write('div style="position:absolute;top:0px;left:0px">
');
for (i=0; i less than M.length; i++){
document.write('div id=y style="position:absolute;width:2px;height:2px;font-size:2px;background:'+mCol+'">
');
}
document.write('/div>')
document.write('div style="position:absolute;top:0px;left:0px">
');
for (i=0; i less than H.length; i++){
document.write('div id=z style="position:absolute;width:2px;height:2px;font-size:2px;background:'+hCol+'">
');
}
document.write('/div>')
document.write('div style="position:absolute;top:0px;left:0px">
');
for (i=0; i less than S.length; i++){
document.write('div id=x style="position:absolute;width:2px;height:2px;font-size:2px;background:'+sCol+'">
');
}
document.write('/div>')



function clock(){
time = new Date ();
secs = time.getSeconds();
sec = -1.57 + Math.PI * secs/30;
mins = time.getMinutes();
min = -1.57 + Math.PI * mins/30;
hr = time.getHours();
hrs = -1.57 + Math.PI * hr/6 + Math.PI*parseInt(time.getMinutes())/360;
if (IE4){
Ypos=document.body.scrollTop+window.document.body.clientHeight-Ybase-20;
Xpos=document.body.scrollLeft+window.document.body.clientWidth-Xbase-20;
for (i=0; i < dots; ++i){
 ieDigits[i].style.pixelTop=Ypos-15+Ybase*Math.sin(-1.045 +i *Split*Math.PI/180)
 ieDigits[i].style.pixelLeft=Xpos-15+Xbase*Math.cos(-1.045 +i *Split*Math.PI/180)
 }
for (i=0; i < S.length; i++){
 x[i].style.pixelTop =Ypos+i*Ybase/4.1*Math.sin(sec);
 x[i].style.pixelLeft=Xpos+i*Xbase/4.1*Math.cos(sec);
 }
for (i=0; i < M.length; i++){
 y[i].style.pixelTop =Ypos+i*Ybase/4.1*Math.sin(min);
 y[i].style.pixelLeft=Xpos+i*Xbase/4.1*Math.cos(min);
 }
for (i=0; i < H.length; i++){
 z[i].style.pixelTop =Ypos+i*Ybase/4.1*Math.sin(hrs);
 z[i].style.pixelLeft=Xpos+i*Xbase/4.1*Math.cos(hrs);
 }
}
setTimeout('clock()',100);
}
clock();

How to Select all checkbox in CheckboxList ?

function selectall()
{

 for (var i=1; i <   document.forms(0).length; i++)
 { 
if(document.forms(0).elements[i].id )
     {
    if(document.forms(0).elements[i].id.indexOf("CheckBoxList1")!=-1)
      {
     document.forms(0).elements[i].checked=true;
      }
    }
 }
}


How to DeSelect all checkbox in CheckboxList using Javascript?

function deselectall()
{
 
 for (var i=1; i <   document.forms(0).length; i++)
 { 
if(document.forms(0).elements[i].id )
     {
    if(document.forms(0).elements[i].id.indexOf("CheckBoxList1")!=-1)
      {
     document.forms(0).elements[i].checked=false;
      }
    }
 }
}



Amount Field Validation

function fnCurrency(pCtlTextBox)
{
    var pNumKeyCode = window.event.keyCode;
    var pStrValue = pCtlTextBox.value;
    var pNumLength = pStrValue.length - 1;
    var pNumDeciPosi = pStrValue.indexOf(".");
    if (pNumLength < 0 && pNumKeyCode == 46)
    {    alert("Period Not allowed In First Position.");
        window.event.keyCode = 0;           
    }
    else if (pNumDeciPosi > 0 && pNumDeciPosi+2 == pNumLength)
    {   
        alert("After Period Only Two Numbers are Allowed.");
        window.event.keyCode = 0;
    }
    else if(pNumKeyCode > 47 && pNumKeyCode < 58)
    {
        window.event.keyCode = pNumKeyCode;
    }
    else if(pNumKeyCode == 46 && pNumDeciPosi < 0)
    {   
        window.event.keyCode = pNumKeyCode;
    }
    else
    {   
        alert("Only numeric values allowed.");
        window.event.keyCode = 0;
    }
}

How to Know No. Of users Logged In?

STEP 1 

Add below lines in  Global.asax File

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application.Add("UserCount", 0)
End Sub



Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)

Dim UserCount As Integer
UserCount = Convert.ToInt32(Application.Get("UserCount").ToString())
UserCount = UserCount + 1
Application.Set("UserCount", UserCount)
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Dim UserCount As Integer
UserCount = Convert.ToInt32(Application.Get("UserCount").ToString())
UserCount = UserCount - 1
Application.Set("UserCount", UserCount)
End Sub

Step: 2 
Add a Web.Config File

  < sessionState mode="InProc"/ >        

Step: 3
Code Behind


   TextBox1.Text = Application.Get("UserCount").ToString()


Monday, December 14, 2009

How to convert the string to DateTime ?

Common Function:

Public Function ConvertoDate(ByVal dateString As String,
 ByRef result As DateTime) As DateTime   
Try             
     Dim supportedFormats() As String = New String() 
{"dd/MM/yyyy", "MM/dd/yyyy", "MM/dd/yy", 
"ddMMMyyyy", "dMMMyyyy"}             
     result = DateTime.ParseExact(dateString, 
supportedFormats, System.Globalization.CultureInfo.
CurrentCulture, System.Globalization.DateTimeStyles.None)  
     Return result    
Catch ex As Exception   
    Return Nothing      
End Try    
End Function 
We should enter the Date below format. Then only it 
will convert into DateTime.

Dim supportedFormats() As String = New String() {"dd/MM/yyyy", 
"MM/dd/yyyy", "MM/dd/yy", "ddMMMyyyy", "dMMMyyyy"}


Calling the function

ConvertoDate(frmDate, TfrmDate)
frmDate - String
TfrmDate - DateTime object

Where does the Session Variables gets Stored?

Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property.

In an ASP.NET page, the current session variables are exposed through the Session property of the page object.

Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response.

By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a "cookieless" session.


By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file.






Different Session-State Modes

ASP.NET session state supports several different storage options for session data.

  1.       InProc mode, which stores session state in memory on the Web server. This is the default.
  2.       StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  3.       SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  4.      Custom mode, which enables you to specify a custom storage provider.
  5.      Off mode, which disables session state.

 In-Process Mode

In-process mode is the default session state mode and is specified using the InProc SessionStateMode enumeration value. In-process mode stores session state values and variables in memory on the local Web server. It is the only mode that supports the Session_OnEnd event

StateServer mode

StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The ASP.Net state service is installed at the following location:

systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe

SQL Server Mode

SQLServer mode stores session state in a SQL Server database. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

To use SQLServer mode, you must first be sure the ASP.NET session state database is installed on SQL Server. You can install the ASP.NET session state database using the Aspnet_regsql.exe tool

Example





Custom Mode

Custom mode specifies that you want to store session state data using a custom session state store provider. When you configure your ASP.NET application with a Mode of Custom, you must specify the type of the session state store provider using the providers sub-element of the sessionState configuration element. 


You specify the provider type using an add sub-element and include both a type attribute that specifies the provider's type name and a name attribute that specifies the provider instance name. 

The name of the provider instance is then supplied to the customProvider attribute of the sessionState element to configure ASP.NET session state to use that provider instance for storing and retrieving session data.

Examples



State Management Advantages and Disadvantages

ASP.Net State Management
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

client-side state management
  1.       View state
  2.       Control state
  3.       Hidden fields
  4.       Cookies
  5.       Query strings
View state
Web Forms pages provide the ViewState property as a built-in structure for automatically retaining values between multiple requests for the same page. View state is maintained as a hidden field in the page

Advantages of using view state:

  1.        The view state is contained in a structure within the page code.
  2.       View state does not require any custom programming to use. It is on by default to maintain state data on controls.
  3.        The values in view state are hashed, compressed, and encoded for Unicode implementations, which provides more security than using hidden fields.
Disadvantages of using view state:
  1.        Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.
  2.        Mobile devices might not have the memory capacity to store a large amount of view-state data.
  3.        The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue


Control State
The ASP.NET page framework provides the ControlState property as way to store custom control data between server trips

Advantages of using control state are:

  1.     By default, control state is stored in hidden fields on the page.
  2.     Because control state cannot be turned off like view state, control state is a more reliable method for managing the state of controls.
  3.     Custom adapters can be written to control how and where control-state data is stored.
Disadvantage of using control state are:
      Some programming is required   While the ASP.NET page framework provides a foundation for control state, control state is a custom state-persistence mechanism. To fully utilize control state, you must write code to save and load control state.

Hidden Fields

You can store page-specific information in a hidden field on your page as a way of maintaining the state of your page.If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.

Advantages of using hidden fields are:
  1.       The hidden field is stored and read from the page.
  2.       Almost all browsers and client devices support forms with hidden fields.
  3.      Hidden fields are standard HTML controls that require no complex programming logic.

Disadvantages of using hidden fields are:
  1.      The hidden field can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. You can manually encrypt and decrypt the contents of a hidden field, but doing so requires extra coding and overhead. If security is a concern, consider using a server-based state mechanism so that no sensitive information is sent to the client.
  2. The hidden field does not support rich data types. Hidden fields offer a single string value field in which to place information. To store multiple values, you must implement delimited strings and the code to parse those strings. You can manually serialize and de-serialize rich data types to and from hidden fields, respectively. However, it requires extra code to do so. If you need to store rich data types on the client, consider using view state instead. View state has serialization built-in, and it stores data in hidden fields.
  3.   Because hidden fields are stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
  4.   If the amount of data in a hidden field becomes very large, some proxies and firewalls will prevent access to the page that contains them. Because the maximum amount can vary with different firewall and proxy implementations, large hidden fields can be sporadically problematic

Cookies

Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server

Advantages of using cookies are:

  1.       The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.
  2.      The cookie is stored on the client and read by the server after a post.
  3.       The cookie is a lightweight, text-based structure with simple key-value pairs.
  4.      Although the durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention, cookies are generally the most durable form of data persistence on the client.

Disadvantages of using cookies are:
  1.         Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.
  2.        Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.
  3.        Users can manipulate cookies on their computer, which can potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although cookies are only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from other domains on a user's computer. You can manually encrypt and decrypt cookies, but it requires extra coding and can affect application performance because of the time that is required for encryption and decryption

Query Strings

A query string is information that is appended to the end of a page URL.

You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a simple but limited way of maintaining some state information. For example, query strings are an easy way to pass information from one page to another, such as passing a product number to another page where it will be processed.

Advantages of using query strings are:
  1.        The query string is contained in the HTTP request for a specific URL.
  2.     Almost all browsers and client devices support using query strings to pass values.
  3.       ASP.NET provides full support for the query-string method, including methods of reading query strings using the Params property of the HttpRequest object.
Disadvantages of using query strings are:
  1.       The information in the query string is directly visible to the user via the browser's user interface. A user can bookmark the URL or send the URL to other users, thereby passing the information in the query string along with it. If you are concerned about any sensitive data in the query string, consider using hidden fields in a form that uses POST instead of using query strings
  2.     Some browsers and client devices impose a 2083-character limit on the length of URLs.

Server-Side State Management Options

Server-side options for storing page information typically have higher security than client-side options, but they can use more Web server resources, which can lead to scalability issues when the size of the information store is large.

server-side state management options that ASP.NET supports:

  1.       Application state
  2.       Session state
  3.       Profile properties
  4.       Database support

Application State

ASP.NET provides application state via the HttpApplicationState class as a method of storing global application-specific information that is visible to the entire application. Application-state variables are, in effect, global variables for an ASP.NET application

Advantages of using application state are:

  1.        Application state is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  2.         Because application state is accessible to all pages in an application, storing information in application state can mean keeping only a single copy of the information.

Disadvantages of using application state are:

  1.       The scope of application state can also be a disadvantage. Variables stored in application state are global only to the particular process the application is running in, and each application process can have different values. Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm server configurations.
  2.       Because global data that is stored in application state is volatile, it will be lost if the Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.
  3.        Application state requires server memory, which can affect the performance of the server as well as the scalability of the application.

Session State

ASP.NET provides a session state, which is available as the HttpSessionState class, as a method of storing session-specific information that is visible only within the session. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides the ability to persist variable values for the duration of that session.


Advantages of using session state are:
  1.      The session-state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  2.        Session management events can be raised and used by your application.
  3.        Data placed in session-state variables can be preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing session data because the data is stored in another process space. Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web garden.
  4.        Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  5.       Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application. Using session state without cookies, however, requires that the session identifier be placed in the query string, which is subject to the security issues stated in the query string section of this topic.
  6. You can customize and extend session state by writing your own session-state provider. Session state data can then be stored in a custom data format in a variety of data storage mechanisms, such as a database, an XML file, or even to a Web service.

Disadvantage of using session state are:
      Performance considerations   Session-state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.


Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, the profile data is not lost when a user's session expires. The profile properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user.

The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile.

The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner

Advantages of using profile properties are:
  1.       Data placed in profile properties is preserved through IIS restarts and worker-process restarts without losing data because the data is stored in an external mechanism. Additionally, profile properties can be persisted across multiple processes, such as in a Web farm or a Web garden.
  2.      Profile properties can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  3.      In order to use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism, such as an XML file, or even to a Web service.

Disadvantages of using profile properties are:
  1.       Profile properties are generally slower than using session state because instead of storing data in memory, the data is persisted to a data store.
  2.       Unlike session state, the profile properties feature requires a considerable amount of configuration to use. To use profile properties, you must not only configure a profile provider, but you must pre-configure all of the profile properties that you want to store.
  3.       Profile properties require a certain amount of maintenance. Because profile data is persisted to non-volatile storage, you must make sure that your application calls the appropriate cleanup mechanisms, which are provided by the profile provider, when data becomes stale.

how to Pass Parameter values for Crystal Report in VB.Net?

Written one Common Function:

Public Function ShowReport(ByVal path As String, ByVal sParamFld As String, ByVal sParamVal As String, ByVal sReportViewer As CrystalDecisions.Web.CrystalReportViewer) As ReportDocument
        Dim tmpSortList As New SortedList
        Dim ParamLength As Int16 = 0, iLoop As Int16 = 0
        Dim ParamFld() As String, ParamFldVal() As String
        Try

            myReportDocument = New ReportDocument
            myReportDocument.Load(path)
            myReportDocument.SetDatabaseLogon(System.Configuration.ConfigurationManager.AppSettings("UserName").ToString(), System.Configuration.ConfigurationManager.AppSettings("Pwd").ToString())
            ParamFld = sParamFld.Split("*")
            ParamFldVal = sParamVal.Split("*")
            If ParamFld.Length <> ParamFldVal.Length Then
                Err.Raise(1, , "Parameter Fleid should be equal to Parameter Value")

            End If
            For iLoop = 0 To UBound(ParamFld)
                tmpSortList.Add(ParamFld(iLoop), ParamFldVal(iLoop))
            Next
            ParamFldDefn = myReportDocument.DataDefinition.ParameterFields
            ParamFldDefn.Reset()
            Dim tmpCount As Integer = 0
            sReportViewer.ReportSource = myReportDocument
            'sReportViewer.DataBind()
            sReportViewer.EnableParameterPrompt = False
            For tmpCount = 0 To tmpSortList.Count - 1
                myReportDocument.SetParameterValue(ParamFldDefn(tmpCount).Name, tmpSortList(ParamFldDefn(tmpCount).Name).ToString())
            Next
            Return myReportDocument
            'fnToolbarSetting()


        Catch ex As Exception
            ' lblErr.Text = ex.Message
            Return Nothing
        End Try
    End Function

Calling the above function:



path = Server.MapPath(".\AgtCancelingList.rpt")
            ParamFld = "@AgentCode*@FrmTranDate*@FrmToDate*AgentName*DisplyFr*DisplyTo"
            ParamVal = AgtCode.ToString() + "*" + TfrmDate + "*" + TToDate + "*" + AgtCode + "-" + AgtName + "*" + frmDate + "*" + TDate
            Dim tmp As ReportDocument = clsCommon.ShowReport(path, ParamFld, ParamVal, CRViewer)
@AgentCode - Store Procedure Parameter Field
AgentName - Crystal Report Parameter Field.

Wednesday, December 9, 2009

Error : "The query contains references to items defined on a different data context " in LINQ queries

Solution

can't do a join across servers You could have two separate LINQ queries, one against each server, and then join those two together:

Examples

var q1 = // get your data from your first server
var q2 = // get your data from your second server
var ResultData = from r1 in q1
join r2 in q2 on r1.Key equals r2.Key
select new { r1.Value1, r2.Value2 };


Real Time Examples
First DataBase Query


var WNotMast = (from objClmType in objWebNotDC.WNotMasts
select new

{

objClmType.TimeStamp,

objClmType.WUserKey,

objClmType.Id

}).ToList();

Second Database Query


var WUsers = (from objUsers in objRegDC.WUsers

join objUsrGrp in objRegDC.WUserGroups on
objUsers.WUserGroupKey equals objUsrGrp.WUserGroupKey

select new

{

objUsers.Name,

objUsers.WUserKey,

objUsers.WUserGroupKey,

objUsrGrp.Dsc

}).ToList();

Joined Both Database result

var Result = (from objResult in WNotMast

join objUsr in WUsers on objResult.WUserKey equals
objUsr.WUserKey

where objResult.TimeStamp > dtStartDt &&



orderby objUsr.Dsc

select new

{

ID = objResult.Id,

Time = objResult.TimeStamp,

Dsc = objUsr.Dsc,

UserKey = objUsr.WUserKey,

Name = objUsr.Name


}).ToList();