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.
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
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.