Archive for the '.Net' Category

Web Forms RegisterStartupScript Fails

I have been working on MVC for close to 4 years now and have been out of touch with Web Forms. In one of our product (web forms grrrrrrrrrrr) I had to help our my team who was facing a weird problem.

ClientScript.RegisterStartupScript block was not registering the javascript at all….We tried numerous methods (load, prerender etc) but it always failed. That is when my team mate found that the form tag is missing the runat=server and it worked!!!

So this if for people who are facing the exact same problem. Add the runat server to your form tag for your clientscript or startupscript to work.

Happy Programming!!!

Cheers,

Raja

Advertisements

Javascript – Getting URL Values

I found this nice function at Snipplr. This is a simple function but the thought behind such a simple function amazed me. I used to get the query string values using <% %> and adding the values to a hidden span. This is much more effective since it gets the values in name value pairs.


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
 var vars = [], hash;
 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

 for(var i = 0; i < hashes.length; i++)
 {
 hash = hashes[i].split('=');
 vars.push(hash[0]);
 vars[hash[0]] = hash[1];
 }

 return vars;
}

Hope this helps.

Happy Programming!!!

Cheers,

Raja

Automatic redirect upon session timeout – using Javascript

We had a requirement that the logged in user should be automatically logged out after 5 minutes of inactivity. We tried the session_end event in global.asax but it didnt work as it should have. After thinking a bit me and bryan came up with a simple solution using Javascript which works really nice.


var wintimeout;

function SetWinTimeout() {
 wintimeout = window.setTimeout("window.location.href='../weblogin/default.aspx';",300000); //after 5 mins i.e. 5 * 60 * 1000
 }
 $('body').click(function() {

window.clearTimeout(wintimeout); //when user clicks remove timeout and reset it

SetWinTimeout();

});
 SetWinTimeout();

That is it. Just put the above code in document load ($) and it works like a charm. Just 5 mins away from keyboard and monitor would do a world of good.

Hope this helps.

Happy Programming!!!

Cheers,

Raja

NetworkCredential in SMTP mail (Forms Authentication)

In the project I am currently working on we have to send email confirmation to the registered user giving them their User ID and Password (yup…..you saw that right password….not secured but that is the requirement :-(). we created a no-reply account and to our amazement all emails sent inside our domain were reaching fine but external domains were not. My hardware tech lead (Mihai) helped me out in checking exchange server(since I didnt have access to it). We saw that no mails to external domain was even queued in exchange. Then Mihai came up to me and asked me to check the credentials which was used for sending email and that was the missing piece :-). Prior to this application all our apps were windows authenticated so there was no need to specify the Network Credentials but in this app we have to use forms authentication since it is an internet site not an intranet site. So added the following line and it worked like charm 🙂


System.Net.NetworkCredential objAuthInfo = new NetworkCredential("<username>", "<password>");

objSMTP.Credentials = objAuthInfo;

Hope this helps.

Happy Programming!!!

Cheers,

Raja

ASP.Net Hybrid Authentication

We are working on a large .Net website that will have users both on and off of our domain.

  • We want to use the ASP.Net Membership framework
  • We want Windows authentication for people on our network
  • All users will be required to have an account (If a windows user on our domain does not have and account (A generic log on ‘kiosk01’) they should receive the Forms logon page
  • We do not want people with Windows accounts to be able to log on outside of our domain. (An employee here should not be able to log on as an employee from home)

This was actually very easy to setup.

First we setup the website. It should have two folders for authentication.

image

The WebLogin folder should take the default security setting from the websites web.config

image

As you can see we are using Forms authentication for the whole site and setting the logon URL to the WinLogin folder.

We create an HTML file (401-2.htm) containing a redirect to the WebLogin page. This will handle the 401-2 access denied error thrown when a user who can’t authenticate because the are off the domain or don’t have a ASP.Net account.

image

(You may want to do your redirect with aspx and code behind instead of html, if you don’t want to hard code the redirect address)

The ‘Weblogin/Default.aspx’ page should be a aspx page with a standard or customized Asp.Net Login control.

In IIS the site level authentication should be set like this…

image

 

Now for the WinLogin folder only, we set the Authentication like this…

image

Right click WinLogin and edit its properties alone

Now while still on WinLogin properties set a custom error HTTP Error 401;2 pointing to the 401-2.htm file created earlier.

image

 

Now all that is left is to write the code for the users who where able to Authenticate to the WinLogin page.

image

Add what ever custom logic you want for your windows authentications.

As you can see we don’t need to do anything with the password. If this code is executing then the user has Authenticated and we are calling the FormsAuthentication.RedirectFromLoginPage method with just the username and the createPersistantCookie boolean variable alone. The call to the RedirectFromLoginPage method  is also actually logging the user in. This confused me at first.

If the asp.net user account is not found (as in our generic log on ‘domain\kiosk01’) the user will be directed to the forms logon.

Now you can create asp.net membership accounts for the domain users assigning them roles etc. Just make sure the user name includes the domain and userid, ‘mydomain\j.user.01’ You can create a randomly generated password for the membership account preventing the domain user from logging in without the Windows authentication. (You would also have to have logic to prevent these users from resetting there password.)

And that’s it. The best of both worlds without making things to complicated.

-ctrlShiftBryan

Easy Dirty Checking with LINQ to SQL

dirtyDog

What is dirty checking?

Dirty checking is simply a way to check an object to see if it contains changes. This can be used to prevent unnecessary database updates. Properly implemented it should also account for the object changing back to its original state.

For example:

We change the spelling of a dog’s name “Spottie” to “Spotty". If we were to test the object it should return dirty.

Then if we decide the original spelling was correct and change it back to “Spottie” the object should no longer return dirty.

How we implemented it:

We wanted to extend our LINQtoSQL generated classes to implement dirty checking. All we had to do was extend the OnLoaded() method to call our copy constructor so that we had a private copy of the original object. Then we can simply check that private object against the current object state property by property to determine if the object was dirty.

partial class Dog
{
    private Dog _Original; 

    // Copy constructor.
    public Dog(Dog previous)
    {
        Name = previous.Name;
        Breed = previous.Breed;
        Age = previous.Age;
        Sex = previous.Sex;
        Weight = previous.Weight;
        Color = previous.Color; 
    } 

    //Here we copy the original object inside of itself for dirty checking
    partial void OnLoaded()
    {
        _Original = new Dog(this);
    } 

    //dirty checking using _Original from copy constructor
    public bool IsDirty
    {
        get
        {
            return
            !(
                this.Name == _Original.Name &&
                this.Breed == _Original.Breed &&
                this.Age == _Original.Age &&
                this.Sex == _Original.Sex &&
                this.Weight == _Original.Weight &&
                this.Color == _Original.Color 
            );
        }
    } 

}

-ctrlShiftBryan