Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
1

Create a timestamp in c# (using Datetime)


Hi wondering how to create a timestamp in c# using Datetime values, use the method below. 
public static String GetTimestamp(this DateTime value)
{
    return value.ToString("yyyyMMddHHmmssffff");
}

0

How to use Stopwatch in C#


Create an object of Stopwatch class and start it, then execute the method, logic whose execution time is to be calculated. Next stop the watch shown below.

Stopwatch watch = new Stopwatch();
watch.Start();           

for (int i = 0; i < 100000; i++)
{
   for (int j = 0; j < 20000; j++)
   { 
                    // To waste some time....:P
   }
}
watch.Stop();
double time_wasted = watch.Elapsed.TotalSeconds;
// To round 
double time_wasted_rounded = Math.Round(watch.Elapsed.TotalSeconds);
0

Default button for ENTER key using C#

Sometimes you may want a button's on click event to occur on the press of the ENTER key.
In such cases there are a number of ways to do it.
I'll show you 2 of these many ways.


1. In your FORM element in your aspx page add an attribute

<form id="form1" runat="server" defaultbutton="Button1">
<div>
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
</div>
<form>
2. On page_load method add:

Form.DefaultButton = Button_Name.UniqueID;


0

Session Management For Grid View Control

I recently came across a situation, where I had to use session management for GRID VIEW CONTROL.


I had a search page where there was a grid displaying some data. Whenever a search was made, the data was fetched from the back end and displayed in the grid view. Now whenever the user navigates to another page and comes back to the search page, my gridview values should be still there. 
Use the code below in the appropriate place. 

// Store GridView in Session
Session["Test"] = GridView1;
GridView1 = null;


// Retrieve GridView from Session
GridView1 = (GridView)Session["Test"];


Hope this helps!
4

Add Row / Columns to GridView (Programmatically)


1) Create a DataTable object to which than we will bind the GridView

DataTable dt = new DataTable();
2) IF you need two columns than create two DataColumn objects

DataColumn dc1 = new DataColumn("first", typeof(string));

DataColumn dc2 = new DataColumn("second", typeof(string));
DataColumn dc3 = new DataColumn("third", typeof(string));

Add it to the table

dt.Columns.Add(dc1);

dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
3)Run the loop for as many rows you want to add. eg: 3 rows to be added.

for(int i=0;i<3;i++)// 3 = number of rows needed.

{
   DataRow row1 = dt.NewRow();
   int c = 0;
   while (c < 3)
   {
       row1[c] = "some_data";
       c++;
   }
   dt.Rows.Add(row1 );
}

Now iterate through each datacolumn and create a BoundField foreach column

foreach (DataColumn col in dt.Columns)

{
BoundField bField = new BoundField();
bField.DataField = col.ColumnName;
bField.HeaderText = col.ColumnName;
GridView1.Columns.Add(bField);
}

GridView1.DataSource = dt;
//Bind the datatable with the GridView.
GridView1.DataBind();
And you have successfully added rows/cols to the grid !
0
Database Basics using C#:


The following demonstrates a Register Page where the user is allowed to register, by entering a username and password. These inputs are saved in a table in database and later verified when user wants to login using the login page.

Section I:
Code for Register Page

    String ConnString = “--Your Connection_String goes here--";
    SqlConnection con = new SqlConnection(ConnString);

    String Command = ”insert into TABLE_NAME values(@username,@password)”;
    SqlCommand cmd = new SqlCommand(command, con);

    con.Open();

    cmd.Parameters.Add(“@username”, SqlDbType.Text).Value = Textusername.Text;
    cmd.Parameters.Add(“@password”, SqlDbType.Text).Value = Textpassword.Text;

    int a = cmd.ExecuteNonQuery();

    if (a > 0)
    {
        Response.Redirect(“~/Login.aspx”);
    }
    else
    {
        lablel.ForeColor = System.Drawing.Color.Red;
        label.Text = “Error Occured!”;
    }

Section II:
Code for Login Page


SqlConnection con = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter(“select * from userinfo”, con);
DataSet ds = new DataSet();
da.Fill(ds, “info”);

string username = Textusername.Text;
string password = Textpassword.Text;

int find = 0;
foreach (DataRow dr in ds.Tables["info"].Rows)
{
    if (username == dr["username"].ToString())
    {
        if (password == dr["password"].ToString())
        {
        find = 1;
        break;
        } // end of 1st if
    }// end of 2nd if
} // end of for each

if (find == 1)
{
    Response.Redirect(“~/Home.aspx”);
}
else
{
    Labelerror.ForeColor = System.Drawing.Color.Red;
    Labelerror.Text = “Username Password Mismatch”;
}



0

Simple AJAX Tutorial



As usual, we will use the good old "Hello, world!" as our very first example. We will begin with the code, and then we'll do a bit of explanation afterwards. If you haven't already done so, you should create a new ASP.NET website project in Visual Web Developer. The IDE will create a Default.aspx and Default.aspx.cs file for you, which will look just like any other ASP.NET enabled page. Let's add some AJAX to it:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Hello, world!</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="MainScriptManager" runat="server" />
        <asp:UpdatePanel ID="pnlHelloWorld" runat="server">
            <ContentTemplate>
                <asp:Label runat="server" ID="lblHelloWorld" Text="Click the button!" />
                <br /><br />
                <asp:Button runat="server" ID="btnHelloWorld" OnClick="btnHelloWorld_Click" Text="Update label!" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>
In the CodeBehind, there's nothing new except for this event which you should add:
protected void btnHelloWorld_Click(object sender, EventArgs e)
{
    lblHelloWorld.Text = "Hello, world - this is a fresh message from ASP.NET AJAX! The time right now is: " + DateTime.Now.ToLongTimeString();
}
In the markup part, we use two new things, when compared to regular ASP.NET: The ScriptManager control and the UpdatePanel control. The ScriptManager makes sure that the required ASP.NET AJAX files are included and that AJAX support is added, and has to be included on every page where you wish to use AJAX functionality. After the manager, we have one of the most used controls when working with AJAX, the UpdatePanel. This control allows you to wrap markup which you would like to allow to be partially updated, that is, updated without causing a real postback to the server. More about the UpdatePanel in a coming chapter. Besides those two controls, everything else is standard controls, with no modifications that would indicate alternate behavior.

Try running the example site, and click the button. The label will be updated with our usual Hello world text, and the current time. Try repeatedly clicking the button, and you will see the label get the current timestamp each time. Notice the wonderful absence of a blinking window and a running status bar - everything is done without updating anything but the label! We've just created our first AJAX enabled page
1

C# Encryption Decryption (Asymmetric key)


Hi,
Asymmetric key encryption uses different keys for encryption and decryption. These two keys are mathematically related and they form a key pair. One of these two keys should be kept private, called private-key, and the other can be made public (it can even be sent in mail), called public-key. Hence this is also called Public Key Encryption.
Simple as it may sound, but it trouble me for a week, as I could not find any good articles after googling so many days. Going through the API’s I stumbled upon few classes (RSACryptoServiceProvider) and methods that really helped me a LOT.
So here I am writing this article, to help all those looking for the same.
Firstly you will need to install a certificate, of which public and private key you intend to use. Once installed the certificate can be viewed in Internet Explorer > Tools Internet Options > Content Certificates.
There you will find a lot of information related to the installed certificates, such as Issuer Name, Expiry Date, etc. But the most important one for now is the SERIAL NUMBER.
Copy this SERIAL NUMBER and save it.
Now use, the following code to get your (required) certificate.
public X509Certificate2 Get_Certificate(string serial_number)
{
X509Certificate2 x_cert2 = null;
X509Store x_store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
X509Store newstore = new X509Store(x_store.Name);
x_store.Open(OpenFlags.ReadOnly);
int count = x_store.Certificates.Count;
foreach (X509Certificate2 cert2 in x_store.Certificates)
{
string s = cert2.SerialNumber;
if (cert2.SerialNumber == serial_number)
{
x_cert2 = cert2;
}
}
return x_cert2;
}

This will return the certificate with the matching serial number.
Now, the next step is to Encrypt the message (which i have assumed to be of type string.) using the public key and later decrypt using private key. (You may also do the other way round.)
Use the following function to encrypt: Here we have passed the certificate found previously (using the function written above) and the message which is to be encrypted. RSACryptoServiceProvider is the class which we have used, i suggest you explore this class a bit using the API’s.
public string Encrypt_Message(string str_msg, X509Certificate2 cert)
{
//Gets the public key.
string public_key = cert.GetPublicKeyString();
// Encrypts the message using public key.
var providerSender = (RSACryptoServiceProvider)cert.PublicKey.Key;
var plainSender = Encoding.ASCII.GetBytes(str_msg);
var cipher = providerSender.Encrypt(plainSender, false);
string e_msg = Encoding.Default.GetString(cipher);
return e_msg;
}

Now you have the encrypted message with you, now you may need to decrypt it using  the private key of the same certificate for that use the following.
public string Decrypt_Message(string encryptd_message, X509Certificate2 cert)
{
// Decrypts the Encrypted message using the private key.
var providerReceiver = (RSACryptoServiceProvider)cert.PrivateKey;
var plainReceiver = providerReceiver.Decrypt(Encoding.Default.GetBytes(encryptd_message), false);
string decryptd_message = Encoding.Default.GetString(plainReceiver);
return decryptd_message;
}

And you’ll have the decrypted message. Hope this will be helpful. If you have any question or suggestion related to the article, feel free to leave a reply. tc. :)
0

Create Window Services using C#

Step 1: Open a new Window Service Project

Start Microsoft Visual Studio, (I have used 2010) Select Add a new project and select Windows Service and select a language of your preference,(i have used C#) give a suitable name to your project and click ok.
Now in the solution explorer you will see a WindowService.cs file, rename it to some name you can remember (eg: your name).

Step 2: Functions OnStart(), OnStop().
As you can see in the web service .cs file, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service.

protected override void OnStart(string[] args)
{
System.Diagnostics.Process.Start(“notepad”);
}
protected override void OnStop()
{
System.Diagnostics.Process.Start(“mspaint”);
}

I am opening a notepad.exe” application when this services is started and opening a “paint” application when this service is stopped, this i am doing for us just to understand when a service is started and stopped.

Step3 :Install and Run the Service

Before installing the service be sure to add an installer, by right clicking on the .cs file and selecting the add new installer option, after which two components will be added : serviceProcessInstaller and serviceInstaller, now goto the serviceProcessInstaller properties tab and change the Account property to LocalService !
Build this application, a .exe file will be created in your debug folder, now Access the directory in which your project’s compiled executable file is located.
Run InstallUtil.exe from the command line with your project’s output as a parameter. Enter the following code on the command line:
 
installutil yourproject.exe
installutil /u yourproject.exe

The second command is used when you want to uninstall the service.
(In some cases you may get an error as installutil is not a recognised command or so, if such error occurs then simply use the full path of installutil.exe as C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil followed by the applicationName.exe)

Step 4: Start and Stop the Service

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer.
Under Services and Applications,  after clicking on services tabyou will see the service yasserService.

Start the service and Stop the service.
 

2011 ·Code-Studio by yrus.