Posts Tagged ‘asp.net’

Juice UI: Open source ASP.NET Web Forms components for jQuery UI widgets

February 29th, 2012

Here’s a helpful resource for anybody using ASP.NET Web Forms and jQuery UI.  In this blog postJon Galloway highlights JuiceUI, a new open source project from the folks over at appendTo which brings easy server side support for jQuery UI controls to your ASP.NET Webforms applications.

I definitely plan on checking out Juice UI the next time I have a need!

Using HTML5 Web Storage in ASP.NET

January 25th, 2012

This article does a great job at showing you a simple example of how to use local browser web storage in conjunction with ASP.NET web methods to save and retrieve the data from a server side database.  Even if you aren’t interested in using this functionality in an application you have now, it’s worth reading to know what HTML5 brings to the table as far as storing your data down at the client.

Ajax-based data loading using jQuery in ASP.NET

June 28th, 2011

Great article to check out!

Ajax-based data loading using jQuery.load() function in ASP.NET – Hajan Selmani takes a back to basics look at using jQuery to load partial chunks of HTML from a page using Ajax and insert them into the current page, providing a nice way of lighting up a web application with an ‘Ajax’ feel whilst easily maintaining non-ajax support.

Tutorial for getting started with ASP.NET, WCF and jQuery

June 15th, 2011

I have been doing some work lately with jQuery, WCF, HTML5 and ASP.NET and it’s been actually pretty fun challenging and fun. I’ve gotten to tinker with quite a few new technologies that I hadn’t used before and really got to sink my teeth into jQuery and some of the cool new features that HTML5 has to offer (like local storage and offline capabilities).

When starting out with my recent project I had to pull from various resources to learn what these tools were capable of and how I could fit them all together. And while it doesn’t get into the HTML5 aspects of my project this article on creating a simple task list with ASP.NET, WCF and jQuery would have been very helpful to me in the beginning.

While the article is only Part 1 in a series, I think it will get you going in the right direction and will show you some of the power that you have on the client with the new jQuery data templates.  I must say that with the introduction of these templates you can truly offload a large amount of your logic down to the client which will provide for a much better (and faster) user experience.

Anyway, check out the article.  It’s short, to the point and offers the source code as a download too!

Use ASP.NET and DotNetZip to Create and Extract ZIP Files

February 16th, 2011

I recently came across this article from Scott Mitchell, that shows how to use DotNetZip to create and extract ZIP files in an ASP.NET application, and covers advanced features like password protection and encryption.

The article details all that you can do with the feature-rich, free, open source ZIP implementation for .NET - DotNetZip. Using DotNetZip and a dash of .NET code you can:

  • Create a new ZIP file and add one or more files or folders,
  • Read the contents of a ZIP file,
  • Extract all (or some) of the contents of a ZIP file to a specified folder,
  • Use advanced ZIP file format features, such as encrypting the contents of the ZIP and protecting them with a password.

This is definitely something that will come in handy.  I’ve tried working with zip files in the past and it has never been this easy.  Dealing with a ZIP file is definitely something that you will need to do at some point if you program long enough.  With this article, it will definitely be something that you won’t bang your head against the wall trying to accomplish!

Ways to optimize your ASP.NET applications

February 2nd, 2009

I’ve spent quite a bit of time recently optimizing our ASP.NET application to help improve performance.  After spending time analyzing the code and the database for inefficiencies, it was clear that something needed to be done to minimize the data (reduce the request size) that was being delivered to each user for each page request.

After lots of reading and testing, I ended up reducing the size of most of our page requests by as much as 95% in some instances. In the next few posts I will go over, in detail, how you can use the following steps to optimize your ASP.NET (and non-ASP.NET) web applications with only a little bit of work:

  • Enabling and configuring HTTP compression in IIS6
  • Enabling content expiration for static content (graphics, css files, JavaScript files, etc) in IIS6
  • Changing your application to store ViewState in the session rather than in each page
  • Configuring Telerik’s Radcontrols to work as efficiently as possible

Setting up SSL with IIS for ASP.NET

January 12th, 2009

On my project at work I recently had to deal with securing our IIS 6 website with SSL and forcing that no non-secure requests would be honored.

require-ssl

What I quickly found was that IIS didn’t offer a way to automatically redirect any non-secure requests to a secure version of the same page, or some other page (i.e. http://www.yoursite.com/login.aspx redirect automatically to https://www.yoursite.com/login.aspx).

Luckily after spending a good amount of time Googling I found this post that involves a handy tip that you can use to change the custom error page for error 403;4 (the one displayed when you try to view the non-secure site).  I won’t re-state everything from his blog post, but it definitely has everything you need to get around this problem if you’re in the same boat.

JavaScript Reporting Services ReportViewer control error fix

December 8th, 2008

I have been going back and forth banging my head against a wall trying to fix a JavaScript error that was happening on my Reporting Services ReportViewer control when the View Report button is clicked.  The error was a JavaScript error and seemed to be related to using something AJAX related on the same page as the ReportViewer control, but it took me a while to figure out what it was and fix it.  All of the problems I saw on the web related to using either an AJAX update panel or one of the extenders in the AJAX Control Toolkit.  Unfortunately for me I wasn’t using either one of them so trying to figure this one out was tricky.

The specific JavaScript error was:

Microsoft JScript runtime error: ‘this._postBackSettings.async’ is null or not an object

My page was setup where I had a master page with an AJAX menu on it (Radmenu to be specific).  In order to use the Radmenu you need a ScriptManager object.  Other than the menu, I didn’t have any AJAX related controls on either the master page or the content page.

What I eventually figured out was that my report pages (which use a base class) needed to disable partial rendering.  To do this, you must do it in your page’s init event.  If you do it after the init you’ll get an invalid operation exception.  Here’s the code in the base class (you can put this in your code behind if you’re not using a base class):

    Private Sub Page_Init1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
 
        ' Make sure this page has a master page
        If Not IsNothing(Me.Master) Then
 
            Dim masterScriptManager As ScriptManager
            masterScriptManager = CType(Master.FindControl("MasterScriptManager"), ScriptManager)
 
            ' Make sure our master page has the script manager we're looking for
            If Not IsNothing(masterScriptManager) Then
 
                ' Turn off partial page postbacks for this page
                masterScriptManager.EnablePartialRendering = False
            End If
 
        End If
 
    End Sub

Just in case others stumble across this and are trying to solve their problem, here are some of the links I landed on when trying to solve the problem:

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!

FormView not retaining values when server-side validation fails

July 13th, 2007

I recently spent quite a bit of time trying to figure out why my FormView wasn’t retaining values after some of my custom server-side validation failed in my business logic layer.  I kept seeing that you just had to set KeepInEditMode = true (or KeepInInsertMode if you’re doing an insert) and that would take care of it.

Well, after a lot of trial and error and hours googling and reading messages forums I finally found the answer.  Before I go into what I needed to do to fix it, I’ll give a little bit of background.

I am using a FormView with an ObjectDataSource.  The ObjectDataSource maps to our business logic layer for the Select, Insert and Update methods.  Initially, the insert and update methods were returning an “envelope” object that contained a list of any BLL errors that were caught from server-side validation.

Everything worked fine using this approach except for retaining the values in the FormView that the user had changed before the last insert or update action.  I couldn’t for the life of me figure out why the FormView kept re-initializing the data even though I didn’t actually save anything to the DB in the BLL.

Well, it turns out that my approach of returning an envelope just wasn’t cutting it.  What I had to do was throw an exception from the BLL class back to the calling page so that the FormView’s ItemInserted and ItemUpdated events would keep the old data around.

Here’s what I ended up with…

If Not e.Exception Is Nothing Then
     e.ExceptionHandled = True
     e.KeepInEditMode = True           

     CType (Master, Site).ShowErrorPopup("Errors:", e.Exception.InnerException.Message)
End If

If it doesn’t see an exception, it thinks that the operation before (insert or update) was successful and it doesn’t keep the old data around.  It goes and reinitializes the FormView with the select again.

So in my BLL I simple got rid of my envelope that I was passing back and built a new exception.  It’s use is as follows:

Dim brokenRules As New StringBuilder
brokenRules = ValidationManager.ConsolidateBrokenRules(oneEntity.BrokenRulesList, brokenRules)
Throw New Common.EntityValidationException(brokenRules.ToString)

The new exception paired up with a class in the Master Page to display the errors to the user (via the AJAX Control Toolkit’s Modal Popup Extender ) took care of my problems.

Comments (from previous blog):

Cheers – have been pulling my hair out for a couple of days on this. Works like a dream. I couldn’t find the KeepInInsertMode/KeepInEditMode properties at first as I was looking in the ObjectDataSource Inserted function and not the FormView function. DOH.
cheers
Russell

I’m using a 3 tiered approach with an Oracle DB with a each table having an a unique UPDATED field which is used for concurrency checking. My problem was if the formview tried to update the data (& a conncurrency check stopped the update) my BLL would return 0 rows affected – but this also led the Formview to throwing away the new values…

So I came to the same conclusion as you, I discovered the if I threw a fake “Concurrency” exception back from my BLL the objectdata source, I could trap the exception in the formview itemupdated event & keep the new values…

I came across your “soultion” while trying to see if I was missing some easy way to stop the formview refreshing its contents from the itemupdated event – doesn’t seem you can unless there was an exception… oh well – seems I’ll stick to this method… thanks for the confirmation!