Joseph Michael Pesch
VP Programming

LINQ to SQL Error: Cannot access a disposed object.

by 3. October 2008 14:48

LINQ to SQL Error:

Cannot access a disposed object.
Object name: 'DataContext accessed after Dispose.'.

One case that case cause this error is when related table/object doesn't have any rows and the parent object is used outside of the scope of the DataContext object that instantiated it.

EXAMPLE:

public static tbl_LoanRequest GetLoanRequest(Guid LoanRequestID)
{
  using (BidMortgageDataContext bmdb = new BidMortgageDataContext())
  {
    tbl_LoanRequest LoanRequestTable = bmdb.tbl_LoanRequests.SingleOrDefault(r => r.LoanRequestID == LoanRequestID);
    if (LoanRequestTable == null)
      LoanRequestTable = new tbl_LoanRequest();
    else if (LoanRequestTable.LoanRequestBids.Count() == 0)
      LoanRequestTable.LoanRequestBids = new System.Data.Linq.EntitySet<LoanRequestBid>();  // This line prevents the error.
    return LoanRequestTable;
  }
}

Tags:

LINQ to SQL

Virtual PC - Copying image that was connected to a domain

by 29. September 2008 15:59

Virtual PC - Copying image that was connected to a domain
There are a few issues that you need to deal with if the VM is joined to the domain. You will need to copy the relevant .vhd (disk image) and .vmc (config) files from the source, and then either:

  1. Run sysprep on your copy (may break some software installs)
  2. Or, manually change machine name
    • remove your copy from the domain (must be while disconnected from the network)
    • run newsid on the vm (available from sysinternals)
    • rename the vm
    • rejoin the vm to the domain

Tags:

Virtual PC

LINQ to SQL Links

by 14. September 2008 03:52

Tags:

[None]

SQL Transfer Object Between Schemas

by 14. September 2008 02:36

alterschema NewSchemaHere transfer ExistingSchemaHere.ObjectNameHere

Example: alter schema dbo transfer jpesch.tbl_SomeTable

This would transfer the table (tbl_SomeTable) from jpesch to dbo

 

Tags:

SQL Server

C# Regular Expression Date

by 12. September 2008 20:19

Author: Pujitha Sendanayake    01 Sep 2006 
Original Article: http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=147
c# Date validator function with Leap Year handling
-------------------------------------------------------------------------------------------------------------
public bool isDate(string strDate)
{
string strRegex = @"((^(10|12|0?[13578])([/])(3[01]|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(11|0?[469])([/])(30|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(2[0-8]|1[0-9]|0?[1- 9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(29)([/])([2468][048]00)$)|(^(0?2)([/])(29)([/])([3579][26]00)$)|(^(0?2)([/])(29)([/])([1][89][0][48])$)|(^(0?2)([/])(29)([/])([2-9][0-9][0][48])$)|(^(0?2)([/])(29)([/])([1][89][2468][048])$)|(^(0?2)([/])(29)([/])([2-9][0-9][2468][048])$)|(^(0?2)([/])(29)([/])([1][89][13579][26])$)|(^(0?2)([/])(29)([/])([2-9][0-9][13579][26])$))";

Regex re = new Regex(strRegex);
if (re.IsMatch(strDate))
return (true);
else
return (false);
}

This function will validate any date from 1800 -to 9999.
Also It will handle leap years.
Allowed formats are mm/dd/yyyy , m/dd/yyyy , mm/d/yyyy , m/d/yyyy.
 

 

Tags:

[None]

C# Regular Expression Date Validation

by 12. September 2008 20:15

Author: Pujitha Sendanayake    01 Sep 2006 
Original Article: http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=147
c# Date validator function with Leap Year handling
-------------------------------------------------------------------------------------------------------------
public bool isDate(string strDate)
{
string strRegex = @"((^(10|12|0?[13578])([/])(3[01]|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(11|0?[469])([/])(30|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(2[0-8]|1[0-9]|0?[1- 9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(29)([/])([2468][048]00)$)|(^(0?2)([/])(29)([/])([3579][26]00)$)|(^(0?2)([/])(29)([/])([1][89][0][48])$)|(^(0?2)([/])(29)([/])([2-9][0-9][0][48])$)|(^(0?2)([/])(29)([/])([1][89][2468][048])$)|(^(0?2)([/])(29)([/])([2-9][0-9][2468][048])$)|(^(0?2)([/])(29)([/])([1][89][13579][26])$)|(^(0?2)([/])(29)([/])([2-9][0-9][13579][26])$))";

Regex re = new Regex(strRegex);
if (re.IsMatch(strDate))
return (true);
else
return (false);
}

This function will validate any date from 1800 -to 9999.
Also It will handle leap years.
Allowed formats are mm/dd/yyyy , m/dd/yyyy , mm/d/yyyy , m/d/yyyy.
 

 

Tags:

[None]

SQL Server Convert UTC to Local Time

by 27. August 2008 19:06

The following SQL statement assumes you have a variable named @UTCDate that contains a UTC date value, the result will be the conversion of that UTC date value into a local time zone value (based on the server configuration settings from which you are running the statement).

select dateAdd(hour, datediff(hour, getutcdate(), getdate()), @UTCDate)

Side Note: ASP.Net Authentication, Workflow Foundation Persistence, etc. stores dates (such as aspnet_Membership.LastLoginDate, aspnet_Users.LastActivityDate, dbo.nextTimer, etc. in UTC time).

Tags:

SQL Server

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 Capturing HTML Stream

by 20. August 2008 23:31

Capture the stream during render...

protected override void Render(HtmlTextWriter output) {
    if ( (HasControls()) && (Controls[0] is LiteralControl) ) {
        output.Write("<H2>Your Message: " + ((LiteralControl) Controls[0]).Text + "</H2>");
    }
}


Generic code for ASP.Net web site...

The code below also demonstrates accessing web page context (things such as Server, Request, Response, etc.) from an external class (e.g. from a class that is being called by a web page) by using the System.Web.HttpContext.Current.

public static string ReadHtmlPage(string URL, bool RemoveTextLineFeeds)
{
  string html = "";
  if (URL.StartsWith("http"))
  {
    // For external http requests we need to use an actual http request.
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
    using (Stream stream = request.GetResponse().GetResponseStream())
    {
      using (StreamReader reader = new StreamReader(stream))
      {
        html = reader.ReadToEnd();
      }
    }
  }
  else
  {
    // For non-http (i.e. internal) requests we assume a Server.Execute() will be appropriate.
    System.IO.StringWriter writer = new System.IO.StringWriter();
    System.Web.HttpContext.Current.Server.Execute(URL, writer);
    html = writer.ToString();
  }
  // When reading back the html into a string, it seems to typically have \r\n representation of line feeds that we can safely remove.
  if (RemoveTextLineFeeds)
    return html.Replace("\r\n", "");
  else
    return html;
}


Sample from HTSM360 Short Application form:

  ///<summary>

  /// Overridden to handle Confirmation of the order by

  /// capturing the HTTP output and emailing it.

  ///</summary>

  ///<param name="writer"></param>

  protected override void Render(HtmlTextWriter writer)

  {

    // *** Write the HTML into this string builder

    StringBuilder sb = new StringBuilder();

    StringWriter sw = new StringWriter(sb);

    HtmlTextWriter hWriter = new HtmlTextWriter(sw);

    base.Render(hWriter);

    // *** store to a string

    string PageResult = sb.ToString();

    // *** Write it back to the server

    writer.Write(PageResult);

    string ErrorMessage = "";

    if (ValidSubmission)

    {

      HowToTorial.Mail.SendMail("Sender", "Sender", "Receiver", "Short Application", true, PageResult, ref ErrorMessage);

    }

  }

 

 


Links to resources...

http://odetocode.com/Articles/162.aspx

http://bytes.com/forum/thread115349.html

http://forums.asp.net/p/471841/485661.aspx#485661

http://www.velocityreviews.com/forums/t97151-httpresponse-capture-or-redirect-stream.html

Not directly related, but interesting...

http://69.10.233.10/KB/aspnet/fastload.aspx?display=Print

Tags:

[None]

ASP.Net Custom Configuration Setting

by 19. August 2008 16:50

Sample Code

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

void Test()
{
  IDictionary singleTag = (IDictionary)ConfigurationSettings.GetConfig("MySingleTagSection");
   NameValueCollection nameValue = (NameValueCollection)ConfigurationSettings.GetConfig("MyNameValueSection");
   Hashtable dictionary = (Hashtable)ConfigurationSettings.GetConfig("MyDictionarySection");
   NameValueCollection nameValueGroup = (NameValueCollection)ConfigurationSettings.GetConfig("MySectionGroup/MySection1");
   System.Diagnostics.Debug.WriteLine((string)singleTag["sample1"]);
   System.Diagnostics.Debug.WriteLine((string)nameValue["key1"]);
   System.Diagnostics.Debug.WriteLine((string)dictionary["key1"]);
   System.Diagnostics.Debug.WriteLine((string)nameValueGroup["key1"]);
}

 


App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="MySingleTagSection" type="System.Configuration.SingleTagSectionHandler"/>
    <section name="MyDictionarySection" type="System.Configuration.DictionarySectionHandler"/>
    <section name="MyNameValueSection" type="System.Configuration.NameValueSectionHandler"/>
    <sectionGroup name="MySectionGroup">
      <section name="MySection1" type="System.Configuration.NameValueSectionHandler"/>
      <section name="MySection2" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
  </configSections>
  <MySingleTagSection sample1="value1" sample2="value2" sample3="value3"/>
  <MyDictionarySection>
    <add key="key1" value="value1"/>
    <add key="key2" value="value2"/>
  </MyDictionarySection>
  <MyNameValueSection>
    <add key="key1" value="value1"/>
    <add key="key2" value="value2"/>
  </MyNameValueSection>
  <MySectionGroup>
    <MySection1>
      <add key="key1" value="value1"/>
      <add key="key2" value="value2"/>
    </MySection1>
    <MySection2>
      <add key="key1" value="value1"/>
      <add key="key2" value="value2"/>
    </MySection2>
  </MySectionGroup>
</configuration>

Tags:

[None]

SQL Server 2005 Authentication Mode

by 15. August 2008 14:44

Youcan change dht authentication mode between "Windows Authentication" and "Mixed Mode" after installation by changing a single registry value (shown below).  Value of 1 = "Windows Authentication Mode" value of 2 = "Mixed Authentication Mode".

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer]
"LoginMode"=dword:00000001

Additionally, to enable the sa login by using Transact-SQL
Execute the following statements to enable the sa password and assign a password.

ALTER LOGIN sa ENABLE;
GO
ALTER LOGIN sa WITH PASSWORD = '';
GO

To enable the sa login by using Management Studio
In Object Explorer, expand Security, expand Logins, right-click sa, and then click Properties.
On the General page, you might have to create and confirm a password for the sa login.
On the Status page, in the Login section, click Enabled, and then click OK.

Tags:

SQL Server

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

ASP.Net Sending Email

by 13. August 2008 22:28

Web.Config Sample:
<system.net>
 <mailSettings>
   <smtp deliveryMethod="network" from="ASP.Net.Test@ImpacCompanies.com">
     <network host="mailrelay" port="25" defaultCredentials="true"/>
   </smtp>
 </mailSettings>
</system.net>

 

Tags:

[None]

Building Workflow Services (WF+WCF) with Visual Studio 2008

by 13. August 2008 15:25

WEBCAST: Building Workflow Services (WF+WCF) with Visual Studio 2008

The Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) are two very relevant technologies within .NET 3.x for Public Sector applications. WCF represents a total unification layer for building connected systems and WF provides a powerful foundation for process reengineering. Combine them and you have an unbelievable set of capabilities for building robust enterprise application that involve both process automation as well as human and machine to machine workflow and process communication. Come learn the basis of how to build WCF services using workflow foundation in Visual Studio 2008.

When

Friday, February 22, 2008

2:00P-3:30P EST (11:00A-12:30P PST)

Register at this link:

 

http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032366132&Culture=en-US

Tags:

Windows Communication Foundation | Workflow Foundation

SQL Server Identity Columns vs. Oracle Sequence Numbers

by 12. August 2008 21:28

In SQL server you create an identity column like the sample below which creates an identity column with seed value of 1 and increment value of 1.  Then when you insert records the column value is incremented and set automatically.

SQL Server Sample:
create table #MyTable(RecID int identity(1,1), MyData varchar(50))
insert into #MyTable(MyData) values('This is a test')
insert into #MyTable(MyData) values('This is another test')
select * from #MyTable
drop table #MyTable

Not so in Oracle.  There you create the integer column; however, you must manually increment and set the column value as part of your insert statement.  You can use a Sequence object (after you create one) as shown below.

create sequence MySequence minvalue 1 maxvalue 999999999999 start with 1 increment by 1 cache 20
create table imdw.MyTable(RecID int, MyData varchar2(50))
insert into imdw.MyTable(RecID, MyData) values(MySequence.nextval, 'This is a test')
insert into imdw.MyTable(RecID, MyData) values(MySequence.nextval, 'This is another test')
select * from imdw.MyTable
drop table imdw.MyTable
drop sequence MySequence

In both cases you should get the following result set:

 RecID MyData 
 1 This is a test 
 2 This is another test

Tags:

Oracle | SQL Server

SQL Server Split Function

by 12. August 2008 18:39

CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000) -- List of delimited items
  , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (recid int identity(1,1), item VARCHAR(8000))
BEGIN
-- Adapted from: http://searchvb.techtarget.com/tip/0,289483,sid8_gci932171,00.html
-- Added recid (identity column)
-- Tests
/*
  select * from fnSplit('12345', ',')
  select * from fnSplit('1,22,333,444,,5555,666', ',')
  select * from fnSplit('1##22#333##444','##')  --note second item has embedded #
  select * from fnSplit('1 22 333 444  5555 666', ' ')
*/
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
 
 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END
IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO


Sample Usage via a Cursor:


declare
@recid int
, @item varchar(8000)
, @SampleData varchar(50)
set @SampleData = 'Item1,Item2,Item3,Item4,Item5'
declare split cursor for select * from dbo.fnSplit(@SampleData, ',')
open split
while 1=1 begin
fetch next from split into @recid, @item
if @@fetch_status <> 0 break
-- Do something here...
select @recid, @item
end
close split
deallocate split

Tags:

SQL Server