Wednesday, September 22, 2010

Basic hashing example

protected void btnhash_Click(object sender, EventArgs e)
{
string salt = CreateSalt(txtpassword.Text.Length);
string pass = CreatePasswordHash(txtpassword.Text.Trim(), salt);
Label1.Text=pass;
}

public string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}

public string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
return hashedPwd;
}

Password encryption and decription in asp.net

protected void btnsignup_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["cnn"].ToString());
con.Open();
string pass = passencrypt(txtpassword.Text.Trim());
SqlCommand cmd = new SqlCommand("insert into userdetails values('" + txtusername.Text.Trim() + "','" + pass + "')", con);
cmd.ExecuteNonQuery();
txtusername.Text = ""; txtpassword.Text = "";
}
protected void btnrecoverpassword_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["cnn"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select password from userdetails where username=" + session["uname"].Tostring(), con);
string pass =(string) cmd.ExecuteScalar();
pass = passdecrypt(pass);
}

private string passencrypt(string sData)
{
byte[] encData_byte = new byte[sData.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
public string passdecrypt(string sData)
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(sData);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}

Tuesday, September 21, 2010

Basic example of Stored procedure

Hai,

In Asp.net page

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["cnn"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("storedetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@name", txtname.Text.Trim());
cmd.Parameters.AddWithValue("@class", txtclass.Text.Trim());
cmd.Parameters.AddWithValue("@mark", txtmark.Text.Trim());
cmd.ExecuteNonQuery();

Query to create stored procedure

CREATE PROCEDURE storedetails
@name varchar(30) = NULL,
@class varchar(5) = NULL,
@mark int = NULL
AS
BEGIN
SET NOCOUNT ON;
insert into student values(@name,@class,@mark)
insert into result values(@name,@class)
return
OnError: --If error exit gracefully
Return
END

Friday, April 23, 2010

send mail from ASP.Net

Hai,

Check the below program to send mail message from asp.net, on problem is that, it may reach in spam!!

Imports System.Web
Imports System.Web.Mail
Imports System.Net
Imports System.Net.Mail

Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim status As Integer = sendMail("toaddress", "password", "XXXXX"
End Sub

Public Function sendMail(ByVal toadd As String, ByVal pass As String, ByVal nm As String) As Integer
Try
Dim smtpClient As New SmtpClient
smtpClient.Host = "localhost"
smtpClient.Port = 25
Dim msg As New Net.Mail.MailMessage
msg.From = New MailAddress("xxxxxxx@gmail.com")
msg.To.Add(toadd)
'Can add more toaddress, Cc and Bcc also
msg.Subject = "Haii"
msg.IsBodyHtml = True
msg.Body = "Hai " + nm + ",Your Login id is this mail address and Your pass word is :" + pass + "login now by CLICKHERE "
smtpClient.Send(msg)
Return (1)
Catch ex As Exception
Return (0)
End Try
End Function

Note: Another referance for the people who have a configured smtpmailserver. Visit this link: http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx

Thursday, March 11, 2010

upload image in silverlight

Hai,
Webservice
using System.IO;
using System.Configuration;
using System.Data;
[WebMethod]
public bool Upload(PictureFile picture)
{
FileStream fileStream = null;
BinaryWriter writer = null;
string filePath;

try
{
filePath = HttpContext.Current.Server.MapPath(".") +
ConfigurationManager.AppSettings["PictureUploadDirectory"] +
picture.PictureName;
int i = 0;
while (System.IO.File.Exists(filePath))
{
string ext = System.IO.Path.GetExtension(filePath);
filePath = HttpContext.Current.Server.MapPath(".") +
ConfigurationManager.AppSettings["PictureUploadDirectory"] +
System.IO.Path.GetFileNameWithoutExtension(filePath) + i + ext;
i++;
}

if (picture.PictureName != string.Empty)
{
fileStream = File.Open(filePath, FileMode.Create);
writer = new BinaryWriter(fileStream);
writer.Write(picture.PictureStream);
}

return true;
}
catch (Exception)
{
return false;
}
finally
{
if (fileStream != null)
fileStream.Close();
if (writer != null)
writer.Close();
}
}
public class PictureFile
{
public string PictureName { get; set; }
public byte[] PictureStream { get; set; }
}
Coding

using SilverlightApplicationgeetingcards.ServiceReference1;
private void btneffects_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "JPEG files|*.jpg";
if (openFileDialog.ShowDialog() == true)
{
Stream stream = (Stream)openFileDialog.File.OpenRead();//img11.Clip.GetValue(Image.ClipProperty);
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
string fileName = openFileDialog.File.Name;//img11.Clip.GetValue(Image.SourceProperty).ToString();

PictureFile pictureFile = new PictureFile();
pictureFile.PictureName = fileName;
pictureFile.PictureStream = bytes;

services.UploadCompleted += new System.EventHandler(uploadpicturecompleted);
services.UploadAsync(pictureFile);
}
public void uploadpicturecompleted(object sender, UploadCompletedEventArgs e)
{
if (e.Error == null)
{
if (e.Result)
{ txtcomments.Text = "Upload succeeded (.'.)"; }
else
{ txtcomments.Text = "Upload failed ('.')"; }
}
}

Tuesday, March 9, 2010

How to host a silverlight website

Hai,
To host a silverlight website or a website which includes the silverlight application. Note that the hosting is in your server and trying to configure in 'Windows server2003'.
1>
Right click website on your iis- properties- Home directory - Configure
O\on 'Mappings' tab - ''ADD"
Two new extensions- '.aspx' and '.wgx' extensions and its executables.
The executable are same for both .aspx and wgx that is "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
Check 'Script engine' and uncheck 'verify that file exists'.

2>
Right click server name - Properties - 'MIMEtypes' - 'New'
and add three new extensions and MIME type.
extension MIMEType
.xap application/x-silverlight-2
.xaml application/xaml+xml
.xbap application/x-ms-xbap

These are the special settings to host silverlight website, all othrs are same to host
a normal website hosyting.

Sunday, February 14, 2010

Convert image to icon in asp.net

string filename, newfilename;
filename= "E:/..../images/window.jpg"; // your image location
newfilename= Path.ChangeExtension(filename, ".ico");
using(Bitmap bitmap = Image.FromFile(filename, true) as Bitmap)
{
using (Icon icon = Icon.FromHandle(bitmap.GetHicon()))
{
using (Stream iconfile = File.Create(newfilename))
{
icon.Save(iconfile);
Response.Write("Converted - " + newfilename);
}
}
}

Note: Get an icon file n the same folder of image with extension'.ico', it may not work properly,
if the file size morethan 120X120. Try to choose small images.