Archive for Microsoft

Regular Expression for Email Address validation in C#

The task at hand is to validate the Textbox in asp.net for a valid email address.

We can attach a RegularExpressionValidator to the text box with the following regular expression:

<asp:RegularExpressionValidator ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" ID="rxpEmail" runat="server"
ErrorMessage="Email Address is not valid" Text="*" Display="Static" ControlToValidate="txtEmail"></asp:RegularExpressionValidator>

Well i searched the net for the standards of a valid email id and i came across with a wonderful article at

I Knew How To Validate An Email Address Until I Read The RFC

It gives a an idea of what an exact RFC standard for the email id is.

I believe that we should follow validations which are quite obvious to the users and allow only standard email addresses.

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

Microsoft DotNet Interview Questions 2012

Recently I gave lot of interviews for Dot Net developer positions in various leading companies. I came across numerous good interview questions which sometimes confuse us. I would like to share with you all.

  1. What is Dependency Injection? Why is it required?
  2. Answer A brief introduction to dependency injection.

  3. Whether System.String class is a value type or reference type? Can we create an object of System.String class using new keyword?
  4. Answer Is string a value type or reference type in C#?

  5. What is the difference between System.String class and string keyword. Similarly what is the difference between int and System.Int32 etc.
  6. Answer What is the difference between String and string


  7. Why System.String class is immutable? What is the purpose behind this design by CLR?
  8. Answer Immutable types: understand their benefits and use them

  9. Are there any other types apart from System.String that are immutable? If yes which ones. If no then why this special treatment for System.String?
  10. Answer All core value types in framework like Byte, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, BigInteger, Complex, all enums, and so on are immutable.

  11. How is StringBuilder class implemented internally? What is the best approach to create a custom StringBuilder class?

  12. Why cant methods be overloaded based on return type in C#. Is it allowed by CLR? Is this feature available in any other .NET language?

  13. DateTime is reference type or value type?
  14. Answer:DateTime type in C#

  15. What are the advantages or disadvantges of using a value type over reference type?

  16. What are the advantages or disadvantges of using a reference type over value type?

  17. What is the main benefit of using Generic types?
  18. Answer:Why use generics in C# dot net

  19. Explain how boxing process is done by CLR from memory standpoint.

  20. Explain how unboxing process is done by CLR from memory standpoint.

  21. How CLR assigns allocates memory to references types? What are the operations that happen in memory when a reference of a type is created. What operations get executed when a new instance is created using new keyword and assigned to the reference of a class?

  22. How/Where is memory allocated for Static variables?

  23. How does CLR calls virtual methods? How does it actually trace the address in memory of the overridden definition of a virtual method?

  24. If protected accessor means accessible in family and internal means assembly(accessible in same assembly) then protected internal means? “family or assembly” or “family and assembly?
  25. Answer: Its “family or assembly”. Other one is not supported by C#. Refer more here: Access modifiers in C#.NET

  26. Why cant someone create an object of static class in dotnet?
  27. Answer: This is because CLR does not emit a default constructor in IL for the static class. For more about static keyword please browse to What is Static keyword in C#.


  28. What is a Managed Module?

  29. What is Strongly Named assembly?How do we attach strong name to an assesmbly why should that be done?

  30. Is a strongly Named Assembly tamper proof? Consider someone opens the assembly in a notepad and changes the binary content of the assembly and saves the file. Will this corrupted assembly get loaded? If Not why?

  31. Can a assembly be unloaded? How can this be achieved?

  32. What is the main reason of introducing the concept of AppDomains?

  33. If there are 2 websites running under IIS and one of them crashes, will it imapct the other one?

  34. Suppose you have developed an assmbly and distributed to hundreds of clients. After one year you relese a new version of the assembly, then how would this new version be deployed in production at all applications?

  35. How Garbage Collector works internally? Briefly describe the generations approach used by GC.

  36. Can GC be called on demand? Will GC get called when GC.Collect() method is executed?

  37. How can you restrict types that are allowed to be used in a generic type? For example, can a List be restricted so that T can only be Employee type?



Please hold your breath I will add the answers to these questions in coming days. Till then feedback and answers are welcome in comments but do provide the question number.

Also read SQL server interview questions.

Shout it

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

reCAPTCHA : Free Captcha service for ASP.NET

Its a common requirement that we require a captcha to be integrated on our page. I would like to mention a free captcha service which can be implemented in integrated on websites.

What is reCaptcha?

  1. reCAPTCHA is a free CAPTCHA service that helps to digitize books, newspapers and old time radio shows.
  2. It’s Free! Yep, reCAPTCHA is free.
  3. It’s Easy. reCAPTCHA is a Web service. As such, adopting it is as simple as adding
    a few lines of code on your site.
  4. It’s Accessible. reCAPTCHA has an audio test that allows blind people to freely
    navigate your site.
  5. It’s Secure. Most other CAPTCHA implementations can be easily broken.
  6. It’s Popular. Over 100,000 sites use reCAPTCHA, including household names like Facebook, Ticketmaster, and Craigslist.
  7. Whenever uses input data in reCaptcha control, they actually help digitizing books.

Moreover is very easy to integrate reCaptcha in our websites. Below are the steps
which are required to integrate it into a ASP.NET page.

Steps to Integrate reCaptcha in ASP.NET

  1. Register for a reCaptcha key : As a first step we need to register for recaptcha keys. Navigate to Get reCaptcha URL to signup for the keys. After we register for the keys, we get a public and private keys which we need to use in our asp.net page. By default all keys work on localhost as well.

  2. Download reCaptcha library for ASP.NET: Download the dll file from here. Also add the reference to the dll in the asp.net project.
  3. Add reCaptcha widget on ASP.NET page : Insert the reCAPTCHA control into the form you wish to protect by adding the following code snippets:
    • At the top of the aspx page, insert this:
      <%@ register
                      tagprefix="recaptcha" namespace="Recaptcha" assembly="Recaptcha" %>
    • Then insert the reCAPTCHA control inside of the form tag:
                      <recaptcha:recaptchacontrol id="recaptcha" runat="server" publickey="your_public_key"
                          privatekey="your_private_key" />
                      
  4. Make sure you use ASP.NET validation to validate your form (you should check Page.IsValid on submission).

As an example I created a ASP.NET page whose markup and code behind code looks as given below:

Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RecaptchaPage.aspx.cs" Inherits="ContosoUniversity.RecaptchaPage" %>
<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:Label Visible="true" ID="lblResult" runat="server" />

     <recaptcha:RecaptchaControl
              ID="recaptcha"
              runat="server"
              Theme="red"
              PublicKey="6LcoxcASAAAAAGAQQz_xOTk4-ALrRQri_Cf8AuhL"
              PrivateKey="6LcoxcASAAAAALfZhquqene7_4bTrzmuqHBrkuk0"
              />

          <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />

    </div>
    </form>
</body>
</html>

Code-behind

    public partial class RecaptchaPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid) 
            {
              lblResult.Text = "Captcha sucessfull!";
              lblResult.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
              lblResult.Text = "Incorrect";
              lblResult.ForeColor = System.Drawing.Color.Red;
            }
        }
    }

When I entered correct captcha text and pressed submit button following was the output:

When I entered incorrect captcha text and pressed submit button following was the output:

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

What is Static keyword in C#

In this post let us try to explore what is static keyword in C#

Definition of static keyword
As per MSDN, “Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.”

So it means that static keyword should be used with types which provide generic functionality and it doesn’t make sense to create objects of that type. For example, consider the System.Math class in c#. It provide various mathematical functions which can be used in the code as per requirements. And it doesn’t make sense to create an object of Math class to use those functions. Rather a typical usage will be like Math.Floor(0.5).

How CLR handles the static keyword
When a type is declared as static, CLR would:

  • Emit static keyword as abstract and sealed. What this means is that the type would become abstract and sealed. Sealed would make sure that type cant be further inherited.
  • It also doesn’t emit the default constructor in the type.This also means that since there is no contructor in the type, no instance for this type can be created.

Some restrictions on using the Static keyword

  • A static keyword can only be applied to reference types. Keyword cannot be applied on value types(like structures) because CLR always create instances of value types.
  • Static class can contain only static members(fields, properties, methods). This is because static class cannot refer to any instance members.
  • As already mentioned above, static class cannot be instantiated. Hence static class cannot be used in a manner which signifies it being used for some specific instance.

Hope above explanation clears the concepts regarding static keyword. If there are any questions you can post them and I would be happy to address them.

kick it on DotNetKicks.com

Shout it

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

Property elements in WPF: XAML

As we know XAML allows us to define properties of elements using the attribute syntax. It means that,for example, if we want to specify the content/background colour of button control than we can specify it using attributes as shown below:

<Button Content="Attribute Style" Background = "Yellow"/>

However there might be a challenge using this syntax. Consider a scenario where we want to display a rectangle inside the button. In this case it would not be possible to define a rectangle in the content attribute.This will be due to string restrictions of attribute syntax. To overcome this kind of scenarios, XAML provides the Property elements.

The syntax of property element is . So now we can provide a child tag under the Button tag to define the rectangle inside the button. The code would be

 <Button>
        <Button.Content>
            <Rectangle Height="40" Width="40" Fill="Yellow"/>
        </Button.Content>
    </Button>

Please note how beautifully the rectangle tag is given as child tag for Button.

kick it on DotNetKicks.com

Shout it

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare