Friday, June 26, 2009

Convert date to different date string using Convert function of ms sql server 2005

Many times we need to convert datetime to different strings representing date, varying from 2009/06/2009 to June 26, 2009, and so on. Microsoft sql server 2005 can do the job for us! I had the same need some time ago, and sql server did this for me. (By the way, don't we programmers often find it irritating to have datetime representations different in different data base providers and different programming languages? Yes. Exactly here is what I am pointing towards what sql server 2005 can do for us. Follow the rest of this article for the magic!)

This is the syntax:

CONVERT (data-type, date-time-string-input, date-display-style)

Parameters:
data-type: Any data type from nchar, nvarchar, char, varchar, binary, varbinary [length is optional, e.g. varchar(20) or varchar(22)
date-time-string-input: Date time string supplied as input (You can use GETDATE() function etc.)
date-display-style: The string style (You need '2009.06.26' or 'June 26, 2009' etc. You can even use the useful style number. Read on.)

Note: If you provide insufficient length, you may be trimming your result!

Now, here is a list of the sql query and the result to the query that will introduce a number of the ways to get desired date strings.

SELECT CONVERT(VARCHAR(20),GETDATE(),100) 
Result: Jun 26 2009 5:53PM

SELECT CONVERT(VARCHAR(20),GETDATE(),101)
Result: 06/26/2009

SELECT CONVERT(VARCHAR(20),GETDATE(),102)
Result: 2009.06.26

SELECT CONVERT(VARCHAR(20),GETDATE(),103)
Result: 26/06/2009

SELECT CONVERT(VARCHAR(20),GETDATE(),104)
Result: 26.06.2009

SELECT CONVERT(VARCHAR(20),GETDATE(),105)
Result: 26-06-2009

SELECT CONVERT(VARCHAR(20),GETDATE(),106)
Result: 26 Jun 2009

SELECT CONVERT(VARCHAR(20),GETDATE(),107)
Result: Jun 26, 2009

SELECT CONVERT(VARCHAR(20),GETDATE(),108)
Result: 17:49:42

SELECT CONVERT(VARCHAR(20),GETDATE(),109)
Result: Jun 26 2009 5:50:02

SELECT CONVERT(VARCHAR(20),GETDATE(),110)
Result: 06-26-2009

SELECT CONVERT(VARCHAR(20),GETDATE(),111)
Result: 2009/06/26

SELECT CONVERT(VARCHAR(20),GETDATE(),113)
Result: 26 Jun 2009 17:51:24

SELECT CONVERT(VARCHAR(20),GETDATE(),114)
Result: 17:51:44:397

SELECT CONVERT(VARCHAR(20),GETDATE(),120)
Result: 2009-06-26 18:00:17

SELECT CONVERT(VARCHAR(20),GETDATE(),121)
Result: 2009-06-26 18:01:14

SELECT CONVERT(VARCHAR(20),GETDATE(),126)
Result: 2009-06-26T18:02:00

As you can see, I have used the select statement to retrieve the desired sql query result. You can use it with any combination of sql query to perform any of the CRUD (Create, Read, Update and Delete) operations.

You can comment to add to the above list. It may be incomplete. Remember your participation is very important to make it more complete and more useful. You are as always heartily welcome to post you suggestions, comments, rate this article or spread the words by adding it to the social bookmarks! Happy Programming!


Shout it pimp it

Wednesday, June 10, 2009

Highlight gridview row on mouse over in asp net web page: Adding effects to the gridview control

Programmers heavily use the asp.net gridview control. Adding some effects to the gridview will change the appearance so that user interactivity increases. One of such effects is highlighting the gridview row on mouseover. With this short background let's go for the design markup of the example gridview.

<asp:GridView ID="gridTest" runat="server" OnRowDataBound="gridTest_RowDataBound" AutoGenerateColumns="false">

<Columns>

<asp:BoundField HeaderText="Status" DataField="Status" />

<asp:BoundField HeaderText="Name" DataField="Name" />

<asp:BoundField HeaderText="Comment" DataField="Comment" />

<asp:BoundField HeaderText="Date" DataField="Date" />

</Columns>

</asp:GridView>

Now we have the asp.net gridview, why not choose the highlighted row's color? Let's define a style sheet class for highlighted row.

<style type="text/css">

/*for gridview row hover, select etc*/

.normalrow

{

background-color:white;

}

.highlightrow

{

background-color:#cccccc;

}

</style>

(The gridview markup shown above is only for example purpose. So you will not see any matches between the figure showing highlighted row and the example markup. Further you will also need to implement your own css styling, if you prefer any). Note the OnRowDataBound event handler in the gridview design markup. We will write some lines of code in this event handler to add the effect of highlighting gridview rows on mouse over. Here goes the code.

//row created event
protected void gridTest_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='highlightrow'");
e.Row.Attributes.Add("onmouseout", "this.className='normalrow'");
}
}

We have specified the css class to adapt by the gridview row on mouse over. At the same time, we need to assign another css class on mouse out so that the gridview will be highlighted only on mouseover and on mouse out the effect will be void. Happy programming!

kick it on DotNetKicks.com pimp it Shout it

Tuesday, June 9, 2009

22 Visual Studio Short Keys and 6 Short-cut Ways to Custom Jobs: A List of Tips and Tricks

Efficient programmers use short keys in IDE like Visual Studio. This saves time and in many cases makes the work run faster also. I also love short keys. They are smart! And there also go some tricks that help make your visual studio days a party! I have listed here some short cuts and some tips with the hope that this will be helpful to you all.

Visual Studio Short-cuts

  1. Ctrl+F5 to run the website without debugging. F5 only will run the website in debugging mode.
  2. Stop Debugging: Shift+F5
  3. Restart Debugging: Ctrl+Shift+F5
  4. Break All: Ctrl+Alt+Break
  5. F11 to debug line by line downwards from the toggle point. This works with F10 also. In fact you can see F10 assigned for this task. See Debug menu in the visual studio.
  6. F9 to toggle a break point.
  7. To delete all the break points at once: Ctrl+Shift+F9. If you only wish to disable the break points you can go down the Debug menu.
  8. Ctrl+S to save the current document. Ctrl+Shift+S to save all the documents at once.
  9. Print a document directly from the visual studio? Press Ctrl+P. This will bring the print dialog.
  10. Ctrl+F to find a text. A find dialog will be displayed. Then you are left with a number of options.
  11. Ctrl+H or Ctrl+Shift+H for find and replace.
  12. Ctrl+G to go to the specific line number in the current document.
  13. Open the web browser right from within the visual studio? Press Ctrl+Alt+R.
  14. Irritated switching back and forth the design view and code behind page of a file? Use F7 to navigate back and forth the files of a page.
  15. Press F4 to view the properties window for a control from the design page.
  16. To view the server explorer: Ctrl+Alt+S
  17. To view the solution explorer: Ctrl+Alt+L
  18. To view the output window: Ctrl+Alt+O
  19. To view the toolbox: Ctrl+Alt+X
  20. Press Shift+Alt+Enter to view/undo full screen.
  21. Press Ctrl+O to open a document from the project folder.
  22. Ctrl+F11 to view disassembly: the machine level code!

Visual Studio Tips

  1. To view the start page, navigate View->Other Windows->Start Page
  2. To initiate the start page to display feed from a website, Tools->Options->Startup. Choose show start page at start from the combo fox. Input the start page news channel rss feed. Click Ok.
  3. To display line numbers in the documents, Tools->Options->Text Editor. Now click the editor you need to display number in. Check Line Numbers at the right side of the window.
  4. Initiate the home page for the web browser [opened by pressing Ctrl+Alt+R]? Follow Tools->Options->Environment->Web Brower. Set the home page and optionally the search page from the right side of the window.
  5. Know the class name or method name but confused the right namespace? Right click the class name or method name and click Resolve; you will see the reference you need to add. Click the reference. It will be added for the page.
  6. Using find window and clicking Find button each time to go to next match? Leave the trend. Just press F3 to go to next match!!

Shortcuts are the small but useful ladders of programming. You can use them to go up and down, left and right or south and north. I would like to heartily welcome to share your tips and tricks that you have learned from your dedicated play around with the visual studio. All the tips and shortcuts I have listed above are tested and learned from visual studio 2005. They may or may not work in visual studio 2008 and later versions. You can specify the compatibility of your trick that you are posting as comment in this article. Thank you very much. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Monday, June 8, 2009

How to read email address, host, port number from smtp settings section of web.config file in asp.net

How can I read the email address, smtp host, port number from my mail settings section of the web.config file in an asp.net web application? Yeah, we can specify an email address in the mail settings section of web.config file and read it from asp.net web page in the time of sending an email. We can also read the smtp host and port number which is necessary while sending email from an asp.net web page. I have already discussed: How to send email from asp.net web page. So here I would just put the coding to read email address, host, port number from mail settings section of web.config file in asp.net web application.

Let's look into the mail setting portion of a web.config file.

<system.net>

<mailSettings>

<smtp from=support@test.com>

<network host="mymailhostaddress" port="25"/>

</smtp>

</mailSettings>

</system.net>

While sending an email, we need from, to email addresses and an smtp client also. So the code snippet below puts them together.

using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

//the method to send email
public void SendMail()
{
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
SmtpSection smtpSection = mailSettings.Smtp;
//read the from email of the web.config file
string fromEmail = smtpSection.From;
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;

//..other code follows from here
//that sends the email

//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress(fromEmail), new MailAddress("anup@best.com"));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient(host, port);
try
{
client.Send(message);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
}
catch (Exception ex)
{
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;
}
}

Using the code above, we easily accessed the important information from mail settings section of the web.config file. Please note again that I have just put the coding of reading information form web.config file. You can learn from here to Send Email in asp.net web page so that you can combine what this article provides with sending email in asp.net web application. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Tuesday, June 2, 2009

How to extract data out of your datacontrol (asp.net formview, detailsview or gridview) using FindControl or ExtractValuesFromCell method?

Most of the times asp.net programmers need to extract data out of the asp.net datacontrols like formview, detailsview or gridview. Mostly we use FindControl method of the data control for this purpose. And another method ExtractValuesFromCell is also entertained to achieve the goal. It would be very interesting to throw a little light upon both of them.

Naturally I am familiar with the FindControl method of the datacontrols. For example, to find a dropdownlist in the formview or detailsview control, I would call:

DropDownList ddlTest=FormView1.FindControl("DropDownList1") as DropDownList;

Similarly, we could search for an asp.net control in a particular row of a gridview control. For example:

GridViewRow row=GridView1.Rows[5]; // here we are dealing with the fifth row
TextBox textName=row.Cells[2].FindControl("textboxName") as TextBox; //here, there is a textbox with id textboxName in the second cell of the row
if(textName!=null) //check if such textbox was found in the specified cell or the specified row
{
string name=textName.Text;
}

Practically we need to get a control from the data control in special events of the control like inserting, inserted, updating, updated, deleting, deleted, selectedindexchanging, selectedindexchanged etc. Combining the FindControl method with such event handlers help customize data during data operations (add,edit,delete) and provides flexibility to display data from database or other data sources (xml, csv, programmatically created datatables etc).

Before discussing ExtractValuesFromCell, I would like to drop one note. Please note that some standard controls in some data controls may be available for extracting only in the particular mode of the data controls. Confusing? Don't worry. This simple example will clarify it. Say, we do have a textbox in the edititemtemplate of a detailsview. To reference this textbox and extract value from it, we can use the findcontrol method only if we are in edit mode. In other modes we will get null reference (and possibly null reference exception may be thrown when we try to extract text or other properties). That is why I have checked for the null in the code above before reading text value from the textbox.

Now let's focus on ExtractValuesFromCell. There goes a popular article on Extracting data out of your datacontrol which discusses ExtractValuesFromCell method to get data from the controls in datacontrols like gridview, formview or detailsview. (The title of this article is inspired from it! And I have tried to make it as useful as I can). Please refer to the heavily discussed article to understand what the author davidfoul has discovered and what are the benefits of using ExtractValuesFromCell method to extract data out of a datacontrol.

After you have been through the article, you sure would like to ask which method to use- FindControl or this ExtractValuesFromCell? This is what I commented to the author:

Hi dear author,

I came here following the discussion on the asp.net forum: forums.asp.net/.../1362718.aspx

I have always been using FindControl() method: much easier and handy. You need not to write (and call everytime) the functions to extract values (or cells) using ExtractValuesFromCell.

This ExtractValuesFromCell way of extracting values from cell is just another way around it. So what's wrong to go with FindControl. Please give your opinion (perhaps you could update the post to add a sections: Why to not use FindControl(); I am requesting this because the argument among developers would go longer!).

Hey, this could be the advantage: People sometimes ask how to get all the values from my gridview since I have been editing and updating it, so changing the original value from the datasource. In such case this trick could help a lot.

Thanks.

And our generous author davidfoul has replied his kind views:

@sangam100 I had this same question about FindControl on the forum. Here is what I said:

It's not the use of FindControl that makes my spine tingle its the MISuse and ABuse of it that does. FindControl is a good method and very useful, but look at the name of method, FindControl. Everything has a purpose right? If I'm trying to find a control then i'll call find control. If I'm trying to get data out of a control I might call find control or some other API that is better at getting data, i.e ExtractRowValues. I think that there is alot of knowledge out there, good and bad, about using these data controls and I just want to try to set some things straight by shedding some more light on how stuff works (I love that website).

Before I go lemme show you what I mean by picking the right API.  Lets make a new control IntControl. IntControl has a method int GetValue(). Now OO principals tell us to not break the abstraction by letting consumers grab at the internals but IntControl derives from control, and by default, there is alot of other things exposed to the consumer that shouldn't be. Now we know that IntControl uses a textbox internally so I could never call GetValue and instead write:

int value;

Int32.TryParse(((TextBox)IntControl.Controls[0]).Text, out value);

Everything will work fine until the author of IntControl decides to use a div instead of a textbox.

The REAL lesson to take away from the blog post is to try your best to follow the contract provided by a class or an interface (in this case the DataControl).

You can read comments, views, suggestions of so many enthusiastic asp.net web developers both in the original site by the author and a post in the forums.asp.net/.../1362718.aspx. Please comment in the respective sites to put your opinions to the articles. However you can comment as always on this article regarding my perspectives. Thank you. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Monday, June 1, 2009

How to send email from asp.net? Basic C# code to send simple email

Sending email in asp.net is very useful and customizable too. The powerful classes help you compose and send email in minute! The glamour has always fascinated me, but more important is the frequent questions that are asked in asp.net related forums on sending email in asp.net using C# or vb.net. We can send email using some smtp server. And if this is not viable (sometimes we don't have smtp accounts!) we can use our own gmail account to send email (Thank you gmail!)

Take one example- Here goes the question that was asked in asp.net forum-

"can someone give me code how to send an e-mail from c# code
I am working with a company using Microsoft outlook for my mails.
I want to send mail only to 1 person, also please help me in identifying "smtp hostname"
"

Here goes the simple and helpful answer.

Visiting all above listed links you must have realized that sending email in asp.net is quite fun and useful too. In fact, a lot of customizations exist depending on your requirement. My suggestion is to do the basic email sending first. After that you can play with the classes and objects to perform more actions. Let me show you the basic email sending using c#.

//sending basic mail in asp.net 
public void SendBasicMail()
{
//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress("sangam@test.com"), new MailAddress("anup@best.com"));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient("mail.mysmtpserver.com", 25);
try
{
client.Send(message);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
}
catch (Exception ex)
{
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;
}
}

This simple example will help you understand the basics of sending email in asp.net web application.

Now interested in sending email using our own gmail account? Here goes the coding by getchinna_sv (Thank you getchinna_sv! Yours sangam100).

 protected void sendMail()
{
string from = "me@gmail.com"; //Replace this with your own correct Gmail Address
string to = "you@gmail.com"; //Replace this with the Email Address to whom you want to send the mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, "One Ghost", System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "Password");
client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
HttpContext.Current.Response.Write(errorMessage);
} // end try
}

client.Credentials = new System.Net.NetworkCredential(from, "Password"); in this statement... write your gmail password.... from address should be a gmail address....

Hope this post will help. Thank you. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Dropdownlist selected item validation fails: the suggestion

Today I got across a question in the asp.net forum which seems simple but is still confusing for many beginners. So I am giving a place for it here:

Question:

Hi Everyone,

I'm trying to set some error handling by returning a message when a button is clicked and the user has not selected an item from the dropdown menu. I'm using this but for some reason it is being ignored?

protected void validatebtn_Click(object sender, ImageClickEventArgs e)
{
if (!(DropDownList1.SelectedValue == "Select Item"))
{
lblerrors.Text = "
You have not selected an item from the drop down list.";
}
else
{
//...continue with the code.
}
}

When I debug the code, it reads the first line:

if (!(DropDownList1.SelectedValue == "Select Item"))
and then skips to the else statement and misses my message?

Can anyone advise why this is happening?

Thanks.
Chloe ~X~

Among other suggestions, here is what I have suggested:

Answer:

Looking into your explanation and reading all the answers given by members, some questions came in my mind.

1. Did you check what value is exactly selected from the dropdownlist? I mean DropDownList1.SelectedValue should be "Select Item" only then your comparision will be true.
2. Are you adding this "Select Item" from design view or is it added programmatically from code behind? Did you only specify "text" or both text and value? See the markup below:

<asp:DropDownList ID="ddlTest" runat="server">
<asp:ListItem Text="Select Item" Value="Select Item" Selected="True"></asp:ListItem>
</asp:DropDownList>

If you don't put Selected="true", this item may display at the first position, but is not selected yet. So don't forget to set this. Another thing to notice is you should have set both Text and Value. The "SelectedValue" corresponds to the "Value" in the markup. Only then your code will work. Don't forget to have both text and value if you add listitem to the dropdownlist from codebehind, like this one:

ListItem item = new ListItem("Select Item", "Select Item");
DropDownList1.Items.Add(item);

Hope this helps. Please feel free to ask if the problem persists or if further help is required. Thanks.

kick it on DotNetKicks.com Shout it pimp it

Popular Posts

Recent Articles