Archive for the ‘ ’ Category

Write a program to calculate power(x,n)

Below solution divides the problem into sub problems of size y/2 and call the sub problems recursively

public static UInt64 Power(UInt64 x, UInt64 n)
    if (n == 0)
        return 1;
    else if (n % 2 == 0)
        return Power(x, n / 2) * Power(x, n / 2);
        return x * Power(x, n / 2) * Power(x, n / 2);


Test Case

UInt64 x = 0;
UInt64 n = 0;
x = 2; n = 2;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));
x = 2; n = 3;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));
x = 10; n = 2;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));
x = 12; n = 18;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));


2^2 =4
2^3 =8
10^2 =100
12^18 =8176589207175692288

Find the Length of a given number C#

        public static long Length(this long number)

            long length = 0;

            if (number < 10 && number >= 0)
                length = 1;
                return length;

            number = Math.Abs(number);

            while (number > 0)
                length += 1;
                number = number / _base;

            return length;

Test Case

Length of number 123 is  3

Length of number 1234567890 is  10

Length of number -123456 is  6

Length of number 9 is  1

Length of number 545 is  3

Length of number 123454321 is  9

Length of number -123454321 is  9

Trust Levels in

Trust levels let you define security rules. They define what types of operations an application can perform, such as reading from disk or accessing the registry. Each trust level has an associated policy file, except for Full trust. When an application runs with Full trust, code access security places no restrictions on the resources and operations that the application is allowed to access. Access to resources is based on operating system security and Microsoft Windows® access control lists (ACLs). Full trust is mapped to an internal handler, so it is not possible to edit the user rights to perform operations for an application. Full trust is effectively the absence of an application domain policy, and therefore it never has an associated policy file.

To protect ASP.NET applications, you can restrict access to resources and the operations that they can perform. You do this by setting the <trust> element to a predefined trust level in either the machine-level Web.config file or the application’s Web.config file.

The following list describes the predefined trust levels:


Applications that run at Full trust level can execute arbitrary native code in the process context in which they run. Because of the inherent risks that come with running in Full trust mode, this mode is not recommended in a shared environment except when every Web site uses its own application pool and application pool identity.

Important   The default trust level is Full trust. You should evaluate the security requirements for your environment and set the trust level appropriately.


Code in High trust applications can use most .NET Framework permissions that support partial trust. This mode is often appropriate for trusted applications that you want to run with fewer user rights in order to mitigate risks. For example, this level provides the same access as Full trust, but restricts access to unmanaged code and COM interop.


Code in Medium trust applications can read and write in its own application directories and can interact with Microsoft SQL Server™ databases. However, by default, the user rights that are needed to access OLE DB and ODBC are not granted to Medium trust applications. Medium trust is the recommended setting for a shared server, because it allows connections to SQL Server databases and restricts most other user rights to the application root structure.


Code in Low trust applications can read its own application resources but cannot make any out-of-process calls, such as calls to a database, to the network, and so on. By using Low trust, you effectively lock applications down to their application directory and remove all access to system resources.


Code in Minimal trust applications can execute but cannot interact with any protected resources. Minimal trust may be appropriate for mass hosting sites that want to support dynamic generation of Hypertext Markup Language (HTML) and isolated business logic.

The definition of the trust levels is essentially the same from ASP.NET version 1.1 through version 4. However, some of the user rights or operations that can be granted at each trust level vary slightly. For example, in ASP.NET 2.0 and later, Medium trust code can enable access to OLE DB APIs.

For information about how to run ASP.NET applications in a hosted environment, including trust levels and code access security, download the Microsoft Solution for Windows-based Hosting version 3.5 tool kit from the Microsoft download center. For information about hosting environments and architecture, see the Hosting Guidance for the Microsoft Web Platform on the Web site.

Bing & Ping: Share Bing Search Results With Your Friends

Bing team in Microsoft working very hard to add more and more new feature in Bing. Bing team is now trying to build a bridge between Bing search results and social networking website. Bing & Ping will enable users to share their Bing search results with their friends on different social networking websites.

How Bing & Ping would Work ?


Bing & Ping will appear at the bottom of search results and users will be able to share these search results information with their friends via Social networking websites including Facebook, Twitter or they can simply send them an E-Mail.

Bing & Ping allow Bing users to share any kind of search results with their friends.

Bing & Ping

Bing & Ping

Bing & Ping is not yet available for testing yet but Microsoft only delivered a taste of the feature in the screenshots included with this article. If you’re interested in previewing this feature, be sure to become a fan of our Facebook page. Microsoft will be sending a special invitation to our fans to preview Bing and Ping. Check it out and let Bing team know what you think, if you like it and how Bing Team can make it better.

ASP.NET 4.0 Roadmap

Take a walk through the 4.0 landscape from ASP.NET and learn how you can get involved in shaping ASP.NET future. This talk focuses on the next release of ASP.NET including Web Forms and MVC. Do you love web forms? See how you can taking control of your control IDs, learn about better ViewState managment in GridView and ListView, and get more control over the CSS markup of ASP.NET server controls. See how Dynamic Data makes building you data-driven apps easy. If you’re interested in AJAX, we show you further advancements in client rendering and binding. If you’re considering MVC, we look at the feature set and understand how to create applications with this technology.


Via Dot Net TV

Professional VB.Net Programming

An Overview of HTTP Handlers

An HTTP handler is a process that runs on server to response to a particular type of request. HTTP handlers can be referred to as endpoint also. A typical example of HTTP handlers is when page handler which is used by engine to process the request that come for .aspx files.

Built In HTTP Handlers in

Handler Description Page Handler (*.aspx) A default page handler for all pages.
Web Service handler(*.mspx) The default HTTP handler for Web service pages created as .asmx files in ASP.NET.

Generic Web handler (*.ashx)

The default HTTP handler for all Web handlers that do not have a UI and that include the @ WebHandler directive.

Trace handler (trace.axd)

A handler that displays current page trace information. For details, see How to: View ASP.NET Trace Information with the Trace Viewer.


How to Create A Custom HTTP Handler

To create a custom HTTP Handler you need to implement either IHttpHandler or IHttpAsyncHandler for synchronous and asynchronous handlers. Both these interfaces expose two methods called IsReusable and ProcessRequest. ProcessRequest method is the place where you write code for handling request of your custom handler. The IsReusable property specifies whether the IHttpHandlerFactory object (the object that actually calls the appropriate handler) can put the handler in a pool and reuse it to increase performance. If the handler cannot be pooled, the factory must create a new instance of the handler every time that the handler is needed.

Public Class CustomHand
    Implements IHttpHandler

    Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable

        End Get
    End Property

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

    End Sub
End Class

Mapping File Extension in IIS

By Default IIS is going to respond to file extension that is for custom handler. If you created a new file extension for HTTP Handler then you have to explicitly register the file extension in IIS and have to add a mapping entry in web.config file for your custom handler.

ASP.Net Exception Handling-Part I

.Net languages support structured exception handling means when ever an exception occurs .Net framework creates an exception object, this exception object represents complete information about the exception. You can catch this exception object using the try catch block code if your application failed to catch the exception then you see a error page like this

Exception Handling

Structured Exception Handling Features

  • Exceptions are objects means each exception wrapped with significant amount of useful information about exception instead of just plain text explaining the exception message or cause of exception. These exception objects also support an InnerException property that allows you to wrap a generic error over the more specific error that caused it. You can even create and throw your own exception objects.
  • Exception can be caught based on their type means you can catch specific type of exception following code show an example of this
    IO.File.Open("F:\testfile.text", IO.FileMode.Open)

Catch ex As IO.FileNotFoundException
    Console.WriteLine("File Not found")
Catch ex As IO.PathTooLongException
    Console.WriteLine("File Path is to long")
End Try

  • Exception handlers can also be used in layered manner means you can always create exception handlers on top of other exception handlers for different section of code to handle their exception separately.
  • Exceptions are generic part of .Net framework.


Exception Class Overview

Exception class is base class for all exception classes. Exception class defines two type of exceptions

  • SystemException: This class provides a means to differentiate exception caused by system or application. SystemException does not provide information about the cause of exception and try to avoid throwing instance of this class , if there are cases when you want to throw or created object of this class , a human readable message describing the error should be passed to the constructor.
  • ApplicationException: The ApplicationException class differentiates between exceptions defined by applications versus exceptions defined by the system. If you are creating your own exception class then it is always advised to derive custom exception class from Exception class. Deriving custom exception class from ApplicationException class does not add any significant value to derived class.

Exception Class Properties

Exception includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.

In Next article we will discuss more about exception class members and how to write a exception handling block.

ASP.NET State Management Overview

As HTTP is stateless, meaning the connection to the server does not remain open. When ever page is post back to server a new instance of the class is created this means there is a overhead of loading all the values associated with controls that are present on the page because http is a stateless protocol and each round trip to the server causes controls to loose their values. To overcome the inherent limitation of http protocol ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:

View state

View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view-state hidden field or fields.

Control state

Control state is used to store the state information specific to control. This property is very useful when you are creating custom control and want to know the current state of control.  AS compare to view state property which can be turned off by developer at page level and that can cause your control to break, in case of control state property that can not be turned off like view state.

Hidden fields

Hidden fields are controls that provide a way to store information and at the same time they are not visible to the user. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page. It is easy to see and modify the hidden field value so it is always recommend that never store sensitive information in Hidden field.


Cookies are basically small text files that are used to store small amount of data on client file system. Cookies can also be stored in clients main memory. Cookies can be temporary (with specific expiration times and dates) or persistent. Generally cookies are used to store information about a particular client, session or application. When a client send a request to the server, browser also sent the cookie to the server, Server then extracts value from the cookie. Typically cookies are encrypted and used for storing user authentication information and user profile preferences.

Response.Cookies("destination").Value = "CA"
Response.Cookies("destination").Expires = DateTime.Now.AddDays(1)

Query strings

Query String is a key value pair that is appended at the end of url with a question mark (?). Query string is a very simple way to send information to the server but it is highly browser dependant. Different browsers have different length for query string. Information passed through query string is easily viewed by the client so query string is not a good option for sending sensitive information to the server.

View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways.

Application state

Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another. Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of objects. The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class.

Application("WelcomeMessage") = "Welcome to the Contoso site."

Session state

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Session("FirstName") = FirstNameTextBox.Text
Session("LastName") = LastNameTextBox.Text

Profile Properties

Profile property is a new feature in that allow you to store user specific data this some thing like session but profile information is not lost when a user session is expire. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.

Profile.PostalCode = txtPostalCode.Text

You must define the PostalCode property in the Web.config file by using the following markup:

      <add name="PostalCode" />

Application state, Session state, and profile properties all store data in memory on the server.

We will discuss each of the state management feature in more detail in upcoming articles. some of the definitions are taken from MSDN

Silverlight Layout Container Panels – Dock Panel

Silverlight Dock Panel is one of the Silverlight Panel that enables layout. DockPanel is used to arrange a set of objects around the edges of panel. Dock Panel’s Dock property enables you to specify the location of objects inside Dock Panel. If you set the LastChildFill property to true (the default value) and the last element is allowed to resize, the last element added to the panel will resize to fill the remaining space. If the last element is set to a specific size, the last element will be set to the specified size and positioned in the middle of the remaining space. The order in which elements are added to the DockPanel is important.


DockPanel Example

<Border BorderBrush="Black" BorderThickness="3" >
            <StackPanel x:Name="LayoutRoot" Background="White">
                <TextBlock Margin="5" Text="Dock Panel" />
                <Border BorderBrush="Black" BorderThickness="3" >
                    <controls:DockPanel LastChildFill="true" Height="265">
                        <Button  Content="Dock: Left" controls:DockPanel.Dock ="Left" />
                        <Button Content="Dock: Right" controls:DockPanel.Dock ="Right" />
                        <Button  Content="Dock: Top" controls:DockPanel.Dock ="Top" />
                        <Button  Content="Dock: Bottom" controls:DockPanel.Dock ="Bottom" />
                        <Button Content="Last Child" />

In Next we will discuss about Dock Panel Grid