Blog Archives

IIS6 Change Framework Version without restart of W3SVC service

browse to the location of the folder containing the version of asp_net regiis such as:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

run aspnet_regiis -lk to get the virtual path you will need in the next command. to see which ID matches your website launch IIS manager and under websites you will see a column called “identifier”.

run the command:
aspnet_regiis.exe -norestart -s “W3SVC\1398789133”

done.

Advertisement

ie10 imagebutton _dopostback undefined bug with update panel script manager

IE10 has a nice new little bug which occurs with image buttons on 2nd or consecutive postback on a page which contains an update panel.

You will notice the bug as a broad javascript error message, but behind the scenes the issue occurs due to a bad type conversion to an integer from a floating point which has started to return from the .Net functions.

The official fix is a patch from Microsoft for your server, however, in the meantime you can simply apply the following in your global.asax.

Scott Hanselman has suggested a few things regarding this issue, but I think you will find the solution below to be more straightforward in the short term.

See solution below. (courtesy of R. Prestol)

vb:

'put these in global.asax.cs
Protected Sub Application_PostMapRequestHandler(sender As Object, e As System.EventArgs)
        Dim app As HttpApplication = sender
        Dim handler As IHttpHandler = app.Context.Handler
        Dim page As Page = IIf(TypeOf handler Is Page, handler, Nothing)
        If (page IsNot Nothing) Then
            AddHandler page.Load, AddressOf Page_LoadFix
        End If
    End Sub

    Private Sub Page_LoadFix(sender As Object, e As EventArgs)
        Dim page As Page = HttpContext.Current.Handler
        Dim smg As ScriptManager = ScriptManager.GetCurrent(page)
        If smg IsNot Nothing AndAlso (page.IsPostBack = False OrElse smg.IsInAsyncPostBack = False) Then
            ScriptManager.RegisterOnSubmitStatement(page, page.GetType, "IE10ImgFloatFix", "IE10ImgFloatFix();")
            ScriptManager.RegisterStartupScript(page, page.GetType, "IE10ImgFloatFix_func", "function IE10ImgFloatFix() {try {var o = Sys.WebForms.PageRequestManager._instance;var s = o._additionalInput;s = s.replace(/(.y=\d+)([.]\d+)?/g, '$1');s = s.replace(/(.x=\d+)([.]\d+)?/g, '$1');o._additionalInput = s;} catch (ex){}}", True)
        End If
    End Sub
   

c#:

//put these in global.asax.cs
void Application_PostMapRequestHandler(object sender, EventArgs e)
    {       
        var app = (HttpApplication)sender;
        var handler = (IHttpHandler)app.Context.Handler;
        Page page = handler as Page;
       
        if (page != null)
        {
            page.Load += Page_LoadFix;
        }    
    }

    private void Page_LoadFix(object sender, EventArgs e)
    {
        var page = (Page)HttpContext.Current.Handler;
        var smg = ScriptManager.GetCurrent(page);
        if (smg != null && (page.IsPostBack == false || smg.IsInAsyncPostBack == false))
        {
            ScriptManager.RegisterOnSubmitStatement(page, page.GetType(), "IE10ImgFloatFix", "IE10ImgFloatFix();");
            ScriptManager.RegisterStartupScript(page, page.GetType(), "IE10ImgFloatFix_func", "function IE10ImgFloatFix() {try {var o = Sys.WebForms.PageRequestManager._instance;var s = o._additionalInput;s = s.replace(/(.y=\\d+)([.]\\d+)?/g, '$1');s = s.replace(/(.x=\\d+)([.]\\d+)?/g, '$1');o._additionalInput = s;} catch (ex){}}", true);
        }   
    }
   

References
http://support.microsoft.com/kb/2600088

http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

http://stackoverflow.com/questions/13784718/asp-net-fails-to-detect-ie10-causing-dopostback-is-undefined-javascript-error

c# .net list anonymous read only store dynamic types in session

If you’re new to .Net 4.0 “dynamic” type, then you may or may not be surprised to find this is reserved for unique object types with read-only properties, as compared to its previous counterpart the “object” type.

In general, this is not an issue that many will encounter, at least initially, since many implementations will probably be focused on one-way databinding to controls on pages which in turn update the database directly instead of the in-memory object storing the values from the initial data results.

However, keep in mind that as cool as dynamic is, this immutable nature makes for a mess in circumstances that require two-way binding, such as with a session variable (example below). If you are keen on using it in these scenarios, never fear, I have worked up your solution. 😉

A typical practice sometimes utilized for Session variables is to use a common class for getting/setting session values, such as (you can skip ahead if you’re familiar with this aspect):

The immutable Session scenario

public static class SessionVars {

public static object MySessionValue{get {return getval("MySessionValue");} set {setval("MySessionValue",value);}}

public static List<object> MyListOfSomething { get { return (List<object>)getval("MyListOfSomething"); } set { setval("MyListOfSomething",value); } }

        private static object getval(string key)
        {
            try
            {
                return HttpContext.Current.Session[key];
            }
            catch (Exception ex)
            {
                //YourErrorClass.HandleError(ex);
                //return "Error retrieving value";
return null;
            }
        }

        private static void setval(string key, object value)
        {
            try
            {
                HttpContext.Current.Session[key] = value;
            }
            catch (Exception ex) {
                //YourErrorClass.HandleError(ex);
                //return "Error setting value";
            }
        }
}

The above could then be utilized such as:

SessionVars.MyListOfSomething =somevalue;
//or
SessionVars.MyListOfSomething [0]=somevalue;
//or
yourdatabindingcontrol.DataSource = SessionVars.MapNames;
yourdatabindingcontrol.DataBind(); //etc..

This of course makes Session usage much easier, however, our third line of code in the above example would not be possible if it were of type dynamic, which otherwise generally replaces object.

If MyListOfSomething were instead List of dynamic, you would have to use the following:

Solution

//for list
   var removei = SessionVars.MyListOfSomething [index];
                SessionVars.MyListOfSomething .Remove(removei);
                string newvalue = "somenewvalue";
                var addi = new { id = removei.id, name = removei.name, value= newvalue };
                SessionVars.MyListOfSomething .Add(addi);

//for single value
   var removei = SessionVars.MySessionValue;
                string newvalue = "somenewvalue";
                var addi = new { id = removei.id, name = removei.name, value= newvalue };
                SessionVars.MySessionValue=addi;

References
MSDN (Immutable anonymous types), c# .net list anonymous read only store dynamic types in session
Store List to Session (StackOverflow), http://stackoverflow.com/questions/1259934/store-list-to-session

Impersonation with Network Credentials in C# .Net

(Mostly) unmodified code, courtesy of Phil Harding (see references below for original post).

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Tools.Network
{
public enum LogonType
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,// Win2K or higher
LOGON32_LOGON_NEW_CREDENTIALS = 9// Win2K or higher
};

public enum LogonProvider
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3
};

public enum ImpersonationLevel
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3
}

class Win32NativeMethods
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LogonUser(string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
}

/// <summary>
/// Allows code to be executed under the security context of a specified user account.
/// </summary>
/// <remarks>
///
/// Implements IDispose, so can be used via a using-directive or method calls;
///...
///
///var imp = new Impersonator( "myUsername", "myDomainname", "myPassword" );
///imp.UndoImpersonation();
///
///...
///
/// var imp = new Impersonator();
///imp.Impersonate("myUsername", "myDomainname", "myPassword");
///imp.UndoImpersonation();
///
///...
///
///using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
///{
///...
///
///...
///}
///
///...
/// </remarks>
public class Impersonator : IDisposable
{
private WindowsImpersonationContext _wic;

/// <summary>
/// Begins impersonation with the given credentials, Logon type and Logon provider.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
/// <param name="logonType">Type of the logon.</param>
/// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
public Impersonator(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
{
Impersonate(userName, domainName, password, logonType, logonProvider);
}

/// <summary>
/// Begins impersonation with the given credentials.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
public Impersonator(string userName, string domainName, string password)
{
Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
}

/// <summary>
/// Initializes a new instance of the <see cref="Impersonator"/> class.
/// </summary>
public Impersonator()
{}

/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
UndoImpersonation();
}

/// <summary>
/// Impersonates the specified user account.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
public void Impersonate(string userName, string domainName, string password)
{
Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
}

/// <summary>
/// Impersonates the specified user account.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">Name of the domain.</param>
/// <param name="password">The password. <see cref="System.String"/></param>
/// <param name="logonType">Type of the logon.</param>
/// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
public void Impersonate(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
{
UndoImpersonation();

IntPtr logonToken = IntPtr.Zero;
IntPtr logonTokenDuplicate = IntPtr.Zero;
try
{
// revert to the application pool identity, saving the identity of the current requestor
_wic = WindowsIdentity.Impersonate(IntPtr.Zero);

// do logon & impersonate
if (Win32NativeMethods.LogonUser(userName,
domainName,
password,
(int)logonType,
(int)logonProvider,
ref logonToken) != 0)
{
if (Win32NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0)
{
var wi = new WindowsIdentity(logonTokenDuplicate);
wi.Impersonate();// discard the returned identity context (which is the context of the application pool)
}
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
finally
{
if (logonToken != IntPtr.Zero)
Win32NativeMethods.CloseHandle(logonToken);

if (logonTokenDuplicate != IntPtr.Zero)
Win32NativeMethods.CloseHandle(logonTokenDuplicate);
}
}

/// <summary>
/// Stops impersonation.
/// </summary>
private void UndoImpersonation()
{
// restore saved requestor identity
if (_wic != null)
_wic.Undo();
_wic = null;
}
}
}

References
http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/

Logon failure: unknown username or bad password

The following error occurred on an application deployed to a Server 2008 machine which was not part of the domain, but on the same network. The application needed to query to domain controller for permissions related to the users browsing the site.

If you encounter this error, this is intentional to prevent unauthorized enumeration of domain information by unknown users/accounts. There are a couple different ways to resolve this issue (see references for MSDN link.)

The method I settled on is referred to as the “impersonation feature” of the web.config.

See this article I have posted on using aspnet_setreg in server 2008.

References:
MSDN, http://support.microsoft.com/kb/842789#appliesto

aspnet_setreg in Server 2008

The aspnet_setreg utility is very useful for storing encrypted domain credentials, connection strings and other values referenced in a web.config which should not be visible in plaintext.

One such technique is when using the .Net “impersonation” mechanism. Typically, this would look something like:

<system.web>
<identity impersonate="true" userName="WindowsDomain\YourUserName" password="YourPassword" />
</system.web> 

However, if you download and unzip/install the aspnet_setreg utility, you can now use the following syntax to store these credentials in a binary encrypted field in the registry:

c:\Tools>aspnet_setreg.exe -k:SOFTWARE\MY_SECURE_APP\identity -u:"yourdomainname\username" -p:"password"

Your web.config should now be updated to reflect the new stored values. (Note: this is the exact syntax, don’t replace username and password with your own…):

<identity impersonate="true"
userName="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,username"
password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,password" />

An important thing to note is in Server 2008 on a 64 bit machine after running this utility is a different location it is stored in the registry. To find it you must browse to:

[HKEY_CURRENT_USER\Software\Classes\VirtualStore\MACHINE\SOFTWARE\Wow6432Node]

You can then right click and export this key from here, then open the .reg file in notepad and change to the correct key and import. The end result should be a reg file to import that looks like this:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\Software\MY_SECURE_APP]

[HKEY_LOCAL_MACHINE\Software\MY_SECURE_APP\identity]

[HKEY_LOCAL_MACHINE\Software\MY_SECURE_APP\identity\ASPNET_SETREG]
"userName"=hex:01,00,00, etc
"password"=hex:01,00,00, etc

References
MSDN, http://support.microsoft.com/kb/329290
ASPDEV, http://www.aspdev.org/articles/web.config/
ASPNET FORUMS, http://forums.asp.net/t/1650965.aspx/1?aspnet_setreg+under+Win+2008

Change WPF Toolbar and Window Skin

Took me some Googling to come across some good links to help me find exactly what I was looking to do. Hopefully my post gets enough hits that you’ll come across my title sooner rather than later, and can benefit from my time and research. 🙂

If you’re new to WPF, or even if you’ve been using WPF for some quite some time, you may or may not have noticed that theming and skinning is not relatively straight forward, and there are many different ways to achieve the end result visually.

If you’re using WPF simply to learn the new technology, understand that there are pro’s and con’s to WPF vs standard Winforms, and although the latter is technically “legacy”, depending on third party controls you may or may not be using, implementation in Winforms can be very fast and may still be a better option for some projects.

Here’s a simple grid I’ve come up with to help you decide which to use:

  WinForms WPF
Supports Skins No Yes
Uses graphics resources to render No Yes
Easily bind controls with data No Yes
Easy to design a form with drag+drop Yes No
Some cross-platform compatibility with Mono Yes No
Easily customize look and feel of controls No Yes
Already comes with most controls/visuals needed for business app Yes No

As you can see from the table above, if you are trying to quickly knock out a business app that is not going to require heavy visual modification or too reliant on databinding, it’s probably faster in WinForms. Also, I have personally deployed WinForms cross-platform (Mac, Linux) using mono, which I could not get to work with WPF.

Overall though, for most environments, WPF is usually the way to go if not for visual flexibility then for databinding (why are you using windows client apps again?:P).

One ways listed above that WPF really comes out on top is in utilizing the computer’s graphics card and other graphics resources to render forms. The WPF objects on the screen are still contained in a form however, and many theming examples override the draw methods on the forms themselves which don’t properly utilize the effectiveness of WPF.

In general, I have found there are at least three different ways to change the look and feel of your application in WPF:

Using Silverlight Themes
Using Office Themes
Using your own Custom Themes

If you download and install the Silverlight toolkit (not to be confused with silverlight SDK or silverlight client), you will automatically get multiple dll references which contain XAML themes that can be re-used in WPF. This is a quick way to make your WPF app look good without too much work.

Office themes are pre-built in, and a common choice for many beginner WPF skinners. They share common visuals which you see in many office apps and give your application a more up-to date look and feel with some recognizability by your users also, similar to how Mac applications all share a common theme.

This is also always an option, but be prepared for a long and ardous task and a few lunch days with your favorite designer. Microsoft expressions studio comes with all the tools needed to make your controls as beautiful as you like, and implementing and inheriting from these visuals is actually relatively simple, but when you apply the time it takes to make one control by the amount of different controls you may have, there is alot of work involved. Also for re-usability, you’ll want to put all your custom controls/skins in their own assembly which increases the time even further. If you’re short on time (who isn’t :P), this is not a good option, but in the long-run this could be very beneficial and give your applications their own gleam.

See references for links on how to implement the above and other information regarding skinning and theming in WPF. (The reference links are in order of my google “stream of consciousness” :P)

References
WPF Skins (this blog), <a href="https://ronniediaz.wordpress.com/wp-admin/post.php?post=1250&action=edit
MSDN Blog, http://social.msdn.microsoft.com/forums/en-us/wpf/thread/c87d508b-9195-4a68-831f-315b64520fcf
Codeproject Article, http://www.codeproject.com/KB/WPF/WPFBusinessAppsPartOne.aspx
Stackoverflow Blog, http://stackoverflow.com/questions/260098/any-free-wpf-themes
Codeplex Article, http://wpfcontrib.codeplex.com/wikipage?title=Themes&referringTitle=Home&ProjectName=wpfcontrib
WPF Tutorial.Net, http://www.wpftutorial.net/Expander.html
Silverlight.Net Blog, http://blogs.silverlight.net/blogs/msnow/archive/2009/02/09/silverlight-tip-of-the-day-91-how-to-apply-themes-from-the-silverlight-toolkit.aspx
MSDN Social, http://social.msdn.microsoft.com/forums/en-US/wpf/thread/3c66adb7-fd26-40c7-8404-85f6fefbd392/
C-sharp Corner Article, http://www.c-sharpcorner.com/Resources/Detail.aspx?ResourceId=667
Browsoft Article, http://www.browsoft.com/tutorials/DefaultTheme.html
Jan-Cornelius Molnar (Blog), http://www.vb-magazin.de/forums/blogs/janm/archive/2006/06/19/4655.aspx
MSDN Official Blog, http://blogs.msdn.com/b/wpfsdk/archive/2008/09/08/custom-window-chrome-in-wpf.aspx

C# and VB Equivalents

VB:

'shorthand object constructors; assigned initial properties
dim p as New Person() With {.FirstName = "john", .LastName="smith"}

'add handler for events
AddHandler context.BeginRequest, AddressOf Applicaton_BeginRequest

C#:

//shorthand object constructors; assigned initial properties
Person p = new Person() with {FirstName = "john", LastName="smith"}

//add handler for events
context.BeginRequest += Application_BeginRequest;

IIF in C#

I always find myself referencing my other projects for this one when I jump between languages, so decided to toss it on the web.

Both examples are in the context of ASP .Net, but syntax also applies np to Winforms

In VB:

<asp:label id="lblmessage" runat="server" visible='<%# iif(1=1,"true","false") %>' />

C# Equivalent:

<asp:label id="lblmessage" runat="server" visible='<%# 1 == 1 ? "true" : "false" %>' />

Serialize and Deserialize classes and objects in .Net

Serialization is a powerful tool and a major factor in many intermediate development technologies such as webservices.

Simply call “SerializeObject” and pass in the class name of your object for the “T” parameters, and your object will be serialized as an xml string which can then be stored in DB or written to disk!

To mark a public variable so it is not serialized, such as a decrypted key value or password, simply mark it with the attribute [XmlIgnore].

Enjoy. 😉

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ApplicationName
{

    /// <summary>
    /// Contains generic static/shared methods accessible throughout the site
    /// </summary>
    public static class XMLSerialization
    {
        /// <summary>
        /// Serialize Object of Type T to XML and return value as string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pObject"></param>
        /// <returns></returns>
        public static String SerializeObject<T>(T pObject)
        {
            /*try
            */
            String XmlizedString = null;
            MemoryStream memoryStream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            xs.Serialize(xmlTextWriter, pObject);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return XmlizedString;
            /*}
            catch (Exception e) { System.Console.WriteLine(e); return null; }*/
        }

        public static T DeserializeObject<T>(string URL)
        {
            /*try
            */
            T returnObject;
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextReader xmlTextReader = new XmlTextReader(URL);
            returnObject = (T)xs.Deserialize(xmlTextReader);
            //xs.Serialize(xmlTextWriter, pObject);
            return returnObject;
            /*}
            catch (Exception e) { System.Console.WriteLine(e); return null; }*/
        }

        public static String UTF8ByteArrayToString(Byte[] characters)
        {

            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        public static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }
    }
}


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All server side code examples are in C# .Net.

References
Original reference misplaced.