Tuesday, March 24, 2009

Sending a mail through SMTP

SMTP(Simple Mail Trafer Protocol) is an application layer protocol. It is a internet's standard host-to-host mail transport protocol and traditionally operates over TCP,port 25.It uses TCP as a transport protocol, and in turn uses IP for routing.

Now lets us look at the code for sending a mail to a user who have just registered-

Code in aspx.cs-
string fromAddress = ConfigurationManager.AppSettings["FromAddress"];
string data = "Your UserName=" + txtEMail.Text + "
" + "Your Password= " + txtPassword.Text + "
" +
"Using the following link please validate your registration" + "
" +
"Request.Url.Scheme"+"://"+"Request.Url.Host"+"/Validate.aspx?userName=" + txtEMail.Text + "&userId=" + primaryContact.UserId;

MailMessage mailer = new MailMessage(fromAddress, txtEMail.Text);
mailer.Body = data;
mailer.Subject = WebUtil.GetTranslatedString("EMAIL_SUBJECT");
mailer.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Send(mailer);

Tag to be added in web.config-


system.net
mailSettings
smtp deliveryMethod="Network" from=the mail id of the site
network host="hostname" defaultCredentials="true"/
/smtp
/mailSettings
/system.net
(Please add the pre and post the symbols '<' and '>')

By this code the user will recieve a mail through the site in which they got registered.The mail will appear in the below manner

The mail content-

Your UserName="EmailId of the user" Your Password= "password of the user"

Using the following link please validate your registration :

http//HostName/Website/Default.aspx?username=username&userId=some uniqueidentifier

Note:The total path of the page u want to display for the user once the user logs in,is the link above given to the user in his/her mail.

  • The above link is given to the user to validate his registration.Once the user clicks the link he will be a valid user and will be redirected to the validate page of the website .In that page the user can be given a button for redirecting to the default first page of the site.After this the user can loggin with his credentials using login page of the site.
  • If the user will not click that link provided in his mail he cannot loggin in the website with his account.
  • In this way we can code the mail sending technique usind the SMTP protocol.

Monday, February 23, 2009

How To Check User Logged In

To check whether the user has logged in or not a simple 2 lines to be checked in our application


using System.Security.Principal //namespace to be used

IPrincipal principal = HttpContext.Current.User; //gives the current user logged in
return principal.Identity.IsAuthenticated; //isauthenticated gives return true or false

so if user has logged in then it returns true and vice versa , the userid of the logged in user can be retrieved in the below manner


userId = new Guid(Membership.GetUser(Page.User.Identity.Name).ProviderUserKey.ToString());



Thursday, February 12, 2009

Easy Way Of Maintaing The Users and Membership

The easy way of creating new users and settings roles to the existing users is that we can see one icon in the solution explorer named "ASP.NET Configuration"

By clicking this icon we get a new window opened in which we have three links present name
1)Security , 2)Application Configuration , 3)Provider Configuration - with the existing data if any

Now in these threee links click security link for creating users,roles and maintaining users, for creating new roles click Create or Manage roles now we get one textbox and a button where we should type the role we want in our application like Admin,User etc.. your own role names you can write.
After creating roles go for creating users by clicking Create User we get another page in which we have to fill in the details asked and set the role for that user and click "Create User".Do Remember the password because while logging in the website it is important.
If you want to edit the deatils or change the role of any user then click the link name Manage User ,there we can edit any detail of that user.

After creating the roles and users and also assigning the roles to the particular users we can close that window and try logging in the website you have developed.

How to Set A Default Role While Registration Itself

  • This will be possible only if we have aspnet tables and stored procedures in our database.
  • We should have users,roles in our application.
  • Now in our visual studio we will have a register page from which a new user will get registered in our website.
  • In this Register Page,register click we should include one line given below based on your requirement
  • Roles.AddUserInRole("String username","String rolename"); for single username adding ,if we want for a group of users then we can use the method named Roles.AddUsersInRole("String[] usersname","String rolename"); By this the total group given in the string array will be assigned the same role.
  • Here Roles is the aspnet class and AddUserInRole(),AddUsersInRoles() are methodes in that.
  • So with this line we can easily assign the role which we want the registring user to be assigned.

Monday, January 12, 2009

How to get the ASPNET Tables and ASPNET StoredProcedures Automatically In Our Database

  • Firstly why we need these aspnet tables and stored procedures??
  • Secondly where we get use of them??
  • We need these aspnet tables for authentication and authorization purpose.
  • These are automatically generated if we give a command.
  • Just we should use them in our login pages.
  • The command should be given in the Visual Studio 2005/2008(whatever version is intalled in your system) command prompt.

Follow the steps for execution:

  • Goto Start menu and in that goto All Programs, we get a list of softwares installed in the PC.
  • Now in that see the Microsoft VisualStudio 2005/2008 and in that you can see the Visual Studio Tools.
  • Again in that VS Tools you can see the Visual Studio Command Promt.
  • Click on that,now we get the comand prompt window in which type aspnet_regsql.exe and press Enter key.
  • Now we get a Window (ASPNET SQL Server Setup Wizard) in this keep clicking the Next button for 2 times and then in that window we get we should type the system name we are working on and the authentication details of the database in which you want the aspnet tables to be installed and finally click Finish button.

Now you can see the aspnet tables and stored procedures installed in your database.(press refresh if u cannot see them)

Note: If System Admin has access then no need to specify the authentication details.

Thursday, January 1, 2009

Images Adding Diplaying and Deleting

We can use a listview or a datalist for showing the images for one particular coin for example.(I have many images for a coin in my website.)

I have used Listview in the website i am developing so lets see the code

In .aspx page

asp:ListView ID="lstvwCoin" runat="server" ItemPlaceholderID="itemPlaceholder" GroupItemCount="2" OnItemDeleting="lstvwCoin_ItemDeleting" DataKeyNames="PictureId"
LayoutTemplate
table id="Table1" runat="server" width="100%"
tr id="Tr1" runat="server"
td
Coin Images
/td
/tr
tr runat="server" id="itemPlaceholder" /
tr id="Tr2" runat="server"
td id="Td2" runat="server"
table id="groupPlaceholderContainer" runat="server" border="0" cellspacing="0" cellpadding="0" width="100%"
tr id="groupPlaceholder" runat="server"
/tr
/table
/td
/tr
/table
/LayoutTemplate
GroupTemplate
tr id="itemPlaceholderContainer" runat="server"
td id="itemPlaceholder" runat="server"
/td
/tr
/GroupTemplate
EmptyDataTemplate
center
No Images are inserted for this coin !
/center
/EmptyDataTemplate
ItemTemplate
tr
td
asp:Image ID="coinimg" runat="server" ImageUrl='%#"~/CoinImages/Thumbnail/"+ Eval("PictureId") +".jpg" %' /
asp:Label ID="lblPicId" runat="server" Text='<%#Eval("PictureId")%>' Visible="false" /asp:Label
/td
/tr
tr
td
asp:LinkButton ID="lnkbtnDelete" runat="server" CausesValidation="false" CommandName="Delete"
Text='<%# WebUtil.GetTranslatedString("lnk_ListM_Delete")%>' /


/td
/tr
/ItemTemplate
/asp:ListView


-Here for listview we have ItemDeleting property which is useful for deleting the images by delete link.
-We have 4 templates in the code pasted ItemTemplate,LayoutTemplate,GroupTemplate & EmptyDataTemplate.
-Layout template is used for the displaying the headings of each column (just like headertemplate in datalist).
-EmptyData Template is used for displaying a message if no data available for the criteria we are searching for.
-Item Template is used here for the items to be displayed according to the layout template headings.
-Group Template is used displaying the images in an album format.

Note: Please add lessthan and greater than for each line pasted coz they are not getting displayed once i put them so i have removed them.

In .aspx.cs Page

private void bindimageview(int coinid)
{
CoinDao coinDao = new CoinDao();
lstvwCoin.DataSource = coinDao.GetImages(coinid);
lstvwCoin.DataBind();
}



The Method above is for assigning the datasource to the list view and binding the data.

protected void btnAddImg_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(lblCoinId.Text))
{
Guid picId = Guid.NewGuid();
CoinDao coinDao = new CoinDao();
Coins coin = new Coins();
coin.CoinId = int.Parse(lblCoinId.Text);
coin.Country.CountryId = int.Parse(lblCountryId.Text);
coin.CoinName = txtCoinName.Text;
coin.Country.CountryName = txtCName.Text;
coin.PictureId = picId;


Bitmap originalBitmap = new Bitmap(FileUpload1.PostedFile.InputStream);
int orgHieght = originalBitmap.Height;
int orgWidth = originalBitmap.Width;
Bitmap thubmBitmap = (Bitmap)originalBitmap.Clone();
Bitmap passportBitmap = (Bitmap)originalBitmap.Clone();


string PicfilePath = Server.MapPath("~/CoinImages/Thumbnail/" + picId + ".jpg");
thubmBitmap = BitmapManipulator.ThumbnailBitmap(thubmBitmap, 75, 75);
thubmBitmap = BitmapManipulator.ConvertBitmapToJpeg(thubmBitmap, 100);
thubmBitmap.Save(PicfilePath, ImageFormat.Jpeg);

coinDao.AddImage(coin);
bindimageview(Convert.ToInt32( lblCoinId.Text));
//Response.Redirect("~/ListOfCoins.aspx");

}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/ListOfCoins.aspx");
}

protected void lstvwCoin_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{

string pictureId = ((System.Web.UI.WebControls.ListView)(sender)).DataKeys[0].Value.ToString();
CoinDao coindao=new CoinDao();


if (!string.IsNullOrEmpty(pictureId))
{
coindao.DeleteImage(pictureId);
}


//string imageFolder = Server.MapPath("~/Images/Albums/") + albumName + "/";

//if (Directory.Exists(imageFolder))
//{
// Directory.Delete(imageFolder, true);
//}
bindimageview(Convert.ToInt32(lblCoinId.Text));
}
}

We have 3 methods pasted here, one for Add image click for adding the images in the file path given and also to the database.Here PictureId is uniqueidentifier in the Database and Guid in the VisualStudio and Cancel_click for redirecting to the page we started and the other method Item_Deleting for deleting the image from the Database.

Friday, November 21, 2008

ADO.NET Notes

ADO.Net (Active Data Objects)



We have 4 Managed Providers in ADO.Net(Managed Provider is nothing but a .Net dll file)



1)System.Data.SqlClient - Managed Provider for SqlServer

2)System.Data.OracleClient - Managed Provider for Oracle

3)System.Data.Oledb - Managed Provider - can be used for any database which has Oledb provider (for COM Based Components).It is Object Oriented.

4)System.Data.Odbc - Managed Provider for Odbc Drivers - This can be used for all databases i.e Generic, but it would be slow compared to a managed provider specific to a given database.(for Win32 based).No Object Orientation .Not recommended.



Important Objects In Managed Provider:



1)Connection- Connection object encapsulates the functioanality of establishing a communication path over the sockets.In .Net, Connections are 'Pooled' we can make by default 100 simultaneous connections max without closing but obviously we have to close every connection opened only then it can be reused 'Pooled' means keeps the connection for the short period of time.The connection Pooling can be customized by setting appropriate parameters in ConectionString of Connection Object.

2)Command- Command Object can be used for execution of any type of Sql Statement.
When "Select" or similar type of sql statement is executed a new cursor is created on the back end.This cursor contains primary key or indexed key of the table on which the statement is executed.There is also a pointer,which is by default positioned at BOF.The cursor and pointers functionality is encapsulated by the "DataReader" object created in the front end.Using this object,we can move the pointer in the forward direction getting one record from backend into the front-end at a time.The cursor managed by Data Reader is read-only and forward-only.