Showing posts with label technology. Show all posts
Showing posts with label technology. Show all posts

Tuesday, October 18, 2011

Using multiple authentication modes in a single ASP.NET application


Summary
ASP.NET only allows a single authentication mode to be configured for each application. Some applications may require different modes for different paths. For example, if an application uses Forms authentication for users of the public site, and Windows authentication for users of the administration site.
Resolution
One solution is to create two separate applications; one for the public site using Forms authentication, and one for the administration site using Windows authentication. However, this will mean that resources in the public application cannot be accessed from the administration application using app-relative paths (e.g. /images/logo.jpg).
A better solution is to use the global.asax file to handle theFormsAuthentication_OnAuthenticate event, and apply Windows authentication where appropriate.
  1. In IIS, open the properties of the administration folder;
     
  2. Under "Directory Security", edit the anonymous access and authentication settings, and disable anonymous access;
     
  3. Edit the web.config file, and configure the application to use Forms authentication;
     
  4. Add the following code to the global.asax file in the root of the application:



<%@ Application Language="C#" %>
<%@ Import Namespace="System.Security.Principal" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.Security" %>
 
<script runat="server">
 
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e)
{
    if (null == e) throw new ArgumentNullException("e");
     
    // Check that we have a Windows user
    WindowsIdentity winUser = e.Context.Request.LogonUserIdentity;
    if (null == winUser) return;
     
    // Check that the path allows Windows authentication
    string path = VirtualPathUtility.ToAppRelative(e.Context.Request.Path);
    if (!IsWindowsAuthenticated(path, e.Context)) return;
     
    // Don't allow guest accounts to access
    if (winUser.IsAnonymous || winUser.IsGuest || winUser.IsSystem) return;
     
    WindowsPrincipal winPrincipal = new WindowsPrincipal(winUser);
    if (winPrincipal.IsInRole("Guests")) return;
     
    e.User = winPrincipal;
}
 
private static bool IsWindowsAuthenticated(string path, HttpContext context)
{
    if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
    if (null == context) throw new ArgumentNullException("context");
     
    // Check that the path starts with the restricted folder:
    if (path.StartsWith("/restricted/", StringComparison.OrdinalIgnoreCase)) return true;
     
    return false;
}
 
</script>



      5. Requests to the administration folder will now use Windows authentication; the rest of the site will continue to use Forms authentication

Saturday, June 18, 2011

Observer Design Pattern in C#


Definition

The Gang of Four book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995) says that the Observer design pattern should "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Purpose of Observer Pattern

The Observer pattern is to notify the interested observers about some change occurred. We can add more observers in runtime as well as remove them.

Example: We have a form to select the color. For each color change we need to update the entire application. There will be observers listening to the color change event for updating themselves.

Subject and Observers

The two important key terms in the pattern are Subject and Observer.

Subject is the object which holds the value and takes responsibility in notifying the observers when the value is changed. The subject could be a database change, property change or so.

We can conclude that the subject contains the following method implementations.
public interface ISubject{
    void Register(IObserver observer);
    void Unregister(IObserver observer);

    void Notify();
}


The Observer is the object listening to the subject's change. Basically it will be having its own updating/calculating routine that runs when get notified.
public interface IObserver{
    void ColorChanged(Color newColor);
}


In the above example, we are using an observer interface which has a ColorChanged method. So the interested observers should implement this interface to get notified.

There will be only one Subject and multiple number of Observers.

Registering and Unregistering

In the above interface, the observer can use the Register() method to get notified about changes . Anytime, it can unregister about notifications using the Unregister() method.

Notifying

The Notify() method will take care of calling the listening observers.

Associations

The Subject and Observer objects will be having a one-to-many association.

ObserverPatt1.gif

Using the Code

The associated code is having a main form, where the Subject would be a class named ColorSubject.
public class ColorSubject : ISubject{
    private Color _Color = Color.Blue;
    public Color Color
    {
        get { return _Color; }
        set
        {
            _Color = value;
            Notify();
        }
    }
    #region ISubject Members
    private HashSet<IObserver> _observers = new HashSet<IObserver>();
    public void Register(IObserver observer)
    {
        _observers.Add(observer);
    }
    public void Unregister(IObserver observer)
    {
        _observers.Remove(observer);
    }
    public void Notify()
    {
        _observers.ToList().ForEach(o => o.ColorChanged(Color));
    }
 
    #endregion}
The class implements ISubject interface and thus takes care of registering, unregistering and notifying the interested observers. All the observers keep registered with the ColorSubject object.

Screen Shot of Application

ObserverPatt2.gif

On running the associated project, we can see a color selector form, which acts as as the subject. All the other forms are observers listening to the ColorChanged event.

Note: The multicast event model in .Net can also be considered as an observer pattern. Here the interested parties register a method with the subject (might be a button) and whenever the button is clicked (an event) it invokes the registered observers (subscribers)

Conclusion

In this article we have seen what Observer pattern is and an example implementation.

Passing Values From JavaScript Functions to ASP.Net Functions in ASP.Net

Sometimes it necessry to pass values from a JavaScript function to an ASP.Net function. For example, we have a table and a GridView control on a page. In our table there are fields such as Employee Name, Age and Salary of the Employee and the condition is that only those employees should be added to the database whose age is greater than or equal to 25 and we want to carry out the validation process using JavaScript on a single click event of a button control and if the age is greater than or equal to 25 it should be added to the database and the corresponding records should be displayed in the GridView control.

So for beginning with this example we need to create a table named Emp in our database. I've created Test as a database. These are the following SQL queries.
create database Testuse Testcreate table Emp(EmpName varchar(20) not null,EmpAge int not null,EmpSalary money not null)
select * from Emp.

Now to begin with the ASP.Net code.

The following design needs to be done.


By default there are no records in the emp table; that's why the GridView will not display any records. Now fill the table with the required fields and then click on the save button. Like in the following:

PVasp1.gif
PVasp3.gif

Once you click on the save button a message will be ask if you want to add these details? If you click on ok it will check whether your age is greater than or equal to 25 or not. If it is not then it will display an error message or else it will add the details to the database and display it in GridView.
PVasp4.gif

In this case my age was 23 so it is not greater than 25 so it displayed the error message.
The following is the source code of our Default.aspx and Default.aspx.cs.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>   <script type="text/javascript">        function ValidateAge()
        {
            //var a=document.getElementById('<%= //TextBox2.ClientID%>').value; // or //var a=document.forms[0]["TextBox2"].value; 
           var a=document.forms[0]["TextBox2"].value; 
          var control=a;
           var x=confirm("Do you want to Add Details?"); 
           if(a>=29 && x==true)
          {
                   //get the client Id of the hidden field and store the value of a in it.                document.getElementById('<%= inpHide.ClientID%>').value=control;
                // document.all("Button1").click();//to Call asp Button click event from javascript.          }
          else          {
            alert("Your age should be greater than 29");
           //to open a new web page you can use the following command.         //window.open("Pop.aspx","List","scrollable =no,resizeable=no,width=400,height=250");          }
        }
   </script>
</head>
<
body>    <form id="f1" runat="server">    <div>        <table width="45%">            <tr>                <td>                    <asp:Label ID="Label1" runat="server" Text="Enter Name :"></asp:Label></td>                <td>                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td>                    <asp:Label ID="Label2" runat="server" Text="Enter Age :"></asp:Label></td>                <td>                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>                    <asp:HiddenField ID="inpHide" runat="server" />                </td>            </tr>            <tr>                <td style="height: 26px">                    <asp:Label ID="Label3" runat="server" Text="Enter Salary :"></asp:Label></td>                <td style="height: 26px">                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>            </tr>            <tr>                <td align="center" colspan="2">                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" OnClientClick="ValidateAge()" /></td>            </tr>        </table>    </div>        <asp:GridView ID="GridView1" runat="server">        </asp:GridView>    </form></body>
</
html>
Default.aspx.cs
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 System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    string dbcon = ConfigurationManager.ConnectionStrings["AdvWorks"].ConnectionString;
    SqlConnection con;
    SqlDataAdapter da;
    DataSet ds;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
            FillGrid();
    }
    public void FillGrid()
    {
        con = new SqlConnection(dbcon);
        da = new SqlDataAdapter("Select * from emp", con);
        ds = new DataSet();
        da.Fill(ds, "Emp");
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds.Tables["Emp"].DefaultView;
            GridView1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValidAge", "ValidateAge()", true);        try        {
            int result = int.Parse(inpHide.Value);
            if (result>=25)
            {
                con = new SqlConnection(dbcon);
                cmd = new SqlCommand("Insert into Emp values('" + TextBox1.Text + "','" + TextBox2.Text + "','" +
TextBox3.Text + "')", con);
                con.Open();
                int rows = cmd.ExecuteNonQuery();
                if (rows > 0)
                {
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                    TextBox3.Text = "";
                    con.Close();
                    FillGrid();
                }
            }
        }
        catch (Exception e1)
        {
            con.Close();
        }
    }
}

Hope this will help you in your programming.

Microsoft Launches IE9 Mobile Test Drive Site

Web developers who want see how their sites will look on the new version of IE 9 Mobile, which will soon ship along with Windows Phone 'Mango,' the next-generation update to the Windows Phone mobile OS, now have a new tool to do so. Today, Microsoft has launched Mobile Test Drive, a companion to the Internet Explorer Test Drive site for the desktop. The new site features a number of HTML5 and performance demos highlighting IE 9 Mobile's capabilities.

Ie9 mobile test site
The mobile site is organized much like its desktop counterpart and includes may of the same samples in addition to several mobile-specific ones.
Over the next few months, even more samples will be added as we get closer to Mango's commercial release, says Microsoft. Mango is expected later this fall.
Currently, the first 15 samples on the new site include the following:

  • Audio Player (from MIX11)
  • Geolocation
  • Border Radius
  • DOM Local Storage
  • Scalable Vector Graphics
  • CSS3 Media Queries
  • DOMContentLoaded
  • FishIE Tank
  • Speed Reading (from MIX11)
  • Animated Text
  • HamsterDance Revolution
  • Business Charts
  • IE Logo
  • Video Panorama
  • Browser Control Theming