September 2008 - Posts

Understanding the architecture and code in software application plays as major factor while building good software products.

Along with specification, examples and tools, a new visual modeling technique being introduced, termed as “nAML” (.NET Application Modeling Language), which overcomes the limitation of typical modeling languages in a revolutionary way! Nothing much to say, just download (FREE) it and you can get to know how POWERFUL it is!

Here is the project site: http://code.msdn.microsoft.com/naml

The project is currently in Beta 1 phase. Your valuable input/feedback in this thread will greatly help to make it much better.
Here is a free e-book introduces this visual modeling technique:  http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=naml&DownloadId=3083

I have seen many posts over forums asking for how to send emails in asp.net.

In this blog post, I am going to post code snippet to send email in asp.net (with / without attachment).

MoreOver, for Complete FAQ for the System.Net.Mail namespace found in .NET 2.0 (Click here for System.Web.Mail). This is an excellent resource to understand total mail functionalities in asp.net.

Check out Below Code to send email in asp.net:

C#

using System.Net;
using System.Net.Mail;
-----------------------

public static bool SendMail(string strFrom, string strTo, string strSubject, string strMsg)
{
try
{
// Create the mail message
MailMessage objMailMsg = new MailMessage(strFrom, strTo);

objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = strSubject;
objMailMsg.Body = strMsg;
objMailMsg.Priority = MailPriority.High;
objMailMsg.IsBodyHtml = true;

//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objSMTPClient.Send(objMailMsg);
return true;
}
catch (Exception ex)
{
throw ex;
}
}

 
VB:

Public Shared Function SendMail(ByVal strFrom As String, ByVal strTo As String, ByVal strSubject As String, ByVal strMsg As String) As Boolean
Try

' Create the mail message
Dim objMailMsg As MailMessage = New MailMessage(strFrom, strTo)

objMailMsg.BodyEncoding = Encoding.UTF8
objMailMsg.Subject = strSubject
objMailMsg.Body = strMsg
objMailMsg.Priority = MailPriority.High
objMailMsg.IsBodyHtml = True

'prepare to send mail via SMTP transport
Dim objSMTPClient As SmtpClient = New SmtpClient()
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
objSMTPClient.Send(objMailMsg)
Return True
Catch
ex As Exception
Throw ex
End Try
End Function



Code to send mail with attechment.,

public static bool SendMail(string strFrom, string strTo, string strSubject, string strMsg)
{
try
{
// Create the mail message
MailMessage objMailMsg = new MailMessage(strFrom, strTo);

objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = strSubject;
objMailMsg.Body = strMsg;
Attachment at = new Attachment(Server.MapPath("~/Uploaded/txt.doc"));
objMailMsg.Attachments.Add(at);
objMailMsg.Priority = MailPriority.High;
objMailMsg.IsBodyHtml = true;

//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objSMTPClient.Send(objMailMsg);
return true;
}
catch (Exception ex)
{
throw ex;
}
}

Referecned Thread link: How to send an email with attachment in asp.net 2.0 - ASP.NET Forums

hope this helps.

There will be South Asia MVP Open Day 2008 at Goa, India near around mid of November! Goa is a marvalous city with its lively culture, sumptuous food, and of course the beaches! I am eagerly waiting for!!


I am expected to have Business and social networking with other fellow MVPs, interesting conversations and interactive technical sessions with Microsoft product groups and fellow MVPs.


Here is a Comic representation of South Asia Open Day 2008 :)

I needed to generate Medium (250 X 250) and small (150 X 150) size images from Large (500 X 500) size images as Product images to display in a shopping cart application.

To generate thumbnail images (for scenario I wrote above, or to display iconic Product images within GridView along with Product Details):

        System.Drawing.Image imThumbnailImage;
        System.Drawing.Image _InputImage = System.Drawing.Image.FromFile(Server.MapPath("large.jpg"));

        imThumbnailImage = _InputImage.GetThumbnailImage(100, 100,
                     new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
        imThumbnailImage.Save(Server.MapPath("thumb.jpg"));

        imThumbnailImage.Dispose();
        _InputImage.Dispose();


    public bool ThumbnailCallback() { return false; }

Image.GetThumbnailImage Method (System.Drawing) is used to generate thumbnails.
Parameters to pass in this method are:

thumbWidth (Int32):
    The width, in pixels, of the requested thumbnail image.
thumbHeight (Int32):
    The height, in pixels, of the requested thumbnail image.
callback (System.Drawing.Image.GetThumbnailImageAbort):
    A Image.GetThumbnailImageAbort delegate. In GDI+ version 1.0, the delegate is not used. Even so, you must create a delegate and pass a reference to that delegate in this parameter.
callbackData (System.IntPtr):
    Must be Zero.

I was having a requirement to Stream Audio files in one of my on-going ASP.NET application; While I googled, I found that to Stream Audio files in a webpage, we need to use <object> tag.
The <object> element can support many different media types, like:

  • Pictures
  • Sounds
  • Videos
  • Other Objects

We just need to add the Windows Media Player reference using <object> tag with class ID. Windows Media Player comes in many different versions. The class IDs are different for different versions, with a list of parameters you can set (most of them are boolean and self explanatory).

For Windows Media Player 6.4; which I am using, classID should be clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95. The class ID for Windows Media Player 7 and later is: clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6. Many places on the internet it states that the class ID should be: clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95. This class ID is the old one, but it will work, because of backward compability. However, if you use the old class ID you will not be able to use the new features added to the component.

Below is Sample Code for adding <object> tag in your HTML design code which is having reference to Windows Media Player 6.4 with classID as clsid: 22D6F312-B0F6-11D0-94AB-0080C74C7E95.

        <div>
            <object classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" id="MediaPlayer1">
                <param name="AudioStream" value="true">
                <param name="AutoSize" value="true">
                <param name="AutoStart" value="false">
                <param name="ClickToPlay" value="true">
                <param name="Enabled" value="true">
                <param name="Filename" value="BilloRani_Goal.mp3"> <%--The URL of the file name you want to play--%>
                <param name="AnimationAtStart" value="true">
                <param name="ShowDisplay" value="true">
                <param name="ShowAudioControls" value="true">
                <param name="ShowDisplay" value="true">
                <param name="ShowStatusBar" value="true">
                <param name="ShowGotoBar" value="true">               
            </object>           
        </div>

Here are the list of parameters you can use with Windows Media Player 6.4 reference, they are almost self explanatory: Windows Media Player Reference in ASP.NET

I needed to read my SMTP email settings defined under system.net section in my web.config file. In order to use eNewsLetter and other SiteAdmin CMS modules that sending email notifications; you can setup your web.config to defind SMTP services settings.

Below is one example of SMTP email setting defined in web.config file:
(Under <configuration> Section)

    <system.net>
        <mailSettings>
            <smtp deliveryMethod="Network" from="testuser@domail.com">
                <network defaultCredentials="true" host="localhost" port="25" userName="kaushal" password="testPassword"/>
            </smtp>
        </mailSettings>
    </system.net>

To Access, this SMTP Mail Setting Programatically, you need to import below namespaces:

using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

The .NET Framework provides APIs for accessing settings in a configuration file. Below is how you access the SMTP mail settings of a web.config file in code:

        Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
        MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
        Response.Write("host: " + settings.Smtp.Network.Host + "<br />");
        Response.Write("port: " + settings.Smtp.Network.Port + "<br />");
        Response.Write("Username: " + settings.Smtp.Network.UserName + "<br />");
        Response.Write("Password: " + settings.Smtp.Network.Password + "<br />");
        Response.Write("from: " + settings.Smtp.From + "<br />");

Thats it!

The Scenario may come where application needs data to be updated automatically. The Question comes; Is there a way by which we can auto refresh a page for specific time interval so as to update the Content(automatically).

The ultimate goal is; we want to refresh our page automatically at a defined time interval. First, if you are using AJAX in your website then you can use ASP.NET AJAX > The Timer Control to achieve this. But if you are not using AJAX; then also its not a big deal.

Check out below code which will Referesh the webpage after every 10 seconds:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //page will be refereshed at a interval of 10 sec
            Response.AddHeader("Refresh", "10");
        }
    }

Alternatively, you can also add meta tag under <title> tag, in your HTML Design code as:
    <meta http-equiv="refresh" content="10;url=http://www.google.co.in">

This will Refresh / Auto Postback the current page after 10 seconds. Optionally you can also define a url which means page will be redirected to that url after specified interval (This functionality comes handy while you want your website user to have Login > See the WelCome / Logged in Successfully Page > and redirect to his Account or Home Page Automatically). if you dont spacify the url, then current page will be refereshed after specified time interval.

Recently, I came across a post in the asp.net forums (This one > http://forums.asp.net/t/1313476.aspx) , where a user was trying to get the value of a dropdownlist's selected value kept in one UserControl, and set this value as text of one label which is from another UserControl. I have given the answer and giving here some of the description about the same post.

The Scenario is like; there is one UserControl - 1 in which there is one DropDownList. There is another UserControl - 2 in which there is one Label. In DropDownList's SelectedIndexChanged event; we need to set the selected value in Label which resied in UserControl - 2.

Everybody knows the purpose of FindControl (Control.FindControl Method (String) (System.Web.UI)) method; it searches the current naming container for a server control with the specified id parameter.

In addition, there is one property called NamingContainer (Control.NamingContainer Property (System.Web.UI)) which Gets a reference to the server control's naming container, that means it will give the parent container reference of current server control's.



Tha above image is showing the exact scenario which is discussed above. We need to set the Text property of Label with the selected value of DropDownList.
The idea to accomplish this; is, to get the parent control reference (using NamingContainer, for Ex., DropDownList1.NamingContainer will give the reference of its container UserControl - 1) of DropDownList; that is UserControl - 1, again get the parent control reference of the UserControl - 1; that is _Page. As now we got the reference of the Current Page, we can now easily find the second user control's Label with findcontrol method. Hope it makes sense :-)

Below is the Code:

WebUserControl1.ASPX:
A Simple UserControl with DropDownlList with some Static ListItems having AutoPostBack = True:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl1.ascx.cs"
    Inherits="WebUserControl" %>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem>Select</asp:ListItem>
    <asp:ListItem>test1</asp:ListItem>
    <asp:ListItem>test2</asp:ListItem>
    <asp:ListItem>test3</asp:ListItem>
    <asp:ListItem>test5</asp:ListItem>
</asp:DropDownList>

WebUserControl1.ASPX.CS:
A Simple One Line of code will access Label of Second UserControl on the page and set the Text Property of that label with Selected Text of this DropDownList:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) { }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //reaching to get the _Page reference with NamingContainer Property and using FindControl method to get the Label
        //DropDownList1.NamingContainer will give reference of the UserControl1's instance reference on the page
        //DropDownList1.NamingContainer.NamingContainer will give reference of the _Page's reference
        //Using FindControl Method to find UserControl - Control2
        //again using FindControl Method to find Label inside UserControl - Control2
        ((Label)((UserControl)((Panel)DropDownList1.NamingContainer.NamingContainer.FindControl("Panel1")).FindControl("Control2")).FindControl("Label1")).Text = DropDownList1.SelectedItem.Text;
    }

WebUserControl2.ASPX (No Code in Code Behind):
Simple defining a Label:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl2.ascx.cs"
    Inherits="WebUserControl2" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Finally Default.ASPX Page (No Code in Code Behind):
Placing both the controls inside a Panel Server Container control:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="kk1" TagName="Control1" %>
<%@ Register Src="~/WebUserControl2.ascx" TagPrefix="kk2" TagName="Control2" %>
<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Panel ID="Panel1" runat="server">
            <div>
                <kk1:Control1 ID="Control" runat="Server" />
            </div>
            <div>
                <kk2:Control2 ID="Control2" runat="Server" />
            </div>
        </asp:Panel>
    </form>
</body>
</html>

In, above example, you can see that with the benefit and use of NamingContainer Property; there doesn't require to take the reference of UserControl2 in UserControl1 to access Label inside. Thats it!