Visual Studio 2010 & .Net Framework 4.0

Tuesday, September 30, 2008
I found an Article about Visual Studio Team System (VSTS) 2010. I was amazing to see the Microsoft Announcement. Because till now most of the developers (me also) dint use the Visual Studio 2008. And don’t know much about Framework 3.5. But being a programmer we have to update our knowledge with current technology. So I decided to start VS2008 as soon as possible....!

So..Here I am mentioning some details about VS2010. Microsoft Announce that this Framework as .Net Framework 4.0 and it code name is “Rosario”. The main features are collaborative development, modeling, and debugging.

In This Framework Major pillars are..
  • Democratizing Application Lifecycle Management(ALM)
  • Enabling emerging trends
  • Inspiring developer delight
  • Riding the next generation platform wave
  • Breakthrough Departmental Applications.

If you like to know more details here are the links....

Playing Videos - Part II

Friday, September 26, 2008

In Playing Videos-I I have been explained to upload a videos, how convert video from one format to another format and how to generate thumbnail automatically. In this post I am going to expalin how to retrive the videos and thumbnail dynamically from database.

First I am starting with DataBase part, Here I am creating a table called videos. And it contains 3 fields the are
Video_ID,Video_File,Video_Image. You can see the table design pic.

Here "Video_File" field contains Name of the video with extension. Here I am going to store the file name only. But the video file is located in server. "Video_Image" is the thumbnail file name with extension. Same as video thumbnail also located in server.

When I am uploading video, I am going to save the videofilename, Image name in database. Here I used very simple code to insert this details. Here is the code.....

private void Savedetails()
string filename, imgname;
filename = Session["outputfile"].ToString();
imgname = Session["thumbname"].ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into video(Video_File,Video_Image) values('" + filename + "','" + imgname + "')", con);

You can use stored procedures in back end for the better performance. Once the video uploading is finished then I am going to show these details in DataList. Here is the code to bind the video thumbnail in Datalist

<asp:DataList ID="dtlstVideo" runat="server" GridLines="Vertical"
RepeatColumns="2" RepeatDirection="Horizontal" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="5">
<td><a href="Play.aspx?vid=<%# DataBinder.Eval(Container.DataItem, "Video_ID") %>">
<img src="Video/Thumb/<%# DataBinder.Eval(Container.DataItem, "Video_Image") %>" border="0" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<AlternatingItemStyle BackColor="#DCDCDC" />
<ItemStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedItemStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />

when the user click on the datalist it will be redirected to play.aspx with video ID as the query string. In the
play.aspx page I am goign to bind the SWF player with video file name. Here is the code...

string vid,vfname;
protected void Page_Load(object sender, EventArgs e)
vid = Request.QueryString["vid"].ToString();
DataSet dst = (DataSet)Session["videods"];
DataRow[] dw = dst.Tables[0].Select("Video_ID= '"+ vid +"'");
if (dw.Length > 0)
vfname = dw[0]["Video_File"].ToString();
string plyr = "<embed src='Players/flvplayer.swf' width='425' height='355'
bgcolor='#FFFFFF' type='application/x-shockwave-flash'
flashvars='file=Video/SWF/" + vfname + "&autostart=false&frontcolor=0xCCCCCC&
plh.Controls.Add(new LiteralControl(plyr));

You can see the screen shot of playing a video dynamically..

Source Code

Playing Videos like YouTube and Thumbnail Creation in ASP.Net - I

Monday, September 22, 2008
If you want to play video like youtube in your ASP.Net application what will you do? Can you able to generate thumbnail for the video programmatically? How did you play converted video?? All these are for Free of cost. No need to buy any software then how??.

This article will provide solutions for the above questions. Generally we can see some video sites like youtube. Here we can watch streaming media. But when you upload a wmv file into server and try to play it. What happen? If the video is long it will take time to play. For this reason we have to convert the video to a streaming media(like swf) so that when the page is opened automatically video playing started.

For this we have to convert the video which is uploaded by the user to swf. Then only we can able to play the video quickly. In order to convert the video we will use a software called FFMPEG. It’s open source software you can download this software from here.

Using FFMPEG we can able to generate thumbnails for the video what ever we are uploading. By using FFMPEG’s API we can perform various operations for the videos and audios.
In order to start this Application first we have to import following name spaces…

using System.IO;
using System.Diagnostics;

When User Clicks on Upload button then we have to perform following tasks.

  • Check the Format of Video
  • Convert the Video to flv format with FFMPEG
  • Generate a Thumbnail for the uploaded video
  • Delete the original video.
  • Check the Format of Video

    Here I am using Regular Expression to check the video format. I want to upload only wmv, mpeg, or avi format videos. Here is the regular expression

    <asp:RegularExpressionValidator id="req1" runat="server"

    ErrorMessage="Only wmv, avi or mpeg files are allowed!"


    ControlToValidate="FileUpload1" Display="dynamic"></asp:RegularExpressionValidator>

  • Convert the Video to flv format with FFMPEG
    To Convert our video to SWF format FFMPEG need File Name, File Arguments. File Name is the name of the FFMPEG folder with full path. Arguments can be write as..
  • The general syntax is ..
    ffmpeg [[infile options][@option{-i} infile]]... {[outfile options] outfile}...

    filargs = "-i " + inputfile + " -ar 22050 " + outputfile;
    To run the FFMPEG exe we have to start a Process. This can be write as..
    Process proc;
    proc = new Process();
    proc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
    proc.StartInfo.Arguments = filargs;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = false;
    proc.StartInfo.RedirectStandardOutput = false;
    catch (Exception ex)

    • Generate a Thumbnail for the uploaded video

      For the thumbnail we have to provide path to where we have to save our thumbnail. Here is code for thumbnails..

  • //Create Thumbs
    string thumbpath, thumbname;
    string thumbargs;
    string thumbre;
    thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Video\\Thumb\\";
    thumbname = thumbpath + withoutext + "%d" + ".jpg";
    thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:07 -s 150x150 " + thumbname;
    Process thumbproc = new Process();
    thumbproc = new Process();
    thumbproc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
    thumbproc.StartInfo.Arguments = thumbargs;
    thumbproc.StartInfo.UseShellExecute = false;
    thumbproc.StartInfo.CreateNoWindow = false;
    thumbproc.StartInfo.RedirectStandardOutput = false;
    catch (Exception ex)

  • Delete the original video.
    Once the conversion process is completed we delete wmv file. Here is the code.

  • Here the most important thing is “Permissions”. In order to convert the video and generate the thumbnails we have to provide all permissions to our application. Especially for the folder where your going to save the videos and thumbnails.

    If you’re using FFMPEG in Remote server then you have to give all permissions to FFMPEG folder also. Because here we are running an exe to convert the videos.

    When ever you upload videos more then 4096 KB, ASP.Net does not allow you to upload the video because It’s the Max HTTP Request size for any application. If you want change the HTTP request size you have to change the “maxRequestLength” in web.config section. Here is the complete code..

    apartmentThreading="false" />

    Now you can able to upload videos upto 30MB.

    How to Play Video:
    Using swf player we can play the video. In the sample application you can find this player. For this player we have to give the source file name with correct path. You can find play.aspx file in source code to know more about how to play the videos.

    In Part-I, I am explained how to convert the video from one format to another format and generating thumbnails. In Part-II I am going to explain how to bind this thumbnail to Gridview or DataList dynamically from Database and how to play the videos.

    Note: In the sample I did not place the ffmpeg software due to the size.(Its around 10MB)
    You can download for here:ffmpeg.rar
    Downloadm Source Code

    Reading Contacts(Address Book) from Yahoo, Gmail, Rediff, MSN, AOL

    Saturday, September 13, 2008
    When we are developing a scoal networking websites or Some Referal websites, when the user registration completed then we have to provide an interface to invite the registerd user friends. For this purpose we have to provide option to get contcats (AddressBook) from various Email Providers.

    Here I am taking some popular Email Providers like Yahoo, Google, MSN, Rediff, AOL. In order to Read the Address book of Yahoo, Google, Rediff, MSN, AOL we have access the API which provided by them itself.
    Few days before I download one one dll from net. Its provided by Ideabubling. It contains all API of Yahoo,Google, Rediff, MSN, AOL, which is ready to use. Here In this application I use the dll.

    The Core Functionality is, when user provides Email Address and Password, If these details are valid then we will call getContact method and these details are stored in DataTable. You can see the sample code here..

    DataTable dtContatct = new DataTable();

    MailType mt = FindTheMailType();

    MailClient.GetContacts(mt, strUserid, strPassword, out boolIsOK, out dtContatct, out strError);

    dtContatct = MailClient.GetFormat(mt, dtContatct);

    Here “mt” is the mail type. It will check what type of Email Address It is. Either Yahoo, Gmail, etc.
    Then this DataTable is binded with GridView, so that User can able to see his contcats and he can select some of the or all to send a mail.
    You can see the Screen Shot..

    Download Complete Application.. Click Here..!

    Ajax ModalPopupExtender

    Thursday, September 11, 2008
    Actual Functionality Of A Modal Popup:
    Modal pop ups were among the first JavaScript effects to be widely adopted by web Sites like Google and Amazon who were looking for an interactive edge with their Customers.

    The window.alert( ) method implements the effect, however, the layout of these pop ups could not be changed. Thanks to CSS and the DOM, today you can Create better pop ups, without the need to open new windows.

    Modal pop ups are commonly generated by creating a new DOM element (usually a <div> container), using JavaScript to display the element, then CSS to style it. To Make the pop up modal, you also create a second <div> element that consumes the Complete display area of the browser.

    Then using the z-order CSS property (which Sets the virtual z coordinate of an element, effectively placing elements in front of or Behind each other), stack both elements over the current content of the page; “100%
    display area” <div> first, then the pop up <div>.

    Now The stacking part is taken care of by ASP.NET AJAX; you just have to provide the rest.

    Then, the original content of the page is still visible, but since a 100 percent width, 100 percent height element is placed over it, the user cannot click any links outside the pop up, effectively making the pop up modal.

    Steps for Creating Modal popup:

    The first step to implement this is to create the appropriate CSS classes. We need two: one for the pop up, one for the 100 percent display area <div>.
    For the first class, we just apply a border, a background color, and a width (the height is determined automatically by the browser’s rendering engine):

    .popup {
    border: solid;
    background-color: yellow;
    width: 200px;

    The second CSS class also uses a background color, such as gray, but we also set an opacity value so that the background (the content of the page) is visible through the element. Internet Explorer supports the filter property for this task, and all other browsers use the opacity style.

    .content {
    background-color: grey;
    filter: alpha(opacity=50);
    opacity: 0.5;

    Next, we need a server control to display the modal pop up. A link is a good choice:
    <asp:HyperLink ID="HyperLink1" runat="server" Text="More ..." NavigateUrl="#" />
    Now we create the actual pop up. As shown here, the user could be prompted to log in:

    <asp:Panel ID="popupPanel" runat="server" CssClass="popup">
    <p>Login to get more information!<br />
    User <input type="text" /> - Password <input type="password" />
    <input type="button" value="Login" id="Button1" runat="server" />

    Finally, the ModalPopupExtender from the ASP.NET AJAX Control Toolkit comes into play. It lets you create a modal pop up that can be put over the current content of the page. This includes a bit of work, both from the toolkit and from you. You will need the following properties for ModalPopupExtender:

    BackgroundCssClass:The CSS class to use to make the page’s contents look disabled
    PopupControlID:The ID of the pop up to display
    TargetControlID:The ID of the element that triggers showing the pop up
    OKControlID:The ID of the element that lets the pop up disappear
    (The default position is the center of the page.)

    A Complex Modal PopUp:
    In this situation, Assume that we have a Registration form which may contains username, password, conformpassword,Email. Then we have a Register Button, when user clicks on Register Button we have to perform Following actions

    • Check the validation
    • If validation success then dispaly Licensense Aggreement in ModelPopup.

    In this situation modelpopup will not display if gave TargetControlID="btnregister". For this purpose we have to take an hidden button pass the hidden button id as TargetControlID.
    In the register button click event write the follwing code;
    Now when the validation successful then only modal popup control visible.
    You can download the complete source code. Click Here

    Working with POPUPs in ASP.Net

    Wednesday, September 10, 2008
    In an application I have a requirement like in this way. There are some details about USER like User Name, First Name, Last Name, Email, Mobile Number, and City. After that I have Four buttons with named as Search, Clear, Save, Delete.
    You can see the Screen Shot

    Here the main functionality is when I click on Search button a POPUP Window has to be opened that window contains search functionality for users. When I open the window it will provide a functionality to search user by User Name, City Name. When I provide User Name or City Name and clicked on Search button it will display all related details in Grid. And this grid has to be allowing me to select a row. When I clicks on any row of the grid automatically the grid has to be closed and a selected row detail has to be displayed in the Main Form where search button located.

    Search Screen shot

    In order to achieve this functionality I used Java script with DOM, which allow me to send the search results to Parent window when user clicks on the grid and to close pop window.

    search results

    Grid contains hyper links when user clicks on that one it will call a Java script function. Here is the sample code..!

    <asp:TemplateField HeaderText="User Name">
    <a style="cursor: hand" onmouseover="'underline'" onmouseout="'none'"
    name="UserName" onclick="javascript:CalltoParent(this)" runat="server"
    <%# DataBinder.Eval(Container.DataItem, "UserName") %>

    When user clicks it will call “CalltoParent” and here we are passing the Current Node value.
    Java Script function can be written as..!

     function CalltoParent(user)
    var uval=user.parentNode.parentNode;
    window.opener.document.getElementById('txtuname').value = uval.childNodes[0].childNodes[0].innerText;
    window.opener.document.getElementById('txtfname').value = uval.childNodes[1].childNodes[0].innerText;
    window.opener.document.getElementById('txtlanme').value = uval.childNodes[2].childNodes[0].innerText;
    window.opener.document.getElementById('txtmail').value = uval.childNodes[3].childNodes[0].innerText;
    window.opener.document.getElementById('txtmobile').value = uval.childNodes[4].childNodes[0].innerText;
    window.opener.document.getElementById('txtcity').value = uval.childNodes[5].childNodes[0].innerText;
    return true;

    Source Code

    Microsoft Virtual TechDays on Sept 17,18, 19

    Sunday, September 7, 2008
    Microsoft Virtual TechDays goingon from September 17 to 19. In this TechDays you can learn the following Technologies..
    • .Net 3.5 Service Pack 1
    • Microsoft Visual Studio 2008
    • Microsoft Visual Studio Team Suite
    • ASP.Net
    • Silverlight
    • Internet Explorer 8
    • Windows Vista
    • Virtualization
    • Windows Presentation Foundation(WPF)
    • Windows Mobile Development
    • Microsoft SharePoint Server
    • Microsoft SQL Server 2008
    • LINQ
    • Patterns and Practices
    • Security

    For Registration Click Here..!

    Dotnet Coding Standards

    Monday, September 1, 2008
    We Fallow the Coding Standards to enforce consistent style and formatting in developing the applications. Here I am explaining the following things.
    • Naming Conversions and Style
    • Coding Practices
    • Error Handling
    • Data Access
    1. Naming Conversions and Style
      1. Use Pascal casing for type and method and constants
      2. Ex: public class SomeClass
        const int DefaultSize= 100;
        public SomeMethod ()
        { }

      3. Use camel casing for local variable names and method arguments
      4. Ex:
        int number;
        void MyMethod (int someNumber)
        { }

      5. Prefix member variables with m_. Use Pascal casing for the rest of a member variable name following the m_.
        Ex:public class SomeClass
        private int m_Number;

      6. Name methods using verb-object pair, such as ShowDialog ().
      7. Method with return values should have a name describing the value returned, such as GetObjectState ().
      8. Use descriptive variable names
      9. Always use C# predefined types rather than the aliases in the System Namespace.
      10. For Example:
        object NOT Object
        string NOT String
        int NOT Int32.
      11. Use meaningful namespace such as the product name or the company name.
      12. Avoid fully qualified type names. Use the using statement instead.
      13. Avoid putting a using statement inside a namespace.
      14. Group all framework namespaces together and put custom or third-party namespaces underneath.
      15. Example: 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 MyCompany;
        using MyControl;
      16. Maintain strict indentation. Do not use Tabs or non standard indentation. Such as one space. Recommended values are three or four spaces, and the value should be uniformed across.
      17. Indent comment at the same level of indentation as the code you are documenting.
      18. All comments should pass spell checking. Misspelled comments indicate sloppy development.
      19. All member variables should be declared at the top, with one line separating them from the properties or methods.
      20. public class MyClass
        int m_Number;
        string m_Name;
        public void SomeMethod1()
        { }
        public void SomeMethod2()
        { }
      21. Declare a local variable as close as possible to its first use.
      22. A file name should reflect the class it contains.
      23. Always place an open curly ({) in a new line.

    2. Coding Practices:
      1. Avoid putting multiple classes in a single file.
      2. A single file should contribute types to only a single namespace. Avoid having multiple namespaces in the same file.
      3. Avoid files with more than 500 lines (Excluding machine-Generated code)
      4. Avoid method with more than 25 lines.
      5. Avoid methods with more than 5 arguments. Use structures for passing multiple arguments.
      6. Do not manually edit any machine generated code.
      7. If modifying machine generated code, modify the format and style to match this coding standard.
      8. Use partial classes whenever possible to factor out the maintained portions.
      9. Avoid comments that explain the obvious. Code should be self-explanatory. Good code with readable variables and method names should not require comments.
      10. Document only operational assumptions, algorithms insights and so on.
      11. Avoid method level documentation.
      12. With the exception of zero or one, never hard-code a numeric value; always declare a constant instead.
      13. Use the const directive only on natural constants such as the number of days of the week.
      14. Avoid using const on read-only variables. For that, use the readonly directive.
      15. Every line of code should be walked through in a “white Box” testing manner.
      16. Catch only exceptions for which you have explicit handling.
      17. Avoid error code as method return values.
      18. Avoid defining custom exception classes.
      19. Avoid multiple Main () methods in a single assembly.
      20. Make only the most necessary types public. Mark other as internal.
      21. Avoid friend assemblies. As they increases inter assembly coupling.
      22. Avoid code that relies on an assembly that running form a particular location.
      23. Minimize code in application assemblies (EXE client assemblies). Use class libraries instead to contain business logic.
      24. Always use a curly brace scope in an if statement, even if it contains a single statement.
      25. Always use zero based arrays.
      26. Do not provide public or protected member variables. Use properties instead.
      27. Avoid using “new” inheritance qualifier. Use “override” instead.
      28. Never use unsafe code. Except using interop.
      29. Always check a delegate for null before invoking it.
      30. Classes and Interfaces should have at least 2:1 ratio of methods to properties.
      31. Avoid Interfaces with one member. Strive to have three to five members per interface. Don’t have more than 20 members per interface.12 is probably principle limit.
      32. Prefer using explicit interface implementation.
      33. Never hardcode strings that might change based on deployment such as connection strings.
      34. When building a long string use “StringBuilder”, not “String”.
      35. Don’t use late binding invocation when early-binding is possible.
      36. Use application logging and tracing.
      37. Never use “go to” unless in a switch statement fall-through.
      38. Don’t use the “this” reference unless invoking another constructor from within a constructor.
      39. Avoid casting to and from “System.Object” in code that uses generics. Use constraints or the “as” operator instead.
      40. Do not use the base word to access base class members unless you wish to resolve a conflict with a subclasses member of the same name or when invoking a base class constructor.

    3. Error Handling:
      1. Error handler should be present whenever you anticipate possibility of error.
      2. Do not use Try-catch for flow- control.
      3. Never declare an empty catch block.
      4. Error Message should be user friendly, simple and understandable.
      5. Errors should be raised in the routines present in the components and captured in the application’s GUI.
      6. Use Try-Catch statements in each and every function you write. Adhere to it strictly with out fail.
      7. Use dispose on types holding scarce resources, i.e., files, database connections.

    4. Data Access:
      1. ANSI SQL 92 standards have to be followed for writing queries.
      2. Do not put order by clause in the query unless required.
      3. Do not encapsulate readonly database operations in transactions.
      4. Use a stored procedure with output parameters instead of single record SELECT statements when retrieving one row of data.
      5. Stored procedure execution is fast when we pass parameters by position (the order in which the parameters are declared in the stored procedure) rather then by name.
      6. After each data modification statement inside a transaction, check for an error by testing the global variable @@ERROR
      7. Verify the row count when performing DELETE operation
      8. Use RETURN statement in stored procedures to help the calling program know whether the procedure worked properly.
      9. Key words should be capital. For example; SELECT, UPDATE, DELETE, INSERT, FROM, AND WHERE, etc.
      10. Do not use “SELECT * FROM” type of query. If all the columns of the table are to be selected, list all columns in the SELECT in same order as they appear in the table definition.
      11. While writing a query as a string, do not put any space after single quote (‘). There should be a single space between every two words. There should not be a space between the last word and the concluding single quote (‘).
      12. Where multiple columns are selected, there should be a single space after every ‘,’ between two columns.
      13. All the major keywords should come on the new lines
      14. The number of columns in a SELECT statement should not be more than 6. The line separator should be placed in this case after the (,) of the last column of this line and a single space.
      15. For any new line separator, the separator should come after a single space after the last word of the line.
      16. Place a tab after each key word on a new line.