Joseph Michael Pesch
VP Programming

Get PublicKeyToken in Visual Studio

by 4. July 2009 18:43

The easiest way to get the PublicKeyToken of a .Net assembly is to use the SN.EXE which is typically installed in the SDK folder of the .Net framework (as shown below).

VS2005: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe

VS2008: C:\Program Files\Microsoft Visual Studio 9.0\SDK\v3.5\Bin\sn.exe

Sample usage: SN.exe -T C:\samplepath\sampleassembly.dll

Add the following to the Post Build events: "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe" -T "$(TargetPath)"

Then when you build the assembly it will print the public key token to the output window.

Also, you could run the assembly and put the following line in source code:

System.Diagnostics.Debug.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().FullName);

Tags: ,

ASP.Net | C# | Visual Studio

ASP.Net JavaScript Include References by Root Path (~/) Equivelant

by 27. April 2009 20:42

You cannot add a runat="Server" attribute to a <script> tag (otherwise it will actually run the script server side).  Without this attribute the script needs to have a relative path vs. a root path (e.g. ../../scripts/script.js vs. ~/scripts/script.js).  To overcome this limitation you can add stylesheet and/or script references using the following type of code to a Page_Load event on an ASP.Net web page:

Page.Header.Controls.Add(newLiteralControl(@"<link href='" + ResolveUrl("~/css/MainStyle.css") + "' rel='stylesheet' type='text/css' />\r\n"));

Page.Header.Controls.Add(newLiteralControl(@"<script src='" + ResolveUrl("~/JQuery/jquery-1.3.2.min.js") + "' type='text/javascript'></script>\r\n"));

 

 

Tags: ,

ASP.Net

TCP Provider, error: 0 - Only one usage of each socket address (protocol/network address/port) is normally permitted.

by 11. February 2009 14:27

Error: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - Only one usage of each socket address (protocol/network address/port) is normally permitted.)

This error was encountered on a web application running a batch upload of records into a SQL server database.  Each iteration in the master batch upload process contained approximately 50+ individual SQL transactions.  The issues appears to be that the web server was running out of dynamic ports due to the large volume of individual connections to the SQL server. 

http://support.microsoft.com/kb/328476

Adjust the MaxUserPort and TcpTimedWaitDelay settings

Note that the MaxUserPort and TcpTimedWaitDelay settings are applicable only for a client computer that is rapidly opening and closing connections to a remote computer that is running SQL Server and that is not using connection pooling. For example, these settings are applicable on an Internet Information Services (IIS) server that is servicing a large number of incoming HTTP requests and that is opening and closing connections to a remote computer that is running SQL Server and that is using the TCP/IP protocol with pooling disabled. If pooling is enabled, you do not have to adjust the MaxUserPort and TcpTimedWaitDelay settings.
 

The following changes to the registry key are used to override the default values:           HKEY_LOCAL_MACHINE\System\CurrectControlSet\services\Tcpip\Parameters            Value Name: MaxUserPort          Data Type: REG_DWORD          Value: 30000 (Decimal)           Value Name: TcpTimedWaitDelay           Data Type: REG_DWORD          Value: 30 (Decimal)

 

Tags: ,

ASP.Net | SQL Server

Getting Fully Qualified URL in ASP.Net Code

by 5. January 2009 22:33

Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, ResolveUrl("~/SubFolderIfAny/TheFile.aspx"));

Tags: ,

ASP.Net

C# Gridview History Highlight Example

by 16. December 2008 14:52

This sample loads a GridView and performs the two functions shown below.  The first function is simply to make the column labels more user friendly by adding spaces.  The second function is relevant to the historical aspect of the data being viewed.  It was intended as a method to load a grid of audit trail type changes to a single record.  The comparison will then highlight changed values so they stand out visually against the unchanged values.

  1. Performs a string replacement on the column names, putting spaces at every captial letter. For example: "ThisColumnName" would be converted to "This Column Name".
  2. Performs a column-by-column record comparison of the current row in the GridView (using a RegEx function) against the next row in the DataTable, and if the values don't match the GridView column is highlighted yellow. Note: It is best presented with newest records on top.

GridViewHistoryHighlight.zip (5.57 kb)

Tags:

ASP.Net | C#

C# Get Virtual Root Path of File System Web Site

by 8. December 2008 20:41

RootPath = newString('/', Request.Path.Replace(Request.ApplicationPath, "").Split('/').Length - 2).Replace("/", "../");

 

Tags:

ASP.Net | C#

aspnet_... Security Configuration

by 21. November 2008 19:36

Consists of SQL script to install database objects along with ASP.Net web site components.

Run %systemroot%\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe to install the ASP.Net user framework objects (tables, procs, etc.) into a SQL server database. 


Script to create database objects (in lieu of running the exe above): 
aspnet_Security.sql (238.96 kb)

Backup copy of emtpy database containing just the standard security objects: aspnet_Security.bak (1.83 mb)

Script to export data from: aspnet_Applications, aspnet_Users, aspnet_Membership, aspnet_Roles and aspnet_UsersInRoles tables: aspnet_SecurityDataExport.sql (4.80 kb)

See sample web.config and Login.aspx with some security features in code-behind: Sample.zipx (2.81 kb)

Adding a user to basic security roles:

EXEC sp_addrolemember 'aspnet_Membership_BasicAccess', 'usernamehere'
GO
EXEC sp_addrolemember 'aspnet_Personalization_BasicAccess', 'usernamehere'
GO
EXEC sp_addrolemember 'aspnet_Profile_BasicAccess', 'usernamehere'
GO
EXEC sp_addrolemember 'aspnet_Roles_BasicAccess', 'usernamehere'
GO
EXEC sp_addrolemember 'db_datareader', 'usernamehere'
GO
EXEC sp_addrolemember 'db_datawriter', 'usernamehere'
GO

Script to add new user to application and role (adds the application and role also if necessary)

declare
  @appName varchar(50)
, @userName varchar(50)
, @emailAddress varchar(100)
, @roleName varchar(50)

select
  @appName = 'ApplicationNameHere'
, @userName = 'UserNameHere'
, @emailAddress = 'UserEmailHere@Something.com'
, @roleName = 'RoleNameHere'

declare
  @appId uniqueidentifier
, @userId uniqueidentifier
, @roleId uniqueidentifier

select @appId = ApplicationId from dbo.aspnet_Applications where ApplicationName = @appName
if(@appId is null) begin
  set @appId = newid()
  insert into aspnet_Applications values(@appName, lower(@appName), @appId, @appId)
end

select @roleId = RoleId from dbo.aspnet_Roles where RoleName = @roleName
if(@roleId is null) begin
  set @roleId = newid()
  insert into aspnet_Roles values(@appId, @roleId, @roleName, lower(@roleName), @roleName)
end

set @userId = newid()
insert into aspnet_Users values(@appId, @userId, @userName, lower(@userName), null, 0, '1/1/1900')
insert into aspnet_Membership values(@appId, @userId, '5lxSnTx3kTUzWgnLr8C2xHXOZYM=', 2, 't8DHyWEWq+/Yr/RNBvo6hw==', null, @emailAddress, lower(@emailAddress), null, null, 1, 0, getdate(), '1/1/1900', '1/1/1900', '1/1/1900', 0, '1/1/1900', 0, '1/1/1900', null)

insert into aspnet_UsersInRoles values(@userId, @roleId)

Tags:

ASP.Net | Security

ASP.Net File System Website Build/Run Error

by 17. October 2008 14:00

Error 16 Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

In my case this error was most likely due to a file/folder level permission issue.  I was running a file system website in my VS2008 and received this error when attempting to build/run the web site.  When I moved the web site folder from the original network location (my H: drive) to my local C: drive the error went away.

 

 

Tags:

ASP.Net

ASP.Net Authentication/Role Management Problem - Losing Authentication

by 26. August 2008 19:46

Strange behavior was occurring on a web application, user login, access secure pages, when a page would reference User.IsInRole() method the user would lose their authentication (i.e. they would be logged off without realizing it).  The page making the call would finish loading properly; however, the next page request (either back to that page or to any other secure page) would result in the user being immediately kicked back out to the login screen.  It turns out in this case the issue was due to conflicting (or more specifically overlapping) web.config settings as it pertains to the security settings.  Specifically, the system.web/authentication/forms@name setting cannot be the same as the system.web/roleManager@cookieName.  As shown in the sample below, they have been appropriately given different values (i.e. ".MyAppAuth" and ".MyAppRoles" respectively).  The problem occurs if both settings have the same values they will overwrite each others cookies, in this case the call to the User.IsInRole() was writing over the authentication cookie thereby effectively causing the user to lose their authentication.

<!-- BEG: Security -->
<authentication mode="Forms">
  <forms name=".MyAppAuth" loginUrl="Login.aspx" defaultUrl="Menu.aspx" protection="All" timeout="30" path="/"
         requireSSL="false" slidingExpiration="true" cookieless="UseDeviceProfile" domain="" enableCrossAppRedirects="false">
    <credentials passwordFormat="SHA1"/>
  </forms>
</authentication>
<!-- BEG: Membership -->
<membership defaultProvider="MyAppSecurity">
  <providers>
    <add name="MyAppSecurity" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SQL"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="MyApp"
         requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="3" minRequiredPasswordLength="6"
         minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="5" passwordStrengthRegularExpression="" />
  </providers>
</membership>
<!-- END: Membership -->
<!-- BEG: Roles -->
<roleManager enabled="true" cacheRolesInCookie="true" cookieName=".MyAppRoles" cookieTimeout="30" cookiePath="/"
             cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All" defaultProvider="MyAppRoles">
  <providers>
    <add name="MyAppRoles" type="System.Web.Security.SqlRoleProvider" connectionStringName="SQL" applicationName="MyApp" />
  </providers>
</roleManager>
<!-- END: Roles -->
<authorization>
  <deny users="?"></deny>
</authorization>
<!-- BEG: Security -->

Tags:

ASP.Net

ASP.Net Membership Password Management

by 25. August 2008 23:31

Original source: http://mishler.net/PermaLink,guid,ea65afc0-2970-46f1-9412-4b57bbd906f4.aspx

The Asp.net membership provider was designed to allow for self-service password management but through an understanding of the configuration options as well as a combined use certain provider methods, web site administrators can effectively manage member passwords.  This article briefly summarizes the various settings and methods which can be combined to administratively manage passwords in an Asp.Net membership system based on the default SQLMembershipProvider.

The following (web.config) configuration options define how the AspNetSqlMembershipProvider behaves:

enablePasswordRetrieval – Enables/disables the membership provider’s GetPassword method. Note that GetPassword will always throw an exception if the user’s password is hashed. Default value is false.  Requires the password answer unless “requiresQuestionAndAnswer” in web.config is set to false.

enablePasswordReset – Enables/disables the membership provider’s ResetPassword method, which can be used to produce a randomly generated password. Default value is true.  ResetPassword requires the user’s passwordAnswer unless “requiresQuestionAndAnswer” in web.config is set to false.

requiresQuestionAndAnswer – Alters the behavior of the GetPassword and ResetPassword methods to require or not require the password answer parameter. Default value is true. This method is the key for administrative management of passwords since, by turning it off, administrators can retrieve or reset passwords.

passwordFormat – Defines how passwords will be stored when membership records are created. Note that once a membership record has been created, functions such as ChangePassword and ResetPassword will continue to store the credentials in the original passwordFormat, even if web.config is changed to use a different password format.

Clear the password and password answer are stored in clear text. The passwordSalt field (in the database) is left blank.
Encrypted the password, password answer and passwordSalt are stored in an encrypted format within the database using the key information supplied in the machineKey element of web.config
Hashed the password and password answer are hashed using a one-way hash algorithm and a randomly generated passwordSalt value.

Microsoft set the default value of passwordFormat to Hashed in order to promote their secure web initiative but for many applications, this level of security is overkill and can create inconveniences in managing passwords.

Given the above information, there are a number of approaches that can be taken to administratively manage membership passwords. Note that “administrative” management implies that the administrator does not know the member’s password or password answer.

Retrieving a member’s password

The GetPassword method may be used to retrieve a member’s password and, at first glance, appears to require the password answer. By setting “requiresQuestionAndAnswer” to false in web.config, the GetPassword method can be called with an empty password answer and therefore can be effectively used to administratively retrieve a member’s password. Note that “enablePasswordRetrieval” must be set to true in web.config to enable the GetPassword method:

If password is:

Clear Simply call the GetPassword method with the username and without the need for a password answer to retrieve the password.
Encrypted Simply call the GetPassword method with the username and without the need for a password answer to retrieve the password.
Hashed Not possible, however the password may be reset as described below.

In Visual Basic, you can call the shared GetPassword method as illustrated below. Note that the second parameter would be for the password answer if “requiresQuestionAndAnswer” were true in web.config.

Dim password As String = Membership.Provider.GetPassword(userName, String.Empty)

Resetting a member’s password

The ResetPassword method may be used to generate a new, randomly generated password and, at first glance, appears to require the user’s password answer. By setting “requiresQuestionAndAnswer” to false in web.config, the ResetPassword method can be called with an empty password answer to set a user’s password to some new randomly generated value.  ResetPassword works with all password formats (clear, encrypted, hashed).

In Visual Basic, you can call the shared ResetPassword method as illustrated below. Note that you can pass Nothing for the second parameter, passwordAnswer.

Dim newPassword As String = Membership.Provider.ResetPassword(username, Nothing)

Changing a member’s password

In some organizations, a Customer Service department may wish to change a user’s password to a new known value, perhaps in response to a customer request. The ChangePassword method, which appears to handle this need, unfortunately requires the original user password which is usually unavailable to the site administrator. By setting “requiresQuestionAndAnswer” to false, “enablePasswordRetrieval” to true and “enablePasswordReset” to true in web.config, the ResetPassword and ChangePassword methods can be used to change a user’s password to a known value, regardless of the password format:

Clear text Call the GetPassword method with the username and without the need for a password answer to retrieve the password. Now, armed with the password, call ChangePassword to set the password to a desired value.
Encrypted Call the GetPassword method with the username and without the need for a password answer to retrieve the password. Now, armed with the password, call ChangePassword to set the password to a desired value.
Hashed Call the ResetPassword method with the username and without the need for a password answer to reset the password to a new random value. Using the newly generated password, call ChangePassword to set the password to a desired value.

Changing a member’s Password Question and Password Answer

In some situations, the Customer Service department may wish to modify a member’s Password Question and Password Answer. This is easily accomplished if passwords are encrypted or maintained in clear text. For hashed passwords, however, a password-reset is also required since the provider method, ChangePasswordQuestionAndAnswer, requires the member’s password which is not retrievable. By setting “requiresQuestionAndAnswer” to false, “enablePasswordRetrieval” to true and “enablePasswordReset” to true in web.config, the member’s Password Question and Password Answer may be reset:

Clear text Call the GetPassword method with the username and without the need for a password answer to retrieve the password. Now, armed with the password, call ChangePasswordQuestionAndAnswer to set the Password Question and Password Answer to a desired value.
Encrypted Call the GetPassword method with the username and without the need for a password answer to retrieve the password. Now, armed with the password, call ChangePasswordQuestionAndAnswer to set the Password Question and Password Answer to a desired value.
Hashed Call the ResetPassword method with the username and without the need for a password answer to reset the password to a new random value. Using the newly generated password, call ChangePasswordQuestionAndAnswer to set the Password Question and Password Answer to a desired value. Optionally call ChangePassword to set the password to a more user-friendly value.

Changing the password format

As web sites mature, website administrators sometimes regret their original (sometimes unintended) choice in passwordFormat when using the AspNetSqlMembershipProvider. That is, membership passwords may be clear text when a hashed format is desired or vice versa. Microsoft’s decision to implement hashing in the default AspNetSqlMembershipProvider was wise and conservative but for many web sites with minimal security requirements, the password system can become cumbersome.  By directly calling a couple of the AspNet stored procedures, it is possible to change the password format:

Note: If the passwordFormat is initially “Clear” or “Encrypted”, use the membership.provider.GetPassword method to cache the original password before calling the stored procedures.

  1. Use the stored procedure aspnet Membership GetPasswordWithFormat to retrieve the current passwordSalt.
  2. Use the stored procedure aspnet Membership ResetPassword to set the passwordFormat to its intended (integer) value. The stored procedure requires readily available parameter values including passwordSalt (retrieved earlier), password (empty string) and passwordAnswer (Null).

At this point, the membership record has been placed into an initialized (unusable) state and the PasswordAnswer has been lost. If the original password was hashed, then it too will be unrecoverable.  The provider methods listed below and described in previous sections allow for resetting the credentials and, as they are used, the password and password answer will be stored in the new password format (clear, encrypted, hashed.)

  1. Call the ResetPassword method to generate and retrieve a new random Password. Remember that the second parameter (answer) is not required if “requiresQuestionAndAnswer” is set to false in web.config.
  2. Call the ChangePassword method, using the now-current password retrieved in the previous step, to set the password to a desired value.  If the original password was saved at the start of the procedure, it may be restored at this point.

For originally un-hashed passwords, the preceding steps allow for a change of passwordFormat with complete restoration of the original password.

The Password Answer could have easily been retrieved from the database at the outset if it was stored in clear text. In the case of an encrypted Password Answer, a more complicated approach which involves the provider’s protected DecryptPassword method could have been used to cache the original Password Answer.  If the original Password Answer were available, it could be restored with a call to the ChangePasswordQuestionAndAnswer provider method.

So, what can be done if the Password and/or Password Answer had to be sacrificed in favor of a new passwordFormat?  One solution might be to reset everyone’s credentials then send them by Email. Another solution might be to place a notice onto the web site that informs users and provides further instructions. Either way, the web site should leverage the self-service membership controls which allow the member to reset his/her own credentials.  The following outlines a series of steps that can be taken:

  1. A new arbitrary password can be assigned using either the ResetPassword or ChangePassword provider method. Similarly, a new arbitrary Password Question and Password Answer can be assigned using the ChangePasswordQuestionAndAnswer provider method.
  2. Since the user will not know his/her new credentials, ensure the Login Control includes the necessary properties (PasswordRecoveryText and PasswordRecoveryURL) to link the user to a page that includes a PasswordRecovery Control.
  3. Recall that the PasswordRecovery Control is driven by the provider settings in web.config. In particular, ensure that “requiresQuestionAndAnswer” is set to false so the PasswordRecovery Control does not prompt the user for a Password Answer. Also, ensure that the SMTP setting is specified in web.config so that the Email will be sent. If the membership record uses a hashed password format then a new (random) password will be sent, otherwise the password you assigned in the previous step will be sent.

Conclusion

Armed with a little knowledge, it is possible to use the membership provider methods to perform basic administrative functions for an otherwise self-service web site. It is possible (although probably undesirable) to have a mix of clear, encrypted and hashed passwords in the same database. Depending on the passwordFormat for a particular record, varying levels of administrative control are available. For the AspNetSqlMembershipProvider, it is possible to change the passwordFormat for a particular record using a combination of built-in stored procedure calls and membership provider methods.

Microsoft has done a good job in engineering the membership provider system and has really left no security holes. The procedures outlined here utilize a combination of built-in stored procedures as well as standard provider methods to accomplish certain activities that are routinely required of site administrators.

Tags:

ASP.Net

ASP.Net Accessing Page Object in WebControl

by 25. August 2008 15:47

Here is an example of performing a Page.Validate() from code in a WebControl...

Page page = HttpContext.Current.Handler as Page;
page.Validate("ConsumerProfile");

Tags:

ASP.Net

ASP.Net MessageBox Equivalent

by 21. August 2008 14:32

Tags:

ASP.Net

ASP.Net Streaming Flash Content

by 21. August 2008 14:23

Tags:

ASP.Net

ASP.Net File Manager

by 14. August 2008 14:44

Basic framework to support ASP.Net web page hosting of file management.  Consists of SQL script to install database objects along with ASP.Net web site components.

NOTE: This is built to work with the ASP.Net user framework (i.e. the aspnet_... objects).

Run %systemroot%\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe to install the ASP.Net user framework.

SQL Script: FileContentManager.sql (8.29 kb)

ASP.Net Web Site: FileManager.zip (42.26 kb)

Tags:

ASP.Net