ASP.NET What Server Side controls require a Server Form

This is a list that I have compiled of ASP server side controls that require or do not require to be nested inside of a server form (form runat=server)

Requires Does not Require
  asp:Label
  asp:HyperLink
asp:TextBox  
asp:Button  
asp:LinkButton  
asp:ImageButton  
asp:DropDownList  
asp:ListBox  
asp:CheckBox  
asp:CheckBoxList  
  asp:Image
  asp:ImageMap
  asp:Table
asp:BulletedList  
asp:HiddenField  
  asp:Literal
asp:Calendar  
  asp:AdRotator
asp:FileUpload  
asp:Wizard  
  asp:Xml
  asp:MultiView
  asp:View
  asp:Panel
  asp:PlaceHolder
  asp:Substitution
  asp:Localize
asp:GridView  
  asp:DataList
asp:DetailsView  
asp:FormView  
  asp:Repeater
  asp:XmlDataSource
asp:Menu  
asp:TreeView  

HOWTO obtain the ClickOnce Version at runtime

This article will show you how to get the ClickOnce Version at runtime of you .NET application. My examples are in VB.NET and C# but the same technique would work for any other .NET Assembly.

First you need to add a project reference to System.Deployment

Next import the namespace into your class

VB.NET
Imports System.Deployment
C#
using System.Deployment;

You can obtain the Current Version from the ApplicationDeployment.CurrentDeployment.CurrentVersion property. This returns a System.Version object.

Note (from MSDN): CurrentVersion will differ from UpdatedVersion if a new update has been installed but you have not yet called Restart. If the deployment manifest is configured to perform automatic updates, you can compare these two values to determine if you should restart the application.

Retrieve the ClickOnce Version from the CurrentVersion property

NOTE: The CurrentDeployment static property is only valid when the application has been deployed with ClickOnce. Therefore before you access this property, you should check the ApplicationDeployment.IsNetworkDeployed property first, it will always return a false in the debug environment.

VB.NET
Dim myVersion as Version
if (ApplicationDeployment.IsNetworkDeployed) then
   myVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion
end if
C#
Version myVersion;
if (ApplicationDeployment.IsNetworkDeployed)
   myVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion;

Using the Version object

From here you can use the version information in a label, say on an about form in this way.

VB.NET
label1.Text = string.Format("ClickOnce published Version: v{0}.{1}.{2}.{3}", myVersion.Major, myVersion.Minor, myVersion.Build, myVersion.Revision)
C#
label1.Text = string.Format("ClickOnce published Version: v{0}.{1}.{2}.{3}", myVersion.Major, myVersion.Minor, myVersion.Build, myVersion.Revision);

Webservice fix for error message - Maximum request length exceeded

So I ran into a weird error this morning on one of my webservices. It was a SOAP exception which yielded a 500 HTTP Status error (as viewable from the trace.axd)

“There was an exception running the extensions specified in the config file. –> Maximum request length exceeded.”

The WebService call was posting a DataSet to a WebMethod. I figured out that the DataSet that I was posting was larger than 4MB (4096 KB) which happens to be the default maximum request length for posting to ASP.NET web applications.

You can change this to fix the problem. It is important to note the reason there is a limit in the first place … this setting is there to help protect against DOS attacks. So take precaution when changing this on internet web applications

To increase the default posting limit for your web application. Just add / change the httpRuntime section inside of the system.web element.

<system .web>
<httpruntime maxRequestLength="8192" />
   . . . </system>

This changes it from 4 MB to 8 MB (8192 KB)


Utilizing SQL 2005 Linked Server to connect to external systems via OLE DB

You can utilize MS SQL Server 2005’s Linked Servers ability to connect to any OLE DB provider. Here we are connecting to an iSeries (AS/400) DB2 using the IBMDA400 ole db provider

Here is the command to add a linked server:

EXEC master.dbo.sp_addlinkedserver
  @server = N'MYSERVER',
  @srvproduct=N'IBMDA400',
  @provider=N'IBMDA400',
  @datasrc=N'MYSERVER',
  @provstr=N'Transport Product=Client Access;
    Force Translate=0;
    DATA SOURCE=MYSERVER;
    USER ID=MYUSERID;
    PASSWORD=MYPASSWORD;
    Connect Timeout=30;'

You’ll notice the Force Translate is set to 0, this is to translate the CSSID 65535 characters. For some reason on my system a 0 makes this work… I have seen other people use a value of 1 or 37 for this.

Querying data on a Linked Server

I had to use the OpenQuery statement to access the data on my linked server. Although I have seen other syntax that would suggest that you can access the linked server with out this. I was unable to make that syntax work with my instance.

Here is an example query I was able to execute against my JD Edwards library:

SELECT * FROM OpenQuery(JDEPROD, 'select * from F0911 where gldgj > 107001')

Why is this SO COOL!?

Not only can you select data from a linked system, but you can use most of the extra select parameters with this, like the INTO clause, or the TOP clause.

I was able to use this to transfer data from my JD Edwards EnterpriseOne production library with a command like this:

SELECT *
 INTO #glData
 FROM OpenQuery('select * from f0911 where glfy = 7')

This is just another option you have for integrating, reporting, or data warehousing. Think of composite reporting with your financial system, your project management system, your time keeper system, your HR system, your <insert anything here> system!

Drop me a note if any of you have used this, your likes / dislikes about this method.


Publishing a .NET ClickOnce Application to a linux Apache Server

You might think that you can only publish a ClickOnce application to a IIS server. This is in fact not the case, you CAN publish a ClickOnce application to a apache web server either running on Linux or Windows. In fact its pretty simple.

Configure your apache publish directory for ClickOnce applications

At the root directory of where you are publishing your ClickOnce application, create / edit a .htaccess file. (click here for the apache documentation on AddType) (if you still need help with apache I suggest the following book Apache: The Definitive Guide (3rd Edition) )
Add the following lines to it:

AddType application/x-ms-application application
AddType application/x-ms-manifest manifest
AddType application/octet-stream deploy

For some reason I also needed the following line in my .htaccess file

AddType application/x-msdownload dll

For more reading on ClickOnce check out Smart Client Deployment with ClickOnce(TM): Deploying Windows Forms Applications with ClickOnce(TM) (Microsoft .NET Development Series).

Use FTP when publishing from Visual Studio, Unless you want to install FrontPage Server Extensions on your Apache, Yuk!

Using a ClickOnce application with FireFox

Currently ClickOnce applications will only work with Internet Explorer, you CAN however use FireFox, but you will need to install the FFClickOnce extension.


Creating a Period Date Range Table, with SQL!

You need a way to lump dated records into periodic chunks, like say for a timesheet system. Say your company’s payroll periods are bi-weekly (that’s every other week). So you need a way to distinguish the dated payroll data into two week timesheets.

Sure you could spend three days figuring out a fancy algorithm, only to find out 6 months into your project that there is just this one teeny-tiny instance where they manually change the dates around, and your algorithm doesn’t work.

Well my friend what you need is a table that you can look up against. How are you going to create the data for that table? Very simple, especially with my example of a bi-weekly pay period schedule. We’ll use a SQL Query to perform the insert for us.

Here is what the table will look like for us when we are done:

PeriodID PeriodStart PeriodEnd
1 2006-09-25 00:00:00.000 2006-10-08 00:00:00.000
2 2006-10-09 00:00:00.000 2006-10-22 00:00:00.000
3 2006-10-23 00:00:00.000 2006-11-05 00:00:00.000
4 2006-11-06 00:00:00.000 2006-11-19 00:00:00.000
5 2006-11-20 00:00:00.000 2006-12-03 00:00:00.000

Here is the SQL Script that I used to generate the data for the period table (bi-weekly):

declare @i int, @ws datetime, @we datetime
 
select @ws = '2006-09-25', @i = -2
 
while @i &lt; 2000
begin
  select @i = @i + 2
  select @we = dateadd(day, -1, dateadd(week, @i+2, @ws))
  insert into PayPeriod (PeriodStart, PeriodEnd) values (dateadd(week, @i, @ws), @we)
  print cast(dateadd(week, @i, @ws) as varchar) + ' | ' + cast(@we as varchar)
end

Methodology used here

There you go, now you have a table with a unique id given to a date range of start date and end date. So now if you want to know what period a particular record is in, you can just join to that table in this way:

select employee, dateWorked, PayPeriod.id as payPeriod
 from Timesheet, PayPeriod
where 
 Timesheet.dateWorked between PayPeriod.PeriodStart and PayPeriod.PeriodEnd

Notice there is no JOIN statement used, that means we need to specify the join on criteria in the WHERE clause. We do it this way in order to utilize the BETWEEN function (inclusive of the start date and end date).

There is always a simple solution; some times it takes a little longer than other times to work it out. Coffee always seems to help me, Oh! and google.

For more SQL recipies and help you should check out the SQL Pocket Guide it covers Oracle, Microsoft SQL Server, MySql, IBM DB2, and PostreSQL.


Getting the First and Last day of the month with .NET C#

Ok so now you know how to get the last day of the month with SQL, but how can you get the first day or the last day of the month given a specific date? That problem is so simple with dot net and csharp! There is a convenience constructor for the DateTime object that can help us with it. This will even work with the computers local date time, or localizations.

Here is the DateTime constructor signature that we are going to use:

public DateTime(
   int year,
   int month,
   int day
);

First day of the month

Here we take the date, and using the DateTime constructor (year, month, day). We can create a new DateTime object with the first day of the month.

Here is the simple wrapper method to get the first day of the month:

public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
   return new DateTime(dateTime.Year, dateTime.Month, 1);
}

Last day of the month

For the last day of the month we do basically the same thing as the first day of the month, except after we have that value we add 1 month, then subtract 1 day. Walla! We have the last day of the month with c#!

Here is the simple wrapper method to get the last day of the month:

public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
   DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
   return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

How to reset a DNN password at the Database

If your DotNetNuke passwords all of a sudden stop working (like due to a failed upgrade), have no fear you can reset them at the database! This is not a hack, it uses the official aspnet Password Reset.

  • Open SQL Query Analyzer - Connect to your dotNetNuke database
  • Paste the following Stored Procedure code into the window, this will create a stored procedure for later use called uap_ResetPassword. This should survive DNN upgrades because we are predicating the stored procedure name with uap_
  • create procedure uap_ResetPassword
      @UserName NVarChar(255),
      @NewPassword NVarChar(255)
    as
    begin
      Declare @PasswordSalt NVarChar(128)
      Declare @Application NVarChar(255)
      
      Set @Application = (SELECT [ApplicationID] FROM aspnet_Users WHERE UserName=@UserName)
      Set @PasswordSalt = (SELECT PasswordSalt FROM aspnet_Membership WHERE UserID IN (SELECT UserID FROM aspnet_Users WHERE UserName=@UserName))
      
      Exec dbo.aspnet_Membership_ResetPassword @Application, @UserName, @NewPassword, 10, 10, @PasswordSalt, -5 
    end
  • Now you can reset your DotNetNuke passwords by simply opening up SQL Query Analyzer, connecting to your dotNetNuke database, then typing uap_ResetPassword ‘username’, ‘newpassword’

  • C# method to mimic PHP file_get_contents

    Here is a nifty little function that I wrote to mimic the PHP function file_get_contents. This C# method will read the string contents of a regular file, or a file from a URL (the response from a http request, not the actual file itself).

    Notice you have to convert the byte array results to ASCII using the System.Text assembly.

    note:
    You might be able to read the actual file from the webserver if you replace the DownloadData method on the webclient object to DownloadFile, but this is purely speculation. This kind of action would be useful if you wanted the actual script file not the results from it.

    /// <summary>
    /// Will return the string contents of a
    /// regular file or the contents of a
    /// response from a URL
    /// </summary>
    /// <param name="fileName">The filename or URL</param>
    /// <returns></returns>
    protected string file_get_contents(string fileName) 
    { 
     string sContents = string.Empty; 
     if (fileName.ToLower().IndexOf("http:") > -1) 
     { // URL 
     System.Net.WebClient wc = new System.Net.WebClient(); 
     byte[] response = wc.DownloadData(fileName); 
     sContents = System.Text.Encoding.ASCII.GetString(response); 
     } else { 
     // Regular Filename 
     System.IO.StreamReader sr = new System.IO.StreamReader(fileName); 
     sContents = sr.ReadToEnd(); 
     sr.Close(); 
     } 
     return sContents;
    }


    HOWTO Get the last day of the month with SQL

    Have you ever needed to find out what the last day of the month was with SQL. Lets say you needed to round up a date to the last day of the month… I found this necessary when writing a HR Benefits extract… They needed the benefits end date to be the last day of the month, so there was no lapse in medical coverage.

    This will get you the actual day number

    SELECT DAY(DATEADD(DAY,-1, DATEADD(MONTH,1, DATEADD(DAY,1-DAY(@d),@d)))) AS 'Last day of the month'

    If you want the full date just remove the outer DAY function

    see http://www.extremeexperts.com/SQL/Tips/DateTrick.aspx for more ways to do it



    « Previous PageNext Page »