Archive for the ‘programming’ category

SQL Server 2008 RTM released!

August 8th, 2008

Not that I think I’m breaking any news here, but SQL Server 2008 has been officially RTM (released to manufacturing).  So far I’ve been very pleased working with SQL Server 2008 and am excited to get my RC0 version updated to an official release.

One thing I stumbled across was a warning users to wait for Visual Studio.NET 2008 SP1 to be released BEFORE upgrading to the RTM version of SQL Server 2008.  This blog post cites compatibility problems if you don’t have SP1 installed before working with the RTM version of SQL. What I’m not sure about is if this applies to people using beta versions of SQL Server 2008 (RC0), Visual Studio 2008 SP1 and .NET Framework v3.5 SP1 like I am.  This uncertainty made me think that it may be best to wait for the final release of SP1 for VS.NET and the 3.5 Framework.

I then came across a nugget here that said:

well….there’s a…ahem…NDA about this topic…but SQL Server 2008 RTM ships with a RTM version of the .NET Framework 3.5 SP1 bits…i’ll let you connect the dots.

I guess it’s time to dig around in the RTM version of SQL 2008 to see if it’s there.  I also wonder if it’s safe to install over top of my RC0 version of if I should remove RC0 before installing the RTM version.  I guess I’ll have to Google more to see what’s required.  I’ll provide updates as I find answers and get upgraded.

**** Update:

According to the release notes the beta SP1 isn’t an acceptable solution.  And since they’re saying SP1 will be officially released next week anyways, it makes sense just to wait for that I think.

What’s wrong with my Linqdatasource? – Method not found!

August 8th, 2008

I’ve been having a very weird problem in Visual Studio 2008 when trying to use the automatic operations for the Linqdatasource (insert, update or delete).  It seems that no matter what I try I get this weird “Method not found” problem.  Unfortunately there doesn’t seem to be a lot of help out on the web about why this may be happening.  I’m starting to think that there may be something goofed up with my 3.5 Framework or Visual Studio 2008.

Here’s the error and a link to the problem I posted out on the ASP.NET forums.  If anybody has come across this weird problem let me know. Unfortunately the 1 person that has replied on the discussion forums hasn’t been much help and offers up only basic suggestions as to why it may not be working, all of which were things that I had already known or tried right off the bat.

System.MissingMethodException: Method not found: ‘System.Object System.Web.UI.WebControls.Parameter.GetValue(System.Object, Boolean)’.

Generated: Mon, 04 Aug 2008 12:40:10 GMT
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.MissingMethodException: Method not found: 'System.Object System.Web.UI.WebControls.Parameter.GetValue(System.Object, Boolean)'.
at System.Web.UI.WebControls.LinqDataSourceView.MergeDictionaries(Object dataObjectType, ParameterCollection reference, IDictionary source, IDictionary destination, IDictionary destinationCopy)
at System.Web.UI.WebControls.LinqDataSourceView.BuildInsertDataObject(Object table, IDictionary values)
at System.Web.UI.WebControls.LinqDataSourceView.ExecuteInsert(IDictionary values)
at System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback)
at System.Web.UI.WebControls.FormView.HandleInsert(String commandArg, Boolean causesValidation)
at System.Web.UI.WebControls.FormView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.WebControls.FormView.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.FormViewRow.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
--- End of inner exception stack trace ---
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.sellyourhome_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Comments (from previous blog):

Have you installed the beta for Visual Studio 2008 / .NET Framework 3.5

SP 1?? I had the exact same issue on my development box until I

uninstalled the beta and installed the official release at http://www.microsoft.com/downloads/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E&;displaylang=en . Make sure you first run the beta removal tool: http://www.microsoft.com/downloads/details.aspx?FamilyId=A494B0E0-EB07-4FF1-A21C-A4663E456D9D&;displaylang=en


2008!!

July 16th, 2008

Wow, it’s been quite a while since I’ve posted.  It was just into 2008 back in January.  Wow how time flies!

Well, 2008 has brought many new versions of the tools that I use on a daily basis for my job.  Visual Studio has a 2008 version out.  Microsoft SQL Server has their 2008 version out (well, RTM will be next month so they say).  Also the .NET Framework is cranking along with the 3.5 framework which they are almost out with a final release of SP1.

I am excited that my job and the project I’m currently working on has given me the ability to upgrade to the latest versions of these tools.  So far I’ve been the most excited with SQL Server 2008 and all of the new features it has to offer.  Intellisense for T-SQL, now that’s nice!

I’m also anxiously awaiting Apple’s rumored update of their MacBook Pro laptop line.  Once they come out I’m going to get one and beef it up for my .NET Development.  I know many .NET developers out there would never think of owning a Mac, but man… once you go Mac you never go back!  My desktop at work is a HP workstation with Windows XP and I can’t even tell you how many times I need to reboot to keep things running smoothly.  It’s sad that as a Windows user I just am in the habbit now of rebooting when I leave for the day or when I go out to lunch.  With the Mac, I’m like “gee, I haven’t rebooted in a few weeks, I should probably just do it for the hell of it.”

Family life has been keeping me busy too.  We welcomed our 3rd child this past March and have been knee deep in kids!  Our twins turned 2 in June and they’re getting smarter and smarter with each day that passes.  It scares me that they’ll no doubt have me/us tied up in a closet at some point as they take over the house.

I am going to make an effort to post more moving forward.  God knows I come across enough technical things that would probably be helpful to others.  I’m learning to work with LINQ (also, here, scroll down to LINQ section) and can’t wait to get more into that.  Also, SubSonic, a great tool, is out with a new version.  I’ll be playing with that too when building an application I’m working on for my side-business.

Stay tuned!

Testing email when working with no SMTP server

January 9th, 2008

Happy New Year!

While this tip isn’t my own, it still seems as though it will be very helpful.  I know that I do a lot of development locally where I don’t have an SMTP server setup.  This tip, courtsey of .NET Tip of the Day, really will eliminate that problem and allow you to work with email without the headaches.

Testing code that sends email has always been a pain. You had to set up a SMTP service just to test that your .NET application sends the e-mail correctly.

However, there is a way to send e-mails with no SMTP server set up. Just configure your .NET application to drop e-mails into a specified folder instead of sending them via SMTP server:

<system.net>

<mailSettings>

<smtp deliveryMethod=”SpecifiedPickupDirectory”>

<specifiedPickupDirectory pickupDirectoryLocation=”c:\Test\” />

</smtp>

</mailSettings>

</system.net>

This will instruct SmtpClient class to generate mail message, save it as .eml file and drop it into c:\Test\ folder.

VB.NET RC4 Encryption for database storage

November 28th, 2007

I recently had to upgrade some Classic ASP code to .NET for some data encryption.  The routines use RC4 encryption and make the result database friendly.  The following class can easily be dropped into your project for use with little effort.  The sample code shows the encryption and decryption methods.  You just provide the message and the key for either instance.  From there you can drop it in your database or do whatever you want!

Sample Usage:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim plainText As String = “I’m exposed!”
Dim passkey As String = “keep me safe”

Dim safeText As String
safeText = Common.Encryption.Encrypt(plainText, passkey)

Response.Write(safeText)

Dim decrypted As String
decrypted = Common.Encryption.Decrypt(safeText, passkey)

Response.Write(decrypted)

End Sub

You can view the entire class here.  If you’re looking for some quick and easy encryption this will do the trick.

CMD Email updated

November 27th, 2007

The email command line utility I wrote (and discussed here), CMD Email, has been updated.  The latest release supports email attachments.

You can download the latest runtime or source from the project page on CodePlex.

CMD Email – command line email utility

October 26th, 2007

I’ve completed my first open source project.  I have been wanting to put something out on Codeplex for a while and finally got around to it.  The project I released is a small little command line email utility that uses the .NET 2.0 framework.  I wrote a more simple version of this years ago to email me when Windows scheduled tasks (batch files) completed.  The released version accepts many more options and allows you to store certain data into an application configuration file.

As this post title states, the utility is called CmdEmail and can be found here on codeplex.  From the project page you can download the latest (initial) release, see usage information and access the source code too.  Here’s a blurb on the usage from the project’s home page:

Usage:

CmdEmail -f nobody@nowhere.com -t you@domain.com -s Subject -b Body
CmdEmail -f "nobody@nowhere.com" -t "you@domain.com" -s "Subject" -b "Body"
CmdEmail -f nobody@nowhere.com -t you@domain.com,me@domain.com -s Subject -b Body
All command switches:
t, to         Required. Recipient (To)
f, from       Required. Sender (From)
b, body       Required. Email Body
s, subject    Required. Email Subject
h, host       SMTP Server - Optional only if provided in app config
p, port       SMTP Port - Optional, can also be provided in app config
u, username   Username - Optional, can also be provided in app config
p, password   Password - Optional, can also be provided in app config
help

Learn how to write better code for free!

September 12th, 2007

Use FxCop to write better code.  I’ve been using it for a little while now and it definitely has helped me out.

This article tells you how and why!

How to enable IntelliSense in .skin files in Visual Studio 2005

August 28th, 2007

A co-worker of mine shared this with me recently.  It was one of the biggest annoyances in Visual Studio 2005 if you ask me!

How to enable IntelliSense in .skin files

IntelliSence everywhere! That’s one of the biggest features in new Visual Studio .NET 2005 (VS 2005). But guess what, it doesn’t work out of the box in .skin file  – the place you really need it. Those of you who worked with ASP.NET 2.0 themes understand me . Good news – there is a workaround to enable this feature. Do the following:

1. Go to Tools->Options menu.

2. Pick Text Editor -> File Extesion fom a tree at the left part of Options dialog.

3. Type skin in Extesion text box.

4. Select User Control Editor from Editor dropdown.

5. Click Add and then Ok to close dialog and re-open your skin files.

6. Say something corny about Microsoft.

Enjoy!

FormView and ObjectDataSource with nullable types

July 15th, 2007

I recently ran into this problem when using a FormView and and ObjectDataSource where the FormView was binding to nullable data types…

Here is a challenging question, as I have not found any suitable information on this after two days of searching:

Background:

I have a custom Business Class library that includes custom objects with nullable int and DateTime properties. In order to update this data, I have created a FormView control bound to an ObjectDataSource that retrieves a generic List collection of my business objects. The reflection that is intrinsically called by the FormView/ObjectDataSource combination dutifully builds my basic Select, Update, and Insert templates. Now, when you edit the various (TextBoxes by default) input fields and then call the Update method referenced in the ODS (ObjectDataSource), the ODS attempts to convert the data contained in the input fields to the corresponding Type of the property bound to said input field. This is where we run into our little problem…

Even though I have a nullable Integer property type (let’s call it int? ClassNumber), if the corresponding TextBox is empty (since it’s not required), an exception is thrown by the ODS since it tries to convert an empty string value to an integer value before trying to set the object’s Property. Hah! If ODS was able to determine that the integer is in fact nullable, it should pass in a null value instead! But alas, it throws a System.IndexOutOfRangeException: “Index was outside the bounds of the array” error. And further down the stack: “Exception: is not a valid value for Int32″. Hmmm. Since this is a FormView control, we don’t have the ability to use a BoundField control with 2 very useful properties: NullDisplayText and ConvertEmptyStringToNull. It would be nice to tell ODS to enable sending null values from any control we want.

The above was posted originally here.  I used his clipping because it describes perfectly the problem I had, along with many, many others.

After hours and hours of Googling and trial and error I finally found the solution to this.  There was no way in hell I was going to accept the solution of manually re-populating each field I had bound in my edit and insert templates for my FormView.  The solution was much easier and left all of the heavy lifting to the FormView.

Basically, all you have to do is all insert and update parameters in your ObjectDataSource for each field you’re binding.  For these fields, you just need to supply the field name, the data type and set the ConvertEmptyStringToNull property to TRUE.  Also, you’ll need to be sure to set the ConvertNullToDBNul property to TRUE in the ObjectDataSource itself, like below.

<InsertParameters>
<asp:Parameter Name="TimeZoneOffset" Type="int32" ConvertEmptyStringToNull="true" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="TimeZoneOffset" Type="int32" ConvertEmptyStringToNull="true" />
</UpdateParameters>

So just by adding these parameters for the insert and update you can have your FormView’s databinding work with nullable types.  Not too bad, huh?

Comments (from previous blog):

Don,

Great! I am so glad you’ve found a solution to this annoying issue. Your solution is both simple and elegant. Since my posting (from which this post was based), I have by and large moved on from the FormView control in most cases and have instead used a number of different input methods, particular to the types of applications I have been building. This finding of yours may have sparked a new interest, and now I’ll have to play around with it some more. Thanks for posting a reply to my original post: (http://www.eggheadcafe.com/community/aspnet/2/81350/previous-community-conver.aspx).

I am having a problem like this one. However, I am using the Protected Sub GridView1_RowDataBound in order to control how the row will look like depending on the data. The problem is that when there is no data, I get this message:

Specified argument was out of the range of valid values.

It points to: datasch = e.Row.Cells(1).Text

Obvisly, if there is no data, there is no Row(1)… I tried to make a condition with that idea but nothen so far… help!!

Me again…

I foud this solution.

If e.Row.RowType = DataControlRowType.DataRow Then

‘all the code…

end if

Thanks for being part of the solution.

Gosh, thanks for your post. I hit into such problem and I was so puzzled for what was happening. For the reason that I had an ID field which supposed to be generated by the system. So, it was null during Insert. :-O

I ran into this issue as well and broke my head over it for a day or so. Then I discovered the FormView_OnItemInserting event and realized that I could validate the data there. I wrote code that changes empty strings to null for my decimal properties. Here’s the code:
protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
//do the check for empty strings instead of decimals here and make the value null if necessary
// Iterate through the items in the Values collection
// if key=FeesFirst or key=FeesSecond and value=”", change value to null
foreach (DictionaryEntry entry in e.Values)
{
if (entry.Value.Equals(“”) && (entry.Key.ToString() == “FeesFirst” || entry.Key.ToString() == “FeesSecond”))
{
e.Values[entry.Key] = null;
}
}
}

Don,

I am having the same problem. But in my case I have a custom object as my parameter. I am using a data entity class to transport data between the layers in my application. I have the same scenario whereby I have bound my formview with an objectdatasource.

My update method in my business object looks a bit like this

Public Function Update(ByVal NewEmployee As Employee, ByVal OldEmployee As Employee) As Boolean

JP,

What do the parameters for your datasource look like?

Don,

The parameters for my datasource are the two objects that are being passed to my update function (NewEmployee and OldEmployee). The objectdatasource works with a list of individual parameters representing the individual fields in the database that you may want to update or it can also work with custom objects that holds these parameters as properties. In this case I have taken into consideration of optimistic concurrency. That is why I have two parameters which the objectdatasource picks up as objects. One passes in the new values and the other retains the old values. This works by setting the ConflictDetection property of the objectdatasource to CompareAllValues.

By the way for some reason the whole scenario works without a fuss with a details view. But I need the UI design flexibility of the formview

Thanks

Don

Here is a cut down version of the Employee object being passed as new and old parameters in my business object

”’ <summary>
”’ This is the class representing a single instance of Employee
”’ </summary>
”’ <remarks>Primary key of this class is <c>EmployeeId</c></remarks>
<Serializable()> _
Public Class Employee
Inherits BaseDataEntity
Implements IDataEntity

#Region ” Private Declarations ”
Private _EmployeeId As Nullable(Of Int32)
Private _OrgTreeId As Nullable(Of Int32)
Private _PayNumber As String = String.Empty
Private _FirstName As String = String.Empty
Private _LastName As String = String.Empty
#End Region

#Region ” Constructor/Initialisation ”
Sub New()
init()
End Sub

Protected Overrides Sub init()
‘ Initialization Implementation if needed
End Sub
#End Region

#Region ” Entity Primary Keys ”
<DataObjectField(True, True, False), Browsable(False), Description(“Employee Id”)> _
Public Property EmployeeId() As Int64 Implements IDataEntity.Id
Get
Return _EmployeeId.GetValueOrDefault(0)
End Get
Set(ByVal Value As Int64)
_EmployeeId = Value
End Set
End Property
#End Region

#Region ” Public Properties ”
<DataObjectField(False, False, False), Browsable(False), Description(“Org Tree Id”)> _
Public Property OrgTreeId() As Nullable(Of Int32)
Get
Return _OrgTreeId.GetValueOrDefault(0)
End Get
Set(ByVal Value As Nullable(Of Int32))
_OrgTreeId = Value
End Set
End Property

<DataObjectField(False, False, False, 50), Browsable(False), Description(“Pay Number”)> _
Public Property PayNumber() As String
Get
Return _PayNumber
End Get
Set(ByVal Value As String)
_PayNumber = Value
End Set
End Property

<DataObjectField(False, False, False, 50), Browsable(False), Description(“First Name”)> _
Public Property FirstName() As String
Get
Return _FirstName
End Get
Set(ByVal Value As String)
_FirstName = Value
End Set
End Property

<DataObjectField(False, False, False, 50), Browsable(False), Description(“Last Name”)> _
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal Value As String)
_LastName = Value
End Set
End Property

#End Region

End Class

Hi Don,

Have u managed to find a work around to my problem?

Regards

JP

JP,

I guess I didn’t understand completely what you were asking. In my example, the parameters were nullable database fields that I was trying to bind to in a formview. You indicated that your two parameters are custom objects. The two aren’t really the same thing.

Is your problem that you can’t bind to the properties of the custom objects or that your properties that the capability of being null aren’t retaining their null values?

JP, I had the same problem. I worked around the issue by using the Formview ItemUpdating event to see if the field value was String.Empty, if it was I set it to a null value. In my business object the fields are declared as Nullable<int>.

It is not working with DateTime data type. it is giving me following error
Object of type ‘System.DBNull’ cannot be converted to type ‘System.Nullable`1[System.DateTime]‘.

I have scenario as you have i have connected my objectdatasource with my formview and sending data from BLL to DAL. Can you suggest me any idea

Milind,

Based on the instructions in my original post, it should work fine with a datetime data type. You need to make sure that your insert and update parameters are correct. Here’s a snippet from an ObjectDataSource in one of my projects, which uses datetime datatypes. This works fine:

Keep in mind, I’ve removed some extra insert and update parameters to keep the comment shorter. They keys here to remember are to make sure you have ConvertNullToDbNull=”true” in the object datasource and to be sure to have your nullable field in the insert and/or update parameters collection with ConvertEmptyStringToNull=”true” set.

<asp:ObjectDataSource ID=”EmployeeInfoDataSource” runat=”server” DataObjectTypeName=”HeeHawApp.Entities.EmployeeInfoView”
InsertMethod=”InsertEmployeeInfo” SelectMethod=”GetEmployeeInfoByEmployeeId”
TypeName=”HeeHawApp.Business.EmployeeManager” UpdateMethod=”UpdateEmployeeInfo”
ConvertNullToDBNull=”true”>
<SelectParameters>
<asp:QueryStringParameter Name=”EmployeeId” QueryStringField=”EmployeeId” Type=”Int32″
DefaultValue=”0″ />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name=”EmployeeDOB” Type=”datetime” ConvertEmptyStringToNull=”true” />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name=”EmployeeDOB” Type=”datetime” ConvertEmptyStringToNull=”true” />
</UpdateParameters>
</asp:ObjectDataSource>

I tried to use a FormView and there is a checkbox field to display boolean value. It causes exception when the database value is null. How to solve this?

Thanks man, it solved my problem. I was just about to kick my computer :-)

Can anyone help with this one? Similar problem, but I’m using a GridView. My Select method on the ObjectDataSource is taking it’s parameters from the QueryString.

Example Parameter:
<asp:QueryStringParameter DefaultValue=”Null” Name=”pItemNo” QueryStringField=”Item”
Type=”Int32″ ConvertEmptyStringToNull=”true” />

I also have ConvertNullToDBNull=”True” on the ObjectDataSource.

When I try to run it, I get the following:

[FormatException: Input string was not in a correct format.]
System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +2755599
System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +112
System.String.System.IConvertible.ToInt32(IFormatProvider provider) +43
System.Convert.ChangeType(Object value, TypeCode typeCode, IFormatProvider provider) +293
System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, TypeCode type, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges) +264
System.Web.UI.WebControls.Parameter.get_ParameterValue() +66
System.Web.UI.WebControls.ParameterCollection.GetValues(HttpContext context, Control control) +254
System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +257
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +17
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +149
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +70
System.Web.UI.WebControls.GridView.DataBind() +4
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82
System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +69
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +50
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Control.PreRenderRecursiveInternal() +170
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2041

Thanks!!

-Brice

Never mind! I found my problem. I removed DefaultValue=”Null” from each of my parameters. Also, in my case, I needed to set ConvertNullToDBNull=”false” on the ObjectDataSource.

Thanks! Great Article!! It really helped!