Seach

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

how to encrypt and decrypt a quire string c# asp.net

sender page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;//used for streams support
using System.Security.Cryptography;//used for security
using System.Text;//used for encoding
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    public static string Encrypt_QueryString(string str)
    {
        string EncrptKey = "god you are great";
            //"2013;[pnuLIT)WebCodeExpert";
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string val = Encrypt_QueryString(TextBox1.Text.Trim());
        Response.Redirect("Default2.aspx?EmpId=" + val);
    }
  }
redirecting page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.IO;
using System.Text;

public partial class Default2 : System.Web.UI.Page
{
    public static string Decrypt_QueryString(string str)
    {
        str = str.Replace(" ", "+");
        string DecryptKey = "god you are great";
            //"2013;[pnuLIT)WebCodeExpert";
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byte[] inputByteArray = new byte[str.Length];

        byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByteArray = Convert.FromBase64String(str);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        string Id = Decrypt_QueryString(Request.QueryString["EmpId"]);
        Response.Write("Emp Id =:" + Id);
    }
}

how to findout ip address in c# asp.net application

 String ip = System.Net.Dns.GetHostName();
        string myIP = System.Net.Dns.GetHostByName(ip).AddressList[0].ToString();

how to detect edition of the windows in c# asp.net

//Get Operating system information.
String os_;
        OperatingSystem os = Environment.OSVersion;
        //Get version information about the os.
        Version vs = os.Version;

        //Variable to hold our return value
        string operatingSystem = "";

        if (os.Platform == PlatformID.Win32Windows)
        {
            //This is a pre-NT version of Windows
            switch (vs.Minor)
            {
                case 0:
                    operatingSystem = "95";
                    break;
                case 10:
                    if (vs.Revision.ToString() == "2222A")
                        operatingSystem = "98SE";
                    else
                        operatingSystem = "98";
                    break;
                case 90:
                    operatingSystem = "Me";
                    break;
                default:
                    break;
            }
        }
        else if (os.Platform == PlatformID.Win32NT)
        {
            switch (vs.Major)
            {
                case 3:
                    operatingSystem = "NT 3.51";
                    break;
                case 4:
                    operatingSystem = "NT 4.0";
                    break;
                case 5:
                    if (vs.Minor == 0)
                        operatingSystem = "2000";
                    else
                        operatingSystem = "XP";
                    break;
                case 6:
                    if (vs.Minor == 0)
                        operatingSystem = "Vista";
                    else
                        operatingSystem = "7";
                    break;
                default:
                    break;
            }
        }
        //Make sure we actually got something in our OS check
        //We don't want to just return " Service Pack 2" or " 32-bit"
        //That information is useless without the OS version.
        if (operatingSystem != "")
        {
            //Got something.  Let's prepend "Windows" and get more info.
            operatingSystem = "Windows " + operatingSystem;
            //See if there's a service pack installed.
            if (os.ServicePack != "")
            {
                //Append it to the OS name.  i.e. "Windows XP Service Pack 3"
                operatingSystem += " " + os.ServicePack;
            }
            //Append the OS architecture.  i.e. "Windows XP Service Pack 3 32-bit"
            //operatingSystem += " " + getOSArchitecture().ToString() + "-bit";
        }
        //Return the information we've gathered.
        os_ = operatingSystem;
Response.Write(os_);

how to send email in c# asp.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SmtpClient sc = new SmtpClient("smtp.gmail.com", 587)
        {
            Credentials =new NetworkCredential("your mailid","your password"),EnableSsl=true       

        };
        sc.Send("from mail", "to mail", "subject", "body");
    }
}

inserting data into table by the help of parameters

 SqlConnection c = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\aspprojects\insertion\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
        try
        {
            c.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = c;
            cmd.CommandText = "insert into student values(@name,@age,@add)";
            cmd.Parameters.AddWithValue("@name", TextBox1.Text);
            cmd.Parameters.AddWithValue("@age",Convert.ToInt32(TextBox2.Text));
            cmd.Parameters.AddWithValue("@add", TextBox3.Text);
            cmd.ExecuteNonQuery();
            clear_();
        }
        catch (Exception e)
        {
            Response.Write(e.Message);
        }
        finally
        {
            c.Close();
        }

how to insert into table in c#

first import System.data.sqlclient;
 SqlConnection c = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\aspprojects\insertion\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
        try
        {
            c.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = c;
            cmd.CommandText = "insert into student values('"+TextBox1.Text+"','"+Convert.ToInt32(TextBox2.Text)+"','"+TextBox3.Text+"')";
            cmd.ExecuteNonQuery();
            clear_();
        }
        catch (Exception e)
        {
            Response.Write(e.Message);
        }
        finally
        {
            c.Close();
        }

How to Upload and display image and show full path of image

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    //System.String name, ext;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName.ToString());

        if (FileUpload1.HasFile)
        {
            if (fileExtension == ".jpg" || fileExtension == ".png")
            {
                string a = Server.MapPath("~/image/");
                FileUpload1.SaveAs(a + FileUpload1.FileName);


                Image1.ImageUrl = "~/image/" + FileUpload1.FileName;
                Label1.Text = FileUpload1.FileName;
                Label3.Text="~/image/" + FileUpload1.FileName;


            }

            else
            {

                Label2.Text = "invalid file extension";





             //   Label1.Text = "pls upload a file";


            }





        }

    }
}

HOW TO PROVIDE A CUSTOM LOGIN DEMO USING SQLSERVER WITH C#-ASP.NET

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; //public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { DropDownList1.SelectedItem.Text.ToLower();//TO GET THE SELECTED ITEM IN LOWERCASE if ((DropDownList1.SelectedItem.Text != "") && (TextBox2.Text != "")) { string ss = ConfigurationManager.ConnectionStrings["con"].ToString(); SqlConnection c = new SqlConnection(ss); try { c.Open(); SqlCommand cmd = new SqlCommand("select statement " ",c); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read())//FOR FETCHING EACH RECODE { if ((DropDownList1.SelectedItem.Text == "admin") && (TextBox2.Text == "admin")) { string s = DropDownList1.SelectedItem.Text.ToString(); //Server.Transfer("defalut3.aspx?name='"+s+"'"); Server.Transfer("abcd.aspx?name='"+s+"'"); } else if ((DropDownList1.SelectedItem.Text == dr[0].ToString()) && (TextBox2.Text == dr[1].ToString())) { string s1 = DropDownList1.SelectedItem.Text; Server.Transfer("default2.aspx?a='" + s1 + "'"); } else { //string jScript; //jScript = //""; // Page.RegisterClientScriptBlock("warning", jScript);//TO ENABLE CLIENT SIDE SCRIPTING IN CODE BEHIND FILE } } } finally { c.Close(); } } } }

simple file righting and reading


using System; 

using System.Collections.Generic; 

using System.ComponentModel;

 using System.Data;

 using System.Drawing; 

using System.Linq; 

using System.Text;

 using System.Windows.Forms;

 using System.IO;//used for io operations this name space is must for file manipulation namespace WindowsFormsApplication3

 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog();//for showing savedialog box FileStream f = new FileStream(saveFileDialog1.FileName+".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); StreamWriter sr = new StreamWriter(f); sr.Write(richTextBox1.Text); sr.Close(); f.Close(); richTextBox1.Clear(); } private void button2_Click(object sender, EventArgs e) { string s = "text file|*.txt";//filter varible OpenFileDialog op = new OpenFileDialog(); op.Filter = s;//providing filter op.ShowDialog(); StreamReader sr = new StreamReader(new FileStream(op.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); richTextBox1.Text= sr.ReadLine(); sr.Close(); } } }


how to store and retrive picturs from database(sql2005) in a c#-windows application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; // to work with sqlserver we have to use this
using System.IO; //to work with files we have to use this


namespace WindowsApplication2
{
public partial class Form1 : Form
{
//
Image img;
string curfilename;
string cs = "Data Source=.;Initial Catalog=stud;Integrated Security=True;Pooling=False"; //creating an connection string to connect to database

public Form1()
{
InitializeComponent();
}

private void image_retrival (object sender, EventArgs e) //retriving image from a database
{
if (textBox1.Text != "")
{
string s = "select photo from picture_demo where name='" + textBox1.Text + "' "; //qurry to retrive picture from database by a condiction
SqlConnection c = new SqlConnection(cs); //creating an object of the sqlconnection class
try
{
c.Open(); // sqlconnection is opened
FileStream f;
BinaryWriter b;
int bufsize = 100;
byte[] obyte = new byte[bufsize]; // creating an byte array inorder to retrive and store image
long rtv;
long stindx = 0;
string sdi = textBox1.Text;
SqlCommand cmd = new SqlCommand(s, c); //creating an object to sqlcommand
SqlDataReader sdr = cmd.ExecuteReader(); // creating an object to sqldatareader
while (sdr.Read()) // loop for reading data in the database

{
f = new FileStream(sdi, FileMode.OpenOrCreate, FileAccess.Write);
b = new BinaryWriter(f);
stindx = 0;
rtv = sdr.GetBytes(0, stindx, obyte, 0, bufsize); //this method is importent to retrive image from deatabas
while (rtv == bufsize)
{
b.Write(obyte);
b.Flush();
stindx += bufsize;
rtv = sdr.GetBytes(0, stindx, obyte, 0, bufsize);

}
b.Flush();
b.Close();
f.Close();
// b.Write(obyte, 0, (int)rtv - 1);
// b.Flush();
// b.Close();
// f.Close();
}
//c.Close();
img = Image.FromFile(sdi);
pictureBox1.Image = img;

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
c.Close();
}

}

}

private void browse(object sender, EventArgs e) //this section is used to select an image from our computer
{


if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
curfilename = openFileDialog1.FileName;

pictureBox1.ImageLocation = curfilename;
}

}

private void submit(object sender, EventArgs e) // method is used to save an image to a database
{

if (openFileDialog1.FileName != "")
{
FileStream f = new FileStream(curfilename, FileMode.OpenOrCreate, FileAccess.Read);
byte[] rawdata = new byte[f.Length];
f.Read(rawdata, 0, Convert.ToInt32(f.Length));
f.Close();

SqlConnection c = new SqlConnection(cs);
try
{
c.Open();

SqlCommand cmd = new SqlCommand("insert into picture_demo values('" + textBox1.Text + "'," + " @pic)", c);
cmd.Parameters.Add("@pic", SqlDbType.Image).Value = rawdata;
SqlDataReader sdr = cmd.ExecuteReader();
MessageBox.Show("record entered");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
c.Close();
}

}
}

how to send an simple mail in c# windows application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail; // add this inorder to send mail

namespace email
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
MailMessage m = new MailMessage();
m.From = new MailAddress("mail id");
m.To.Add(textBox1.Text);
m.Body = "hhhhhhhhhadjfsjdfoijfosdijfoisdjfoisdhfisdhfsiodhfoishd";
m.Subject = textBox2.Text;
SmtpClient sc = new SmtpClient("smtp.gmail.com", 587);
sc.EnableSsl = true;
sc.Credentials = new System.Net.NetworkCredential("your mailid", "password");

try
{
sc.Send(m);
MessageBox.Show("message has sended");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// finally
//{

//}


}
}
}