Blogger Widgets
  • Sharing Photos using SignalR
  • TFS Extenstion - allows copy work items between projects
  • Displaying jquery progressbar with ajax call on a modal dialog
  • Managing windows services of a server via a website
  • Exploring technologies available to date. TechCipher is one place that any professional would like to visit, either to get an overview or to have better understanding.

Search This Blog

Wednesday, 22 December 2010

Enable HTTPS for a Website using IIS

Testing your website with HTTPS might be one of the customer requirement. IIS allows you to create a dummy SSL that enables you to test the website using HTTPS. So Now to enable HTTPS follow below steps :

[First lets create a certificate]
1. Goto IIS -> select the machine name
2. Now from features select "Server Certificates"
3. select "Create Self-Signed Certificate" and specify the name "DummyCertificate"
4. Now this should get displayed in the list of certificates

[Now lets associate the certificate to websites]
5. Goto IIS -> Select "Default Web Site"
6. Under "Actions" select "Bindings"
7. Now select "Add", select type as "https" and select the certificate as "DummyCertificate"
8. Now "ok" the message and "close" the site bindings. This should display the bingings to https as shown below:-

9. Now select the site and from features select "SSL Settings". Update as below:

10. Select "Apply" and your website is enabled with https. Now publish with https.



“Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.”
(Eric Raymond)

Monday, 20 December 2010

Width 100% not working in IE compatibility mode

At time its so frustrating to get css styles work correctly in various circumstances such as cross-browser , IE compatibility mode etc.

Recently notice an issue which is setting width 100% does not work in IE compatibility mode. The page display a input:select and input:textbox. It works fine in various places but was having issue at one particular table.

After trying out various options and finally the option that worked is

 td style="width:100%;"

So be very careful with this sort of issues, as these are very minor but becomes so frustrating at times.


Hardware: the parts of a computer that can be kicked. ~Jeff Pesis

Friday, 17 December 2010

Format date based on client time zone using javascript and ASP.NET AJAX

At time you might want to format date based on the client's browser configuration of language. If you are using ASP.NET AJAX then you will have the provision of using Sys namespace.

Here is a sample snippet that show how to use it :-

function ToClientFormat(ClientDate) {
    var dt = new Date(ClientDate);
    return dt.localeFormat(Sys.CultureInfo.CurrentCulture.dateTimeFormat.FullDateTimePattern);
}


Now this will display the date as

Friday, December 10, 2010 11:07:05 AM


As shown you will be able to use Sys.CultureInfo.CurrentCulture.dateTimeFormat to get which ever the format you were interested in, refer to MSDN for more details Sys.CultureInfo.dateTimeFormat


“Make everything as simple as possible, but not simpler.”
– Albert Einstein

Monday, 13 December 2010

Change default browser running VS2010

At times we might have to test various things for cross-browser compatibility as part of validation. But if you want to default your visual studio to run the web application in a specific browser then follow these steps :-

1. Select the page you want to view in Visual Studio
2. Now right click on the file and select "Browse With", the following dialogue box will be displayed.
3. Select the browser and click on "Set as Default" for defaulting visual studio to that specific browser.


“It’s OK to figure out murder mysteries, but you shouldn’t need to figure out code. You should be able to read it.”
– Steve McConnell

Thursday, 2 December 2010

Adding custom buttons to jquery datepicker showButtonPanel

JQuery solves most the requirements of date with the datepicker. Ok now, to add some extra functionality for datepicker such as providing some custom buttons in the buttonpanel after enabling it via "showButtonPanel : true".

Here is a snippet of code that should do the trick:-

$("#datepicker2").datepicker({
 showButtonPanel: true,
      beforeShow: function( input ) {
 setTimeout(function() {
   var buttonPane = $( input )
     .datepicker( "widget" )
     .find( ".ui-datepicker-buttonpane" );

   var btn = $('');
   btn
    .unbind("click")
   .bind("click", function () {
    $.datepicker._clearDate( input );
  });

   btn.appendTo( buttonPane );

 }, 1 );
      }
});

with the html as

Date: 

should display the datepicker with clear option as:-



“From a programmer’s point of view, the user is a peripheral that types when you issue a read request.”
– P. Williams

Tuesday, 30 November 2010

CSS Cursor as pointer not working

Working on website development for quite a bit now. Just had come across a style sheet issue in a web page. With the following style sheet:-

.linkbtn
{
    cursor:pointer;
    text-decoration: underline;
}

What would anyone expect for this simple html as :

Find

Certainly to show a different cursor when user hovers on the text. Yes it works on IE !! but not on firefox & chrome.

Ok lets debug and see what's happening, the css does show only

.linkbtn
{
    text-decoration: underline;
}

Does'nt make sense at all. does it ? Ok Now I have modifed the html to :

Find

Hurray ! it worked by just re-arranging the class & id attribute.

Three things are certain:
Death, taxes, and lost data.
Guess which has occurred.
~David Dixon, 1998, winning entry of the Haiku Error Messages 21st Challenge by Charlie Varon and Jim Rosenau, sponsored by Salon.com

Tuesday, 23 November 2010

Filename validation in VC++

Validating files names should not be very difficult, Is it? . Yes, it is if you trying to do in VC++. Here is a small snippet of code that helps :-

CString fileName = "test:11";
for (int i = 0; i < fileName.GetLength(); i++)
{
 if (!(PathGetCharType(fileName[i]) & GCT_LFNCHAR)) 
 {
  bValid = FALSE;
  break;
 }
}
Do not forget to include "Shlwapi.h"

“If people never did silly things, nothing intelligent would ever get done.”
– Ludwig Wittgenstein

Friday, 12 November 2010

Display progress bar inside JQGrid

Considered displaying a JQuery progress bar inside JQGrid. Here is a small example how this can be achieved.

Consider the json data returned by a web service is as follows:-

{  
"page":"1",  
"total":1,  
"records":"5",  
"rows":[  
{"id":"1","cell":["1","Scott","US","
10
"]}, {"id":"2","cell":["2","Charles","UK","
20
"]}, {"id":"3","cell":["3","Dan","Astralia","
30
"]}, {"id":"4","cell":["4","Chris","Canada","
25
"]}, {"id":"5","cell":["5","Paul","China","
80
"]} ]}

Here is the script that would achieve the results

jQuery("#grid").jqGrid({  
 url:'GetDetails.asmx?team=All',  
 datatype: "json",  
 colNames:['ID','Name','Country','Progress'],  
 colModel:[  
 {name:'id',index:'id', width:55},  
 {name:'Icon',index:'Icon', width:90},  
 {name:'name',index:'name asc, invdate', width:100},  
 {name:'designation',index:'designation', width:80}],  
 rowNum:10,  
 rowList:[10,20,30],  
 pager: '#pager',  
 sortname: 'id',  
 viewrecords: true,  
 sortorder: "desc",  
 caption:"JSON Data"  
}); 

$('div.progBar').each(function(index) {
    var progVal = eval($(this).text());
    $(this).text('');
    $(this).progressbar({
  value: progVal
 });

});

JQGrid would display the required results and once done update the JQGrid cell data with the progress bar required.



“In a room full of top software designers, if two agree on the same thing, that’s a majority.”
– Bill Curtis

Thursday, 11 November 2010

Display Icons in JQGrid

JQGrid is one of the best plug-in to display data as grid. Using JQGrid is very simple and easy to use. In this article we will look into displaying icons in JQGrid.

Consider the following code that makes an ajax call:

jQuery("#grid").jqGrid({
  url:'GetDetails.asmx?team=All',
 datatype: "json",
    colNames:['ID','Team', 'Name', 'Designation'],
    colModel:[
     {name:'id',index:'id', width:55},
     {name:'Icon',index:'Icon', width:90},
     {name:'name',index:'name asc, invdate', width:100},
     {name:'designation',index:'designation', width:80}],
    rowNum:10,
    rowList:[10,20,30],
    pager: '#pager',
    sortname: 'id',
    viewrecords: true,
    sortorder: "desc",
    caption:"JSON Data"
});

The return data from the GetDetails.asmx should be in json format and the data should look like :-

{
"page":"1",
"total":1,
"records":"5",
"rows":[
{"id":"1","cell":["1","","Scott","Manager"]},
{"id":"2","cell":["2","","Charles","Accountant"]},
{"id":"3","cell":["3","","Dan","Sales"]},
{"id":"4","cell":["4","","Chris","Administrator"]},
{"id":"5","cell":["5","","Paul","Developer"]}
]}

The data cell value should contain an image location so that JQGrid will render and display an image in the grid.

“Tell me and I forget. Teach me and I remember. Involve me and I learn.”
– Benjamin Franklin

Wednesday, 10 November 2010

Getting 401 Unauthorized error consistently with jquery call to webmethod

ASP.NET with JQuery provides a flexible method of making ajax calls via a webservice. Making an ajax call using JQuery API would be as simple as

 $.ajax({
            url: "TestService.asmx/Test",
            data: "{'JSONData':'" + JSON.stringify(id) + "'}", // For empty input data use "{}",
            dataType: "json",
            type: "POST",
            contentType: "application/json",
            complete: function (jsondata, stat) {
                if (stat == "success") {
                    var response = JSON.parse(jsondata.responseText).d;
                    $("#divItem").html(response);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {

            }
        });

Now the webservice method definition should look like:-

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Test(string JSONData)
{
   return JSONData + " Test Data";
}

Now that we have the code ready, lets try to run this. Oh No!! ASP.NET bounced back with following error.

"401 Unauthorized"

This internally means JQuery Ajax call had responded as System.InvalidOperationException and hence that would be thrown as 401 Unauthorized exception.

The simple solution is to include the following line before the class definition of the webservice

[System.Web.Script.Services.ScriptService]


“Real knowledge is to know the extent of one’s ignorance.”
– Confucius

Monday, 1 November 2010

Unable to debug published ASP.NET website

Have been struggling to debug ASP.NET application but had no success what so ever. For time being drop the thought of publishing the website using Visual Studio (2005/2008/2010).

Lets start with the Manual process :-

1. Create a folder under C:\inetpub\wwwroot for eg: MyWebsite
2. Goto IIS, right click on Default Website -> Select Add application
3. Specify Alias, select location, select the required application pool and select OK
4. Now goto Visual Studio, right click on the website -> Publish
5. Go back to IIS and select the application created "MyWebsite"
6. double click on Authentication
7. Now select the following:-
- Anonymous (Enabled),
- Impersonation (Disabled),
- Basic (Disabled),
- Digest (Disabled),
- Forms (Enabled)
- Windows (Disabled)
Note: Assuming web.config is configured to use forms authentication
8. Restart default website.

All of this seems quite easy and looks very familiar. But a small mistake in configuring correct authentication might lead to frustrating situations.


The more you know, the more you realize you know nothing.
– Socrates

Server.GetLastError() giving error as 'File does not exist.'

In general Server.GetLastError() is the more used way of getting the last generated error. But have you ever got an error message and does not exactly know what went wrong. Such as the error below:-

{"File does not exist."}

which has actually occurred in the source code at

protected void Application_Error(Object sender, EventArgs e)
{
    HttpException Error = Server.GetLastError() as HttpException;
    Session["Error"] = Error;
    Response.Redirect("Error.aspx", true);
}


The error by itself is self explanatory that says a file is missing and might be because of an .aspx, .gif, .js file missing or does not have permission to read the file.

Well finding the cause for this might look daunting when you see it. But its very simple, just follow these steps :-

1. Set a breakpoint at the Server.GetLastError()
2. Now open quickwatch
3. Type Request.CurrentExecutionFilePath

this should give the file that is missing. Also this might generally occur at places such as binding a data grids where an image is bound to a column.

The first rule of intelligent tinkering is to keep all the pieces. -Aldo Leopold

Tuesday, 26 October 2010

Invalid postback or callback argument on Post back

One of the most familiar error while working on ASP.NET ajax update panels is :-

505|error|500|Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.



Well its not quite easy and literally its frustrating to find out the cause. Everything is working fine in IE but not on firefox, chrome etc. So what went wrong is something very simple no one would expect.

Loading a webpage that contains number of user controls and one of which has a dropdown. The dropdown is binded to an array of strings. Now who would expect binding a string array to drop down would go wrong, no one but it does go wrong.

One of the string has a "\r" character which was messing the complete postback. Some how this is handled in IE but not on other browsers.

Any way after investing so much and finding so little to fix was a relief.

It has become appallingly obvious that our technology has exceeded our humanity.

~Albert Einstein

Friday, 22 October 2010

Updating contents of IFrame using JQuery

Now a new challenge !!!

Updating the contents of iframe using jquery, sounds easy as jquery by default provides the option as follows:-

$("#iframe1").contents()

Now that you are able to retrieve the contents, updating data is quite easy. for eg:-

$("#iframe1").contents().find("#mydiv").css("background-color","red");

In order to update the contents of #mydiv in iframe1 first iframe1 should be loaded with another page. Its all seems fine now. Ok but the hard bit is
- No default src provided
- replace the content of iframe completely not just some specific elements

Why not just use standard html method provided by jquery as

$("#iframe1").contents().html('

Test

);

Yes its easy, but no it does not work. Just a small change to make this work.

$("#iframe1").contents().find('html').html('

Test

');

Also another advantage of this is jquery extenstions or plugins work just as easy. For example using highlight plug-in would be

$('#iframe1').contents().find('html').highlight('test');
  $('#iframe1').contents().find('html').find('.highlight').css('background-color', 'yellow');

Hope this should have save some of your time.

The first rule of intelligent tinkering is to keep all the pieces.

Aldo Leopold

Tuesday, 19 October 2010

LoadViewState not firing on post back in custom control

Recently started developing a custom control with complex data handling. So far so good. Now lets try adding view state content to the custom control. Oh no! its not working. What's wrong is there a design flaw or some thing overlooked.

Have been struggling for quite a decent number of hours to fix this. After revisiting the code and looking into event life cycle for ASP.NET .

Ha ha ... yes overlooked a basic detail but have given me a severe headache. Never load any custom control in Page_Load but load them in OnPreInit.

Instead of loading

    protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack)
       {
       }
    }

load the controls in

    protected override void OnPreInit(EventArgs e)
    {
       if (!Page.IsPostBack)
       {
       }
    }

This very detail can be more daunting after the design had become more complicated.

To err is human, but to really foul things up requires a computer. ~Farmer's Almanac, 1978

Tuesday, 28 September 2010

Displaying jquery progressbar with ajax call on a modal dialog

Working on a website of which one of the requirement is to display a progress bar while completing an ajax call. Yes this is a simple and straight forward requirement and lets look to the details of how to implement it.

1. Create a web service

2. Using jQuery do the following :-
2.1 Show modal dialog box
2.2 show progress bar on the modal dialog box as 0% completed
2.3 Make an ajax call (estimated time of 5 mins)
3. While ajax call is processing make another ajax call to the web service to find the percentage completed and do this using set interval (or) using jquery count down plugin

Now that we have the design aspect, lets start implementing this.

At first an ajax call (ProcessRequest() - webservice method) is made and after 10 secs another ajax call ProcessStatus() - webservice method) is made to retrieve the percentage completed.

AjaxWebService.asmx
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ProcessRequest()
{
   return AjaxData.AjaxProcess();
}

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int ProcessStatus()
{
   return AjaxData.AjaxStatus();
}


AjaxData.cs
public class AjaxData
{
    private static int status = 0;

 public AjaxData()
 {
        status = 0;
 }

    public static string AjaxProcess()
    {
        string retValue = "Started";
        status = 0;
        for(int i=1;i<=100;i++)
        {
            System.Threading.Thread.Sleep(100);
            status++;
        }

        retValue = "Completed Successfully !";
        return retValue;
    }

    public static int AjaxStatus()
    {
        return status;
    }

}
default.aspx (script)

The complete project source code is available on Codeplex

“Physics is the universe’s operating system.” – Steven R Garman

Monday, 13 September 2010

Unable to uninstall: assembly is required by one or more applications

Un-installing from GAC can be done in various methods such as :-

1. Using windows explorer goto C:\Windows\assembly
2. Locate the assembly
3. use delete button (or) right click -> Uninstall

Alternate method is

1. Goto Visual Studio Command prompt
2. type gacutil /u Me.Test.Assembly

If both of these doesn't work then the assembly is used by some of the component. Ok now that you have known that assembly has a dependency but still you want to delete. This might occur in a scenario where in you want to update the assembly with the new version not by having side by side but having only latest version. This can be achieved by clearing some of the entries in the registry. The entry for the assembly can be in one of these two locations:-


HKEY_CURRENT_USER\Software\Microsoft\Installer\Assemblies\Global
(or)
HKEY_LOCAL_MACHINE\Software\Classes\Installer\Assemblies\Global


Locate the entry related to your assembly and delete it, this should remove the dependency. Now just go and uninstall from GAC using either of the two methods above.


The Internet is a minefield of opportunity. Step carefully, or another opportunity will go off right in your face
- Russell Davies

Tuesday, 7 September 2010

Sys._ScriptLoader is null or not an object

Working on a website and have got following error :-

"Sys._ScriptLoader is null or not an object"

Have been using the methodology of downloading multiple javascript files after the visible content. When combine script is enabled the above error is displayed.

The reason for this error being the definition of the following function :-

$type = Sys._ScriptLoader = function _ScriptLoader() {

has not been loaded so need to exclude respective scriptResource.axd during combine scripts mode. Hope this might help to fix some of the issues.

“Real knowledge is to know the extent of one’s ignorance.”
– Confucius

Thursday, 2 September 2010

Unable to get readonly textbox value from server side ASP.NET

Unable to get textbox value from server side is not a bug in ASP.NET but is a feature. Textbox value cannot be read from code behind if it is readonly as per MSDN .

But the value can be read using the following syntax :

txtFirstName.Text = Request[txtFirstName.UniqueID];


“The greatest enemy of knowledge is not ignorance, it is the illusion of knowledge.”
– Stephen Hawking

Thursday, 26 August 2010

"Response.Redirect" or "Server.Transfer" raises ThreadAbortException

Both methods calls Response.End method internally ends the page execution. Then executes Application_EndRequest event in the application's event pipeline and hence the line of code that follows Response.End is not executed which is raising the exception.

To overcome this just disable Response.End in both methods as follows :-

Server.Transfer(Request.FilePath);
Response.Redirect(Request.FilePath);

to

Server.Execute(Request.FilePath);
Response.Redirect(Request.FilePath,false);

Computers are composed of nothing more than logic gates stretched out to the horizon in a vast numerical irrigation system.


Stan Augarten

Monday, 16 August 2010

Ajax Control Toolkit 3.5 : The script 'Timer.js' has been referenced multiple times.

Developed a website using Fast ASP.NET Web page loading by downloading multiple JavaScripts after visible content and in batch using .NET 2.0, Ajax 1.0 and Ajax Control toolkit. After migrated to .NET 3.5 getting the following error:-

"Microsoft JScript runtime error: Sys.InvalidOperationException: The script 'Timer.js' has been referenced multiple times. If referencing Microsoft AJAX scripts explicitly, set the MicrosoftAjaxMode property of the ScriptManager to Explicit."

As per the methodology used to delay loading of JavaScripts after visible content, all resource files(.axd) should be included in Filesets.xml.

Now find out where the error has occured in the script reference for eg:
ScriptResource.axd?d=PG8nyU-48dBLIokilQnXoklX6EpGEQ3aTy3vcRWmvg0DcIYhtPYFxJ8hwJRjuu3W0&t=ffffffffd40de07f

comment out the script resource in the xml. Timer control should not be included as part of combine scripts and hence the respective script resource should be commented.

Also to view any resource file that has been included in the xml just open the resource in Visual Studio (File -> Open when website is running) . for eg: if the location is

ScriptResource.axd?d=PG8nyU-48dBLIokilQnXoklX6EpGEQ3aTy3vcRWmvg0DcIYhtPYFxJ8hwJRjuu3W0&t=ffffffffd40de07f

the url for this would be

http://localhost:49405/WebSiteOne/ScriptResource.axd?d=PG8nyU-48dBLIokilQnXoiLgocTATYIx-0XXTsaGMX5FZyBIBPiYYV8fYhHJhy9o0&t=ffffffffd40de07f


Computers can figure out all kinds of problems, except the things in the world that just don't add up.
James Magary

Migrating Web application from .NET 2.0 with Ajax 1.0 to .NET 3.5

Migrating a web application developed in .NET 2.0, Ajax 1.0 and Ajax control tool kit 2005 to .NET 3.5 is quite simple following below steps :-

1. Open the solution using Visual Studio 2008 (this is migrate automatically all the projects in the solution and will update the references accordingly.

2. Remove the reference to Ajax control toolkit 2.0 and add the new reference to ajax control toolkit 3.5.

3. Since Ajax control toolkit is being used in your solution update tag to .

4. To improve performance load all .js file using a single user control and assign attribute CombineScripts attribute of scripmanager to "True". Reference CombineScripts.

5. Build the solution and web application should work absolutely fine.

To err is human, but to really foul things up requires a computer.

-Farmers' Almanac, 1978

Tuesday, 6 July 2010

.NET VC++ Compilation in x64

Compiling VC++ projects for x64 build might give following errors :-

eg:-
fatal error LNK1181: cannot open input file 'version.lib'

So as to fix the issues library directories should point to 64bit libraries and also 64bit SDK needs to be installed.

To install 64-bit SDK :-

http://www.microsoft.com/downloads/details.aspx?FamilyID=c17ba869-9671-4330-a63e-1fd44e0e2505&displaylang=en

“The more you know, the more you realize you know nothing.”
– Socrates

Saturday, 3 July 2010

Unable to get updated project from source control

At times while getting project from source control the following message is displayed :-



Follow the steps below :
1. Source Control - Get specific version
2. select option "Force get of file versions already in workspace"
3. select "Get"

This should override your files, but if the files are not retrieved using this method then the issue is with your source control binding.

Follow the steps below :
1. goto Source Control explorer
2. select workspace and select workspaces (this will display "Manage Workspaces" dialog)
3. Now select the binding and select "Edit"
4. Under the working folders list, remove bindings that are not required

Note: Binding only to the root is required and any sub folder bindings can be removed.

“Standards are always out of date. That’s what makes them standards.”
– Alan Bennett

Friday, 2 July 2010

Type Sys.UI._Timer has already been registered

Having a webpage with multiple update panels and multiple timers might be bit annoying when you the below error:-
Sys.InvalidOperationException: Type Sys.UI._Timer has already been registered

If scripts are loaded using an user control update attributes for asp:ScriptManager as follows
  


















Hope this have helped someone like me hanging around.

"It’s hardware that makes a machine fast. It’s software that makes a fast machine slow."
- Craig Bruce

VS 2005 - VC++ Include directories invalid for $(VCInstallDir)

At times if Visual studio 2005 doesn't recognize $(VCInstallDir) paths, static paths might be a better option.

select the include & library directories manually as below :




and





The computer was born to solve problems that did not exist before.


– Bill Gates

Thursday, 1 July 2010

Displaying elapsed time with multiple asp:timer's on a page

In cases where a web page consists of multiple asp:updatepanel and multiple asp:timer controls. Each update panel getting refreshed at specific timer intervals (different timings), instead of display stale data before the refresh its good to display the user with elapsed time for an update panel. This gives users feel of live data and user knows exactly when an update panel will be refreshed.

Sample display of how the page looks



Here is the code below :-
TimerWidget





























code-behind

contd...

Corrupted Visual Studio 2005 settings for VC++ directories

To reset to default setting of VC++ directories follow below steps :-

1. Tools -> Import and Export settings



Fig 1

2. select "Export selected environment settings" and select "Next"
3. select "All settings" and select "Next"
4. select "Finish"

This should give the default settings and if any thirdparty libraries are used manually add the include directories.

Technology is a way of organizing the universe so that man doesn't have to experience it.

Max Frisch

Wednesday, 30 June 2010

ASP.NET - Handling Impersonation failures of web.config

Impersonation is possible in number of ways. One of the most common method is to to store encrypted user credentials in registry. Configure web.config to pickup the credentials for authentication as below :-

Use encrypted attributes in the configuration file web.config

So far so good, now consider if the user credentials have failed the following error is displayed




The following section should allow you to display a custom error page:-


<customErrors mode="RemoteOnly" defaultRedirect="GeneralError.aspx"/>


this will work only after the user is authorised and a session is created for the user.

Hence in order to display custom error page for invalid user credentials from web.config, error handling for login credentials should be handled in Global.asax as below :-


void Session_Start(object sender, EventArgs e)
{
if (!Impersonate.ImpersonateUser())
Response.Redirect("GeneralError.aspx",true);

}


Now the code for ImpersonateUser()

///
/// Summary description for Impersonate
///

public class Impersonate
{
// Declare signatures for Win32 LogonUser and CloseHandle APIs
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string principal,
string authority,
string password,
LogonSessionType logonType,
LogonProvider logonProvider,
out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonSessionType : uint
{
Interactive = 2,
Network,
Batch,
Service,
NetworkCleartext = 8,
NewCredentials
}
enum LogonProvider : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}


public Impersonate()
{
//
// TODO: Add constructor logic here
//
}

public static bool ImpersonateUser()
{
bool bRet = false;
IntPtr token = IntPtr.Zero;
WindowsImpersonationContext impersonatedUser = null;
try
{
// Create a token for DomainName\Bob
// Note: Credentials should be encrypted in configuration file
string user = ConfigurationManager.AppSettings["userid"];
string domain = ConfigurationManager.AppSettings["domain"];
string pass = ConfigurationManager.AppSettings["password"];
bool result = LogonUser(user, domain,
pass,
LogonSessionType.Network,
LogonProvider.Default,
out token);
if (result)
{
WindowsIdentity id = new WindowsIdentity(token);

// Begin impersonation
impersonatedUser = id.Impersonate();
bRet = true;
}
}
catch(Exception ex)
{
string err = ex.Message;
// Prevent any exceptions that occur while the thread is
// impersonating from propagating
}
return bRet;
}
}



Hence user authentication is performed in session_start and allows to redirect to custom error page for unauthorised access.

"Many of the great achievements of the world were accomplished by tired and discouraged men who kept on working."

Monday, 28 June 2010

Issue with user control getting loaded with asp:timer

I have been working on a web application which requires loading a user control using asp:timer control. Application is completely based on widgets.

The default page has number of widgets that are loaded dynamically at runtime and all widgets has the facility to enable or disable timer.

All events were working fine except "User Widget" not firing any events. Here is how the code is :-

WidgetTimer.ascx















UserControl.ascx


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="DataListMgrReal.ascx.cs" Inherits="DataListMgrReal"%>










Select Repository






PageSize="25"
AutoGenerateColumns="false"
GridLines="None"
CssClass="gridViewData"
Height="159px">











I have been struggling to find the issue. Then i have tried creating a new web app and have tried with just the above snippet and that works fine.

After some modifications the btnUpdate_Click stated working but only works for the second click.

i have come accross the following articles...

http://forums.asp.net/t/1079709.aspx


http://bytes.com/topic/net/answers/730873-ajax-updatepanel-dynamic-controls-registerstartupscript-click-twice

Application was so complicated so the only detail that has skipped out of my mind is "UserControl" ID property.

I am not assigning ID property manually which has been causing the issue all the time. I have finally fixed the issue now its a relief......

Hope this might be helpful for someone like me with this odd combination.

Never overlook a minute detail !!!
Copyright © 2013 Template Doctor . Designed by Malith Madushanka - Cool Blogger Tutorials | Code by CBT | Images by by HQ Wallpapers