Pages

Monday, 5 December 2011

how to get client ip in asp.net(c#.Net)

Introduction:

In this article I will explain how to find system or client machine IP address from which user visited the website in asp.net behind proxy in c#.

Description:
  
Now I will explain how to get system or client IP address of machine from which the user visited the website in asp.net
in c#. To implement this one write the code as shown below
 
protected void Page_Load(object sender, EventArgs e)
{
string IPAdd = string.Empty;
IPAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(IPAdd))
IPAdd = Request.ServerVariables["REMOTE_ADDR"];
lblIP.Text = IPAdd;
}
//or
protected void Page_Load(object sender, EventArgs e)
{
IPAddress myIP = IPAddress.Parse(Request.UserHostName);

IPHostEntry GetIPHost = Dns.GetHostEntry(Request.UserHostName);

Response.Write(GetIPHost.HostName);
}

If you observe above code when users behind any proxies or routers the REMOTE_ADDR/Request.UserHostName returns the IP Address of the router and not the client user’s machine. Hence first we need to check HTTP_X_FORWARDED_FOR/Request.UserHostName, since when client user is behind a proxy server his machine’s IP Address the Proxy Server’s IP Address is appended to the client machine’s IP Address.

Connect the remote desktop using c#.net


Introduction

Remote Desktop Services is one of Microsoft Windows components to access a remote computer through the network. Only the user interface of the application is presented at the client. Any input is redirected over to the remote computer over the network.
At work, we use Remote Desktop a great deal. It allows us to login to a remote server to perform health checks, deploy applications, troubleshoot problems, etc. We also use remote desktop often when we do WFH (work from home).
Why do you want to write a .NET application to do this when you have the MS Terminal Services client available from OS? Well, consider if you want to work on 3 different application servers at the same time and want to toggle between these 3 servers quite often. With the MSTSC, we will be running 3 different clients for the 3 servers and it is difficult to manage the working environment. In .NET, you can develop an application with tab control to load remote desktop sessions in different tabs in one window.

Background

We will be using AxMSTSCLib an ActiveX component in our program to connect to the remote computer. It’s not that hard to build a remote desktop application in .NET. Microsoft has a “Microsoft RDP client control” ActiveX control that we will be using in our application.

This is How We Do It

We will start by creating a Windows application in the Visual Studio IDE.
Add a reference to “Microsoft Terminal Services Control Type Library” from the COM tab. This will add MSTSCLib.dll to the project.

 
To add MSTSC to the toolbox, right click the toolbox and select “Choose Items…”. Now add “Microsoft Terminal Services control from the COM tab.

Drag the newly added control from toolbox to the form. Add 3 textbox and 2 button controls to the form:


Connect Button - Click Event

Here is how we write the Connect button click event. Now assign the properties (Server, UserName) of RDP control with the textbox values. Here’s how easy it is to login to remote machine. However there is one catch, there is no direct method in RDP control through which you can pass the username and password to login to the remote desktop. Due to security reasons, you have to implement an interface (IMsTscNonScriptable) to cast it separately.
 private void button1_Click(object sender, EventArgs e){
try
{
rdp.Server = txtServer.Text;
rdp.UserName = txtUserName.Text;

System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply pingReply = ping.Send(rdp.Server);
if (pingReply.Status == IPStatus.Success)
{
IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
secured.ClearTextPassword = txtPassword.Text;
rdp.Connect();
}
}

catch (Exception Ex)
{
MessageBox.Show("Error Connecting RDC", "Error connecting to remote desktop " + txtServer.Text + " Error: " + Ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Disconnect Button – Click Event

To disconnect from the remote desktop session, we just need to call the Disconnect() method.
Before disconnecting, we want to ensure that the connection is still available. We don't want to disconnect if it is already disconnected (very clever, huh).
 private void button2_Click(object sender, EventArgs e){
try
{
// Check if connected before disconnecting
if (rdp.Connected.ToString() == "1")
rdp.Disconnect();
}
catch (Exception Ex)
{
MessageBox.Show("Error Disconnecting", "Error disconnecting from remote desktop " + txtServer.Text + " Error: " + Ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

 

please put the comments..............

Calculate age depending on dateofbirth using c#.net

Here I will explain Calculating dateofbirth in c#.net

//Date of Birth

DateTime dateOfBirth = new DateTime(1992, 06, 10);
//Current date
DateTime currentDate = DateTime.Now;
int ageInYears = 0;
int ageInMonths = 0;
int ageInDays = 0;
//Calculate days
ageInDays = currentDate.Day - dateOfBirth.Day;
//Calculate Months
ageInMonths = currentDate.Month - dateOfBirth.Month;
//Calculate Years
ageInYears = currentDate.Year - dateOfBirth.Year;
//leaf years
if (ageInDays < 0)
{
ageInDays +=
DateTime.DaysInMonth(currentDate.Year, currentDate.Month);
ageInMonths = ageInMonths--;
if (ageInMonths < 0)
{
ageInMonths += 12;
ageInYears--;
}
}

if (ageInMonths < 0)
{
ageInMonths += 12;
ageInYears--;

Console.WriteLine("Age in Years :{0}, Months : {1}, Days : {2}", ageInYears, ageInMonths, ageInDays);

 

Thursday, 17 November 2011

Slide Show In asp.net


I had been looking for the source of a web-based slide show. The features I wanted in my slide show pages were that it should dynamically select a picture in the server to display, it should display some transition effects, and it should not cause page refreshing. But I couldn’t find one of this kind. So I decided to code it myself.There is a lot of source code to make the transition effect using JavaScript. But to address the dynamic selection of the picture to display and to avoid the page from refreshing, I used AJAX. There are a lot of AJAX frameworks and tools out there to choose from. But for this simple task, I just used the ASP.NET2’s built-in AJAX supported class system.Web.UI.ICallbackEventHandler.

The included source code will demonstrate the use of this class, and also how to use JavaScript to make the request to get the next image file and apply the transition effects. One thing I need to mention is when applying transition effects, the next image has to be completely loaded before playing the effect, otherwise, the picture display will not be smooth and will be flickering. I also address this in my JavaScript code.


//.aspx page
<img id="photo" src="" runat="server" border="0" style="height: 150px; width: 400px;" />

//javascript function
<script type="text/javascript">
 //A timer will be fired in 5 seconds to call getNextImage()
 var c_interval = 5000;
window.setTimeout("getNextImage()", c_interval);
function getNextImage() {
 //Send the request to server with the current image url as the argument
CallServer(document.getElementById("photo").src, "")
}
function ReceiveServerData(rValue) {
 //Receive server's response of a string rValue, which is prepared in the server's function
//GetCallbackResult()
 var wds = rValue.split(";");
 //Assign the transition effect
 document.getElementById("photo").style.filter = wds[1];
 //Preload the image file from server. When finishing download, imageLoaded function will be called
 //with the img object as the argument
 var img = new Image();
 img.onload = function () { imageLoaded(this); }
img.onerror = function () { imageError(this); }
 img.onabort = function () { imageError(this); }
 img.src = wds[0];
}
function imageError(img) {
 //If image download errors occur, this function will be called.
 window.setTimeout("getNextImage()", 1000);
}
function imageLoaded(img) {
var photo = document.getElementById("photo"); //Find the image control object
photo.filters[0].apply(); //Apply the transition effect
photo.filters[0].play(); //Play the effect and display the new image
photo.src = img.src; //Assign the image to the image control
window.setTimeout("getNextImage()", c_interval); //Initiate the next request
 }
</script>


//.cs file
string m_lastFileName = "none";
protected void Page_Load(object sender, EventArgs e)
 {if (IsPostBack)
     return;
  photo.Src = GetNextImageUrl();
//Register Ajax client script to client's browsers. This has to be hard coded.
 string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
 string callbackScript = "function CallServer(arg, context)" + "{ " + cbReference + "} ;";
 Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
}
public void RaiseCallbackEvent(string eventArgument)
 {
//This is first place to receive the callback from client's browser. The parameter 'eventArgument'
 //is the parameter passed from the Javascript's call 'CallServer()'. In this example, it is the
 //last image url.
 m_lastFileName = Path.GetFileName(eventArgument);
 }
public string GetCallbackResult()
{
//This is the second call triggled by the 'CallServer()' and it is the place to prepare and return a string
 //to the client. Here the returned string is the image url and the transition effect.
 return GetNextImageUrl() + ";" + GetNextTransition();
 }
private string GetNextImageUrl()
 {
//Randomly pick a image file in the server.
 string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "Images", "*.jpg");
if (files.Length == 0)
    return string.Empty;
while (true)
 {
int n = (int)((files.Length - 1) * (new Random()).NextDouble());
 //Do not want to repeat the last image
 if (files[n].IndexOf(m_lastFileName) < 0)
 {
return files[n].Replace(AppDomain.CurrentDomain.BaseDirectory, string.Empty);
 }
}
}
private string GetNextTransition()
 {
//Randomly pick a transition effect. Note some of the effects only work in IE.
 int n = (int)((new Random().NextDouble()) * 5);
 switch (n)
 {
case 0:
 case 1:
 n = (int)((new Random().NextDouble()) * 22);
 return "revealTrans(duration=2,transition=" + n.ToString() + ")";
 case 2:
 case 3:
 if (Request.Browser.Browser == "IE")
{
n = (
int)((new Random().NextDouble()) * 8);
 switch (n)
 {
case 0:
 return "progid:DXImageTransform.Microsoft.RandomDissolve()";
 case 1:
 return "progid:DXImageTransform.Microsoft.Pixelate(MaxSquare=20, Duration=2, Enabled=false)";
 case 2:
 return "progid:DXImageTransform.Microsoft.RadialWipe(wipeStyle='clock')";
 case 3:
 return "progid:DXImageTransform.Microsoft.Wheel(spokes=4)";
 case 4:
return "progid:DXImageTransform.Microsoft.Stretch(stretchStyle='spin')";
 default:
 return "progid:DXImageTransform.Microsoft.Stretch(stretchStyle='push')";
 }
}
else
 return "blendTrans(duration=2)";
 default:
 return "blendTrans(duration=2)";
 }
}