Monday, 1 June 2015

Detecting Page Refresh in ASP.Net


Detecting Page Refresh in ASP.Net

There are certain Scenario when we want to detect whether the page was refreshed or not. Or, Whether It was a Postback or a F5 Refresh.. The following Code Snippet will help you out to resolve this Issue..

Design Part:



 <asp:Label ID="Label1" runat="server"></asp:Label>
 
    <asp:Button ID="Button1" runat="server" Text="Do postback at server side"
        onclick="Button1_Click" />


Coding:


private bool IsPageRefresh = false;
        public bool IsPageRefresh1
        {
            get { return IsPageRefresh; }
            set { IsPageRefresh = value; }
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["postids"] = System.Guid.NewGuid().ToString();
                Session["postid"] = ViewState["postids"].ToString();
            }
            else
            {
                if (ViewState["postids"].ToString() != Session["postid"].ToString())
                {
                    IsPageRefresh = true;
                }
                else
                {
                    IsPageRefresh = false;
                }
                Session["postid"] = System.Guid.NewGuid().ToString();
                ViewState["postids"] = Session["postid"].ToString();
            }
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!IsPageRefresh1)
            {
                Label1.Text = "Page do normal postback";
            }
            else
            {
                Label1.Text = "Page refresh";
            }
        }

Now Check the Output by pressing F5 Key and by clicking the Button..

Fetch Machine Information C#.Net


Fetch Machine Information C#.Net

The following Code Snippet will help you to fetch the Machine/System Info like Processor Details, Machine Name, IP Address..

Create a Class File Named MachineInfo.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Net;
using System.Diagnostics;
 
namespace GenericErrorHandling
{
    class MachineInfo
    {
        ManagementObjectSearcher query;
        ManagementObjectCollection result;
        string responseString;
        int responseInt;
 
        public string GetMachineName()
        {
            return Environment.MachineName.ToUpper();
        }
        public string GetOSVersion()
        {
            return Environment.OSVersion.VersionString;
        }
        public string GetProcessorCount()
        {
            return Environment.ProcessorCount.ToString();
        }
        public string GetIPAddress()
        {
            IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] ipAddress = ipEntry.AddressList;
            return ipAddress[ipAddress.Length - 1].ToString();
        }
        public string GetTotalPhysicalMemory()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
            result = query.Get();
            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["TotalPhysicalMemory"].ToString());
            }
            responseInt = (responseInt / 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;
        }
        public string GetAvailablePhysicalMemory()
        {
            PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes");
            responseInt = ((int)Convert.ToInt64(counter.NextValue()) * (-1)) / (1024 * 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;
        }
 
        public string GetTotalVirtualMemory()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
            result = query.Get();
            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["TotalVirtualMemory"].ToString());
            }
            responseInt = (responseInt / 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;
        }
 
        public string GetAvailableVirtualMemory()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
            result = query.Get();
 
            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["AvailableVirtualMemory"].ToString());
            }
            responseInt = (responseInt / 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;
 
        }
        public string GetCpuFrequency()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
            result = query.Get();
            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["CurrentClockSpeed"].ToString());
            }
            responseString = responseInt.ToString() + " MHz";
            return responseString;
        }
    }
 
}


Then Use the following Code Snippet to get the detailed info of the target Machine:


private void button1_Click(object sender, EventArgs e)
        {
            MachineInfo M = new MachineInfo();
            string msg = "Number Of Processor : " + M.GetProcessorCount();
            msg += "\nProcessor MHZ : " + M.GetCpuFrequency();
            msg += "\nMachine Name : " + M.GetMachineName();
            msg += "\nGetOSVersion : " + M.GetOSVersion();
            msg += "\nGetIPAddress : " + M.GetIPAddress();
            msg += "\nGetTotalPhysicalMemory : " + M.GetTotalPhysicalMemory();
            msg += "\nGetAvailablePhysicalMemory : " + M.GetAvailablePhysicalMemory();
            msg += "\nGetTotalVirtualMemory : " + M.GetTotalVirtualMemory();
            msg += "\nGetAvailableVirtualMemory : " + M.GetAvailableVirtualMemory();
 
            MessageBox.Show(msg);
 
        }

Implementing Ping in ASP.Net


Implementing Ping in ASP.Net


In this Article We will see, how can we ping a host name/ address to check whether it is up or not..
Pinging can be of great help to detect the current status of a website or to check the availability of the Server...

First of All add the following Namespaces:


using System.Net;
using System.Net.NetworkInformation;
using System.Text;

Then Create the  Design Page using the Code below:


<asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc">
                <tr>
                    <td width="100" align="right" bgcolor="#eeeeee" class="header1">
                        Hostname/IP:
                    </td>
                    <td align="center" bgcolor="#FFFFFF">
                        <asp:TextBox ID="txtHost" runat="server"></asp:TextBox>
                        &nbsp;&nbsp;
                        <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
                    </td>
                </tr>
                <tr>
                    <td width="100" align="right" bgcolor="#eeeeee" class="header1">
                        Ping Results:
                    </td>
                    <td align="center" bgcolor="#FFFFFF">
                        <asp:TextBox ID="txtPing" runat="server" Height="400px" TextMode="MultiLine" Width="400px"></asp:TextBox>&nbsp;
 
                        <asp:Label ID="lblStatus" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
            <asp:Timer ID="Timer1" runat="server" Interval="4000" OnTick="Timer1_Tick">
            </asp:Timer>
        </ContentTemplate>
    </asp:UpdatePanel>


Finally Use the following Code Snippet in the Code Behind:


protected void Page_Load(object sender, EventArgs e)
        {
 
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                lblStatus.Text = "";
                sendSubmit();
            }
            catch (Exception err)
            {
                lblStatus.Text = err.Message;
            }
        }
 
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            if(txtHost.Text != "")
                sendSubmit();
        }
 
        public void sendSubmit()
        {
            Ping ping = new Ping();
            PingReply pingreply = ping.Send(txtHost.Text);
            txtPing.Text += "\r\nAddress: " + pingreply.Address + "\r\n";
            txtPing.Text += "Roundtrip Time: " + pingreply.RoundtripTime + "\r\n";
            txtPing.Text += "TTL (Time To Live): " + pingreply.Options.Ttl + "\r\n";
            txtPing.Text += "Buffer Size: " + pingreply.Buffer.Length.ToString() + "\r\n";
        }


What This Code will do for you is that It will ping the entered website in the text-box every 4 second and display the ping result in the textbox.

Check Browser Name Along-with Version C#.Net


Check Browser Name Along-with Version C#.Net


We can get the details of the Browser in which the web-application is running and using this information we can prevent running certain script or code if the browser is in-compatible..

Code-Snippet:



protected void Page_Load(object sender, EventArgs e)
        {
            System.Web.HttpBrowserCapabilities browser = Request.Browser;
            string s = "Browser Capabilities &lt;br/&gt;"
                + "Type = " + browser.Type + "&lt;br/&gt;"
                + "Name = " + browser.Browser + "&lt;br/&gt;"
                + "Version = " + browser.Version + "&lt;br/&gt;"
                + "Major Version = " + browser.MajorVersion + "&lt;br/&gt;"
                + "Minor Version = " + browser.MinorVersion + "&lt;br/&gt;"
                + "Platform = " + browser.Platform + "&lt;br/&gt;"
                + "Is Beta = " + browser.Beta + "&lt;br/&gt;"
                + "Is Crawler = " + browser.Crawler + "&lt;br/&gt;"
                + "Is AOL = " + browser.AOL + "&lt;br/&gt;"
                + "Is Win16 = " + browser.Win16 + "&lt;br/&gt;"
                + "Is Win32 = " + browser.Win32 + "&lt;br/&gt;"
                + "Supports Frames = " + browser.Frames + "&lt;br/&gt;"
                + "Supports Tables = " + browser.Tables + "&lt;br/&gt;"
                + "Supports Cookies = " + browser.Cookies + "&lt;br/&gt;"
                + "Supports VBScript = " + browser.VBScript + "&lt;br/&gt;"
                + "Supports JavaScript = " +
                    browser.EcmaScriptVersion.ToString() + "&lt;br/&gt;"
                + "Supports Java Applets = " + browser.JavaApplets + "&lt;br/&gt;"
                + "Supports ActiveX Controls = " + browser.ActiveXControls
                      + "&lt;br/&gt;"
                + "Supports JavaScript Version = " +
                    browser["JavaScriptVersion"]  + "&lt;br/&gt;&lt;br/&gt;";
 
             
 
            Response.Write(s);
 
            switch (browser.Browser.ToUpper().Trim())
            {
                // WHY No OPERA BROWSER,because opera and chrome user agent is same, 
                // the browser.Browser will return Chrome value in Opera
                case "CHROME": Response.Write("<b>application support your browser</b>"); break;
                case "INTERNETEXPLORER": Response.Write("<b>application does not support your browser</b>"); break;
                case "FIREFOX": Response.Write("<b>application support your browser</b>"); break;
                case "SAFARI": Response.Write("<b>application support your browser</b>"); break;
                default: break;
            }
        } 
back to top