2012-09-21

Automatically logged in on one site when logged in from another site

Have you ever encountered with a situation where you develop two separate websites in asp.net, using Forms authentication and once you logged in from a one website, your second website (Which runs completely separate from the first website) automatically logged in???

Well, that usually happens if you use the same name for the forms tag in web.config file

<authentication mode="Forms">
   <forms name="test" />
</authentication>

The name “test” is the cookie name used for the authentication. If it’s same for both websites, it’s likely sharing the same authentication cookie hence your second website automatically logged in the user when (s)he use the same browser.

What you have to do to get rid of this is, simply specify different names for the forms tag for each website.

Run a process as the admin of the server

Some programs require to run as administrator in order to work properly. We can use the Process class in asp.net to run a process in server. The below example code shows, how to pass credentials to start the process when we use the Process class to start a process.

string returnvalue = string.Empty;

ProcessStartInfo info = new ProcessStartInfo(fileName);
info.UseShellExecute = false;

info.Arguments = args;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;

string passwordStr = "PasswordHere";

SecureString password = new SecureString();

foreach (char c in passwordStr)
   password.AppendChar(c);

info.Password = password;
info.UserName = "Administrator";

using (Process process = Process.Start(info))
{
     StreamReader sr = process.StandardOutput;
     returnvalue = sr.ReadToEnd();
}

We have to pass the Password as a SecureString. So, first we have to convert the string value to a SecureString by passing each character through a loop and append each to the SecureString. ProcessStartInfo class has the properties “UserName” and “Password” which we are setting to start the process with the given credentials.

2012-09-20

Highlight a date range in asp:Calender

Sometimes we need to highlight a selected date range in asp:Calender control. Here is how it’s done.

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!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 id="Head1" runat="server">

</head>
<body>
    <form id="form1" runat="server">
    <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
    </form>
</body>
</html>

We get the difference as a TimeSpan and highlight the dates one by one by going through a loop. In this example I’m highlighting the dates from 2012/08/11 to today’s date.

Code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DateTime startDate = Convert.ToDateTime("2012/08/11");
            DateTime endDate = DateTime.Now;
            TimeSpan difference = endDate.Date - startDate.Date;

            Calendar1.SelectedDates.Clear(); //Clear previously selected dates, if any
            for (int i = 0; i <= difference.Days; i++)
                Calendar1.SelectedDates.Add(startDate.AddDays(i)); //Highlight the dates
        }
    }
}

Use AJAX ModalPopup to block the UI while a postback

It’s a nice user experience if we can display a “Please wait” or a “Loading..” message while our website is processing the user request or a file upload etc. It’s even nicer if we can prevent the user from using website until the postback finishes. We can make use of ModalPopupExtender in the AJAX toolkit for achieve this kind of thing. Following is a short example for this. To make it simpler, I will include only the relevant parts of the code.

ASPX code snippet.

<asp:Button runat="server" Text="Send" CssClass="input-button"
OnClick="btn_Click" Width="167px" OnClientClick="showProgress();" />

<ajaxToolkit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="pnlPopup"
PopupControlID="pnlPopup" BackgroundCssClass="modalBackground" />
    <asp:Panel ID="pnlPopup" runat="server" CssClass="updateProgress">
        <div id="imageDiv">
            <div style="float: left; margin: 9px">
                <img src="Resources/Images/ajax-loader.gif" width="32px" height="32px" /></div>
            <div style="padding-top: 17.5px; font-family: Arial,Helvetica,sans-serif; font-size: 12px;">
                Sending file. Please wait...
            </div>
        </div>
    </asp:Panel>

And the jQuery would be like this

<script type="text/javascript">
    function showProgress() {
        $find('mdlPopup').show();
    }
</script>

On the button click, I’m calling the showProgress() method which shows the ModalPopupExtender. Since I’m calling it OnClientClick event, it fires the modalpopup just before a postback occurs.

We can define the CSS class for the Background from the BackgroundCssClass property of the ajaxToolkit:ModalPopupExtender. Usually we use a grayed out background and make it transparent to show that UI is blocked. We can use the below CSS class for that.

.modalBackground
{
    background-color: Gray;
    filter: alpha(opacity=60);
    opacity: 0.60;
}

The asp:Panel is the part where we show the loading message and the activity indicator. I used a simple gif image here and a text saying “Sending file. Please wait…”. To make that part prominent from the popup background, I’ve applied a different background color for the panel. Following is the CSS class for that

.updateProgress
{
    border-width: 5px;
    border-style: solid;
    background-color: #FFFFFF;
    position: absolute;
    height: 50px;
    width: 290px;
}

Once the postback finished, the page is reloading so the ModalPopup will again reset to it’s initial state (hidden).

Get name of the user account which the website runs under in the server

When you host your website in IIS, it runs under a different user account. It’s not the same account as you host it. To get the user account name which the website runs under, we can use the below code.

Response.Write(WindowsIdentity.GetCurrent().Name);

We have to import the below namespace in order to use the above code

using System.Security.Principal;

C# and PHP database connection code comparison

Here, I’m trying to provide the equivalent DB connectivity code in C# and PHP. Let’s say the PHP code is as below,

<?php

mysql_connect('server.url.goes.here.com', 'username_goes_here', 'password_goes_here');
mysql_select_db('db_name_goes_here');

$q = 'SELECT * FROM myTable';
$r = mysql_query($q);

while (mysql_fetch_object($r)) {
        // do stuff
}

?>

The equivalent C# code would be like below

SqlConnection connection;
SqlDataReader r;

try
{
string connectionString = @ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();
string q = "SELECT * FROM myTable";

SqlCommand sqlComm = new SqlCommand(q, connection);
r = sqlComm.ExecuteReader();

while (r.Read()) {
    //do stuff
}
}
catch(Exception)
{}
finally
{
  r.Close();
  connection.Close();
}

To make it easier to understand, I will take chunk by chunk from the code of both languages and try to explain.

 

PHP code:

mysql_connect('server.url.goes.here.com', 'username_goes_here', 'password_goes_here');
mysql_select_db('db_name_goes_here');

C# code:

SqlConnection connection;

string connectionString = @ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();

In asp.net, Username and Password for the Database server, IP address/URL for the database sever and DB name are storing in the web.config file under connectionStrings section.

 

PHP code:

$q = 'SELECT * FROM myTable';

C# code:

string q = "SELECT * FROM myTable";

That’s how actually we declare variables in those languages. There is no relevant for DB. Above shows just how we store the strings in both languages.

 

PHP code:

$r = mysql_query($q);

C# code:

SqlCommand sqlComm = new SqlCommand(q, connection);
SqlDataReader r = sqlComm.ExecuteReader();

That’s how we execute the SQL query and store the result in a reader object. In C#, we use SqlDataReader object. In PHP we can directly execute the string representation of the SQL query. In C#, we have to build a SqlCommand object from the string representation of the SQL query.

 

PHP code:

while (mysql_fetch_object($r)) {
        // do stuff
}

C# code:

while (r.Read()) {
    //do stuff
}

That’s how we read the data from the reader objects.

Set SkinID for a Custom Controller

SkinID property should set in or before the Page_PreInit event for static controls. Since Custom Controller is written within a class, not a page, there are no page events available to set the SkinID. So, to set the SkinID property for a Custom Controller, you have to override it in the implementation of the custom controller class as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.Adapters;

namespace WebApplication2
{
    [ToolboxData("<{0}:Class1 runat=\"server\"  SkinID=\"Skin1\"> </{0}:Class1>")]
    public class Class1 : Label
    {
       public override string SkinID
       {
           get
           {
               return "Skin2";
           }
           set
           {
               base.SkinID = value;
           }
       }

        protected override void Render(HtmlTextWriter writer)
        {
            Text = this.HeaderText;
            base.Render(writer);
        }

        [Bindable(true)]
        public String HeaderText
        {
            get
            {
                return (string)this.ViewState["HeaderText"] ?? String.Empty;
            }
            set
            {
                this.ViewState["HeaderText"] = value;
            }
        }
    }
}

I’m inheriting this custom controller from asp:Label class.

Skin file should be like below. Note that SkinID for the custom controller in this skin file is same as what I’ve returned in the class, when override the SkinID property. Since the skin file does not recognize the Custom Controller, we have to register it first using Register directive.

<%@ Register Assembly="WebApplication2" Namespace="WebApplication2" TagPrefix="cc2" %>
<cc2:Class1 runat="server" BackColor="Red"  ForeColor="White"  Font-Name="Arial"  Font-Size="9px" SkinID="Skin2" />

Now you can test it with the below ASPX code

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="WebApplication1.About" %>

<%@ Register Assembly="WebApplication2" Namespace="WebApplication2" TagPrefix="cc2" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <cc2:Class1 ID="Class1" runat="server" HeaderText="Ruchira Gamage"> </cc2:Class1>
</asp:Content>