Thursday, February 2, 2012
Thursday, October 13, 2011
Difference between ref and out parameters in c#
Posted by
Vipin
at
11:44 AM
The difference between ref and out parameters is at the language level. In case of ref you must have to assign it as in "Example by ref" string val is assigned.
In case of out you don't need to assign an out parameter before passing it to a method. But the out parameter in that method must assign the parameter before returning.
Example In case of out you don't need to assign an out parameter before passing it to a method. But the out parameter in that method must assign the parameter before returning.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Example by ref");
string val = "hello";
ExampleByRef(ref val);
Response.Write(val);
Response.Write("Example by out");
string vals;
ExampleByOut(out vals);
}
public static void ExampleByRef(ref string val)
{
if (val == "hello")
{
System.Web.HttpContext.Current.Response.Write("Example by ref case");
}
else
{ System.Web.HttpContext.Current.Response.Write("Example by ref else response"); }
val = "hi";
}
public static void ExampleByOut(out string vals)
{
vals = "Example by Out case";
System.Web.HttpContext.Current.Response.Write(vals);
}
}
Output
Example by ref
Example by ref case
hi
Example by out
Example by Out case
Wednesday, September 14, 2011
Track User status if user closes the browser window.
Posted by
Vipin
at
2:03 PM
This is a sample application of "User Status" tracking in asp.net. When the user is logged in. This will show the user status as online user. If the user click on logout then it automatically logout user and update the user status as off line. But what if the user closes the browser then also you can track the status.
Here in this example I have used SQL server as database. I have created a table [tbluserlogins] in database with a "userstatus" column as bit datatype. Every time I update the "userstatus" when user logged in and logged out.
Sample Table Structure
Download the sample code
Here in this example I have used SQL server as database. I have created a table [tbluserlogins] in database with a "userstatus" column as bit datatype. Every time I update the "userstatus" when user logged in and logged out.
Sample Table Structure
CREATE TABLE [dbo].[tblUserLogins]( [sno] [int] IDENTITY(1,1) NOT NULL, [username] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [password] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [userStatus] [bit] NOT NULL, [lastLogin] [datetime] NOT NULL CONSTRAINT [DF_tblUserLogins_lastLogin] DEFAULT (getdate()), CONSTRAINT [PK_tblUserLogins] PRIMARY KEY CLUSTERED ( [username] ASC )WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]1. We have to maintain the session state like this
2. In global.asax there we can update the status.
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
//Update the user status if the application is closed
try
{
SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.Text, "update tblUserLogins set userStatus='false' where sno=" + Session["userid"].ToString(), null);
}
catch (Exception ex)
{
throw ex;
}
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
//If the user close the browser window or session is end. It will automatically update the staus
try
{
SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.Text, "update tblUserLogins set userStatus='false' where sno=" + Session["userid"].ToString(), null);
}
catch (Exception ex)
{
throw ex;
}
}
Download the sample code
Monday, June 13, 2011
Client Callbacks in ASP.NET
Posted by
Vipin
at
1:24 PM
Some time a situation comes wherein you want to process some server side processing without refreshing the whole page. This can be achived by using Microsoft ajax controls like "UpdatePanel" but some time you want to implement a functionality on your own in that case you can use your own client Callbacks.
For this first we will implement the System.Web.UI.ICallbackEventHandler. The ICallbackEventHandler has two methods.
1. GetCallbackResult : This method will return the reslut of server side processing.
2. RaiseCallbackEvent : This method will be called by client and you can use it to get the parameter values from client.
In this example I have used a Textbox and getting the value of that text box value in a lable while typing in textbox.
Code
Download Code
For this first we will implement the System.Web.UI.ICallbackEventHandler. The ICallbackEventHandler has two methods.
1. GetCallbackResult : This method will return the reslut of server side processing.
2. RaiseCallbackEvent : This method will be called by client and you can use it to get the parameter values from client.
In this example I have used a Textbox and getting the value of that text box value in a lable while typing in textbox.
Code
Welcome to ASP.NET!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CallbackExample
{
public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
string _result = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
//callback reference of the client-side function which will be called after the completion of server side processing.
string callbackRef = Page.ClientScript.GetCallbackEventReference(this, "args", "ClientFunction", "");
// Javascript function that will be called from client to call the server
string callBackFunctionScript = @"function CallServerFunction(args){" + callbackRef + "}";
// Now register the script on the page
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServerFunction", callBackFunctionScript, true);
}
public string GetCallbackResult()
{
//throw new NotImplementedException();
return _result;
}
public void RaiseCallbackEvent(string eventArgument)
{
_result = eventArgument;
}
}
}
Download Code
Wednesday, March 16, 2011
Import gmail address using asp.net c#
Posted by
Vipin
at
5:08 PM
Import email addresses like in any social networking site.Below example we have used to fetch the gmail address.
For this we require Google Data API and install the same to get the required dlls.
Add these dlls as reference in your project.
1. Google.GData.Client
2. Google.GData.Contacts
3. Google.GData.Extensions
Use .net framework 3.5 or 4.0
Code
Default.aspx.cs
Download Code
For this we require Google Data API and install the same to get the required dlls.
Add these dlls as reference in your project.
1. Google.GData.Client
2. Google.GData.Contacts
3. Google.GData.Extensions
Use .net framework 3.5 or 4.0
Code
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;
namespace GmailContacts
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region FETCH EMAIL IDS
private List FetchEmailIds(string emailid, string password)
{
List emaillist = new List();
try
{
RequestSettings Logindetails = new RequestSettings("", emailid, password);
Logindetails.AutoPaging = true;
ContactsRequest getRequest = new ContactsRequest(Logindetails);
Feed listContacts = getRequest.GetContacts();
foreach (Contact mailAddress in listContacts.Entries)
{
// Response.Write(mailAddress.Title + "
");
foreach (EMail emails in mailAddress.Emails)
{
EmailLists emailaddress = new EmailLists();
emailaddress.Title = mailAddress.Title;
emailaddress.EmailAddress = emails.Address;
//Response.Write(emails.Address + "
");
emaillist.Add(emailaddress);
}
}
}
catch (Exception)
{
Label1.Text = "Sorry your email id or password does not match.";
}
return emaillist;
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = FetchEmailIds(txtEmailId.Text, txtPassword.Text);
GridView1.DataBind();
}
#endregion
}
}
EmailLists.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GmailContacts
{
public class EmailLists
{
public string Title { get; set; }
public string EmailAddress { get; set; }
}
}
Download Code
Monday, February 28, 2011
Scheduling the task using WSH script
Posted by
Vipin
at
11:31 AM
Sometimes you need to do some automated task perform by the system itself, for a specific time period. You can do this by WSH script.
The below code uses to move the file from one folder to another folder at a specific time period
Code
Steps to install the script in Scheduled Task. Browse your .vbs file in Scheduled Task.
Download Code
The below code uses to move the file from one folder to another folder at a specific time period
Code
Dim OriginFolder, DestinationFolder, sFile, oFSO, oShell
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("Wscript.Shell")
OriginFolder = "d:\folder1"
DestinationFolder = "d:\folder2"
On Error Resume Next
Call MoveFiles()
Sub MoveFiles()
For Each sFile In oFSO.GetFolder(OriginFolder).Files
If Not oFSO.FileExists(DestinationFolder & "\" & oFSO.GetFileName(sFile)) Then
oFSO.GetFile(sFile).copy DestinationFolder & "\" & oFSO.GetFileName(sFile),True
oFSO.deleteFile(OriginFolder & "\" & oFSO.GetFileName(sFile))
End If
Next
End Sub
Steps to install the script in Scheduled Task. Browse your .vbs file in Scheduled Task.
Download Code
Sunday, January 30, 2011
A basic tutorial for WCF: Windows Communication Foundation
Posted by
Vipin
at
3:35 PM
What is WCF: Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it.
Why do we need this: This is the latest SOA technologies and it combines the features of Web Service,MSMQ,Remoting and COM+.
It provides a common plateform for all .NET communication. Interoperability is the fundamental characteristics of WCF.
ABC's of WCF: The 3 parts of the WCF. Address, Binding and Contract.
Address: Address is the address of the service. like (http://localhost:61685/Service1.svc)
Binding: It has number of binding models. It specifies the protocol to communicate.
Contract: Contract is the method exposed to the client. It gives the Data member serialization this is the main reason that it is faster than Webservice.
It includes Service Contract, Operation Contract and Data Contract
[Service Contract]: This attribute define saying which application interface will be exposed as service.
[Operation Contract]: It defines which method should be exposed to the external client, using this service.
[Data Contract]: Data Contract defines which type of complex data will be exchanged between the client and server.
The sample code is not a simple "Hello World" application. The sample includes a login system application.
It includes WCF host and one client. The host authenticate the user against a username and password, checked by WCF host and returns a boolean variable.The client includes a username and password screen, where user can put the username and password to authenticate the client application.
Download Code
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it.
Why do we need this: This is the latest SOA technologies and it combines the features of Web Service,MSMQ,Remoting and COM+.
It provides a common plateform for all .NET communication. Interoperability is the fundamental characteristics of WCF.
ABC's of WCF: The 3 parts of the WCF. Address, Binding and Contract.
Address: Address is the address of the service. like (http://localhost:61685/Service1.svc)
Binding: It has number of binding models. It specifies the protocol to communicate.
Contract: Contract is the method exposed to the client. It gives the Data member serialization this is the main reason that it is faster than Webservice.
It includes Service Contract, Operation Contract and Data Contract
[Service Contract]: This attribute define saying which application interface will be exposed as service.
[Operation Contract]: It defines which method should be exposed to the external client, using this service.
[Data Contract]: Data Contract defines which type of complex data will be exchanged between the client and server.
The sample code is not a simple "Hello World" application. The sample includes a login system application.
It includes WCF host and one client. The host authenticate the user against a username and password, checked by WCF host and returns a boolean variable.The client includes a username and password screen, where user can put the username and password to authenticate the client application.
Download Code
Subscribe to:
Posts (Atom)

