Monday, December 6, 2010

Use jQuery and ASP.NET AJAX to build a client side Repeater

There was some interesting discussion on Matt Berseth‘s blog recently, regarding methods for building and displaying markup on the client side. Though I haven’t posted any examples here before, rendering markup on the client is a technique that I use often and recommend.
By sending only data to the client, you can profoundly reduce the size of what you send and see a substantial increase in performance. You also allow yourself the ability to easily add features like light-weight sorting and paging on the client. This can not only improve your users’ experience, but reduce server load and bandwidth requirements.
To that end, I’m going to walk you through these four steps to effectively implementing a client side Repeater, using ASP.NET AJAX and jQuery:
  • Create an RSS Reader page method to return JSON data to the client.
  • Call that page method with jQuery.
  • Use the returned data to build a table on the client side.
  • Improve upon the table creation with a templating plugin.

Creating an RSS reader page method

Because web browsers prohibit cross-domain AJAX functionality, displaying items from an external RSS feed is a good real-world example. To overcome this limitation, our first step is to write a local server side proxy to relay that feed data to the client.
A web service or page method is ideal for this task. I would typically use an ASMX web service, but let’s use a page method here. It’s useful to illustrate how nearly interchangeable the two really are.
[WebMethod]
public static IEnumerable GetFeedburnerItems(int Count)
{
  XDocument feedXML = 
    XDocument.Load("http://feeds.encosia.com/Encosia");
 
  var feeds = 
    from feed in feedXML.Descendants("item")
    select new
    {
      Date = DateTime.Parse(feed.Element("pubDate").Value)
                     .ToShortDateString(),
      Title = feed.Element("title").Value,
      Link = feed.Element("link").Value,
      Description = feed.Element("description").Value
    };
 
  return feeds.Take(Count);
}
This page method uses LINQ to parse a few details out of the RSS feed, create an anonymous type with that data, and then return a collection of those anonymous types. By selecting only the data we’re interested in on the server side, we can minimize the traffic between client and server.
In response to my recent deferred content loading post, several of you asked how to limit the results, so I added that this time around. The Take extension method performs this task for us.

Calling the page method with jQuery

On the client side, the first thing we need to do is initiate a request to the page method. We’ll do this with jQuery’s ajax() method:
$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/GetFeedburnerItems",
    // Pass the "Count" parameter, via JSON object.
    data: "{'Count':'7'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      BuildTable(msg.d);
    }
  });
});
When the page loads, this function will perform an AJAX request to our page method, requesting information on the first seven feed items. When the response arrives, a JavaScript function will be called with the response data.
If you are unfamiliar with this jQuery syntax, I have covered it in more detail in two previous posts: Using jQuery to directly call ASP.NET AJAX page methods and Three mistakes to avoid when using jQuery with ASP.NET AJAX.

Building and displaying the table

The page method’s JSON response is going to be similar to this:
[{"Date":"6/5/2008",
  "Title":"3 mistakes to avoid when using jQuery with ASP.NET AJAX",
  "Link":"http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/",
  "Description":"Three common problems that I've seen when using jQuery with ASP.NET AJAX, their underlying causes, and simple solutions to them."},
 
 {"Date":"5/29/2008",
  "Title":"Using jQuery to directly call ASP.NET AJAX page methods",
  "Link":"http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/",
  "Description":"An example of how to use jQuery to call an ASP.NET AJAX page method, without using a ScriptManager."}]
The anonymous type in our LINQ query comes through very nicely. The properties that we designated in the page method become keys in an associative array, making it easy for us to work with the data.
To build a table of this data on the client side, we can loop through each element, construct an HTML string, and then assign that string to a container’s innerHTML property:
function BuildTable(msg) {
  var table = '<table><thead><tr><th>Date</th><th>Title</th><th>Excerpt</th></thead><tbody>';
 
  for (var post in msg)
  {
    var row = '<tr>';
 
    row += '<td>' + msg[post].Date + '</td>';
    row += '<td><a href="' + msg[post].Link + '">' + msg[post].Title + '</a></td>';
    row += '<td>' + msg[post].Description + '</td>';
 
    row += '</tr>';
 
    table += row;
  }
 
  table += '</tbody></table>';
 
  $('#Container').html(table);
}
If you think that code looks ugly, that’s because it is. While it works great, I would not recommend this implementation. It will be difficult for you to maintain, and you’ll hope that anyone else forced to maintain it doesn’t know where you live.

Improving the situation with templating

The reason the former code is so ugly is that the presentation and logic are not separated. Even though this is all on the client side, separation of concerns is still an important goal to keep in mind.
To achieve separation, what we really need is a templating solution. As it turns out, there’s a great jQuery plugin called jTemplates, which is perfect for this application.
Using jTemplates, we can create a simple HTML template like this one:
<table>
  <thead>
    <tr>
      <th>Date</th>
      <th>Title</th>
      <th>Excerpt</th>
    </tr>
  </thead>
  <tbody>
    {#foreach $T.d as post}
    <tr>
      <td>{$T.post.Date}</td>
      <td><a href="{$T.post.Link}">{$T.post.Title}</a></td>
      <td>{$T.post.Description}</td>
    </tr>
    {#/for}
  </tbody>
</table>
Since we’re focusing on disentanglement, this template belongs separate file. If we embedded in our JavaScript, we’d be taking two steps forward and one step back. In this case, I saved it as RSSTable.htm.
Note: I originally used the suffix .tpl for templates, but found that some versions of IIS will block access to them unless *.tpl is explicitly added as a valid filetype.
With the HTML template created, we can use a couple of jTemplates’ methods to apply the template to the container and then render the page method’s return.
function ApplyTemplate(msg) {
  // This method loads the HTML template and
  //  prepares the container div to accept data.
  $('#Container').setTemplateURL('RSSTable.htm');
 
  // This method applies the JSON array to the 
  //  container's template and renders it.
  $('#Container').processTemplate(msg);
}
The rendered result will be identical to the previous, manual method, but the code is much cleaner. At this level of abstraction, I consider this method to be very similar to a client side Repeater.

Conclusion

This is a powerful optimization technique. Identifying overburdened UpdatePanels and replacing them with something like this yields massive performance increases. An order of magnitude isn’t uncommon, in my experience.
One of my sites, WinScrabble.com, was suffering from poor performance due to its primary feature relying on partial postbacks. Because the page was simple and had ViewState disabled, I thought the UpdatePanel would have a relatively minimal impact.
You wouldn’t believe just how wrong I was.
When I removed the UpdatePanel and replaced it with this technique, changing none of the underlying algorithms, requests for 7-8 letter searches ran over 400% faster. I have no doubt that you’ll be able to realize similar improvements in your projects.
In upcoming posts, I’ll go into detail about how to add some client side embellishments: Client side sorting, light-weight paging, and using CSS to improve upon the presentation. So, if you aren’t already subscribed to receive updates via RSS or Email, be sure to do so today.

Download Source From: http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/

ASP.NET Menu with jQuery Superfish

Choosing the right type of menu for a website is not easy at all. The ASP.NET Menu Control is definitely NOT a good starting point due to the horrendous markup it renders, nor is it good for SEO because of the Markup/Content ratio, neither can it be easily styled.
Of course there is the CSSFriendly Control Adapters project that started back in 2006, which made the the ASP.NET Menu (and many other ghastly markup rendering controls) render beautiful <div> based markup. In the case of the Menu it rendered <div> and <ul>-<li> type markup which is probably the most widely spread technique used for creating menus known to mankind.

You need use the same sort of markup for your server side ASP.NET Menu control like you’ve used with the standard CssFriendly Menu Adapter, and make the JavaScript call needed to set the Superfish plugin up.
view sourceprint?
01.<asp:Menu ID="mnu" runat="server" CssSelectorClass="myMenu">
02.    <Items>
03.        <asp:MenuItem NavigateUrl="#" Text="Item1">
04.            <asp:MenuItem NavigateUrl="#" Text="Sub1 Item1"></asp:MenuItem>
05.            <asp:MenuItem NavigateUrl="#" Text="Sub1 Item2"></asp:MenuItem>
06.            <asp:MenuItem NavigateUrl="#" Text="Sub1 Item3"></asp:MenuItem>
07.            <asp:MenuItem NavigateUrl="#" Text="Sub1 Item4"></asp:MenuItem>
08.        </asp:MenuItem>
09.        <asp:MenuItem NavigateUrl="#" Text="Item2">
10.            <asp:MenuItem NavigateUrl="#" Text="Sub2 Item1"></asp:MenuItem>
11.            <asp:MenuItem NavigateUrl="#" Text="Sub2 Item2"></asp:MenuItem>
12.            <asp:MenuItem NavigateUrl="#" Text="Sub2 Item3">
13.                <asp:MenuItem NavigateUrl="#"
14.                              Text="Sub2 Item3 Item1 and some
15.                                    very very very long text">
16.                </asp:MenuItem>
17.                <asp:MenuItem NavigateUrl="#" Text="Sub2 Item3 Item2"></asp:MenuItem>
18.                <asp:MenuItem NavigateUrl="#" Text="Sub2 Item3 Item3"></asp:MenuItem>
19.            </asp:MenuItem>
20.        </asp:MenuItem>
21.        <asp:MenuItem NavigateUrl="#" Text="Item3">
22.            <asp:MenuItem NavigateUrl="#" Text="Sub3 Item1"></asp:MenuItem>
23.            <asp:MenuItem NavigateUrl="#" Text="Sub3 Item2"></asp:MenuItem>
24.            <asp:MenuItem NavigateUrl="#" Text="Sub3 Item3"></asp:MenuItem>
25.        </asp:MenuItem>
26.        <asp:MenuItem NavigateUrl="#" Text="Item4"></asp:MenuItem>
27.    </Items>
28.</asp:Menu>
The necessary JavaScript:
view sourceprint?
01.<script type="text/javascript">
02.    // initialize plugins
03.    $(function() {
04.        $("ul.sf-menu").supersubs({
05.            minWidth: 13,
06.            maxWidth: 40,
07.            extraWidth: 5
08.        }).superfish();
09.    });
10.</script>
And the outcome looks like …


View More Detail & Source Code : http://blog.dreamlabsolutions.com/post/2009/08/09/ASPNET-Menu-with-jQuery-Superfish.aspx

Store and Display Images from MS Access Database Using C#



 
using System.Data.OleDb;
OleDb is used to connect the web site forms with MS Access Database using Microsoft.Jet.OLEDB.4.0
 
using System.IO;
IO is used to create the memory stream variable that can store the binary format of the image content.
 
C# Code to Upload Image to MS Access Database:
 
int imageSize;
string imageType; Stream imageStream;
// Gets the Size of the Image
imageSize = fileImgUpload.PostedFile.ContentLength;
 
// Gets the Image Type
imageType = fileImgUpload.PostedFile.ContentType;
 
// Reads the Image stream
imageStream = fileImgUpload.PostedFile.InputStream;
 
byte[] imageContent = new byte[imageSize]; int intStatus; intStatus = imageStream.Read(imageContent, 0, imageSize);
 
Connection string to connect the ASP.Net 2.0 web application with MS Access Database:

Download & View More Detail : http://programming.top54u.com/post/Store-and-Display-Images-from-MS-Access-Database-Using-C-Sharp.aspx

Saturday, December 4, 2010

WPF Sample Series – Using WPF Binding StringFormat Property with Nullable Types

One of the great features introduced in .NET 3.5 Framework Service Pack 1 is the BindingBase StringFormat property.  When used in a data binding expression the StringFormat property replaces most IValuteConverters that were used for formatting of values in  WPF 3.0 & WPF 3.5 applications.
Here are two examples of the StringFormat property in action formatting a currency field:
<TextBox Text="{Binding Path=Salary, StringFormat=c}" />

<TextBox Text="{Binding Path=Salary, StringFormat=\{0:c\}}" />

Nullable Type in the Mix

If you are binding to a non-Nullable data type the above will work just fine.
However, if you are binding to a Nullable data type the above will not work.
This breaks down when a UI Control like a TextBox as a value and the user clears the TextBox and press TAB.  The default implementation of StringFormat will attempt to set the Target Property to an empty string which in the the case of a Nullable Decimal property will cause the following or similar data binding exception.  The below data binding exception can be viewed in the Visual Studio Output window.
Exception
 
System.Windows.Data Error: 7 : ConvertBack cannot convert value ” (type ‘String’). BindingExpression:Path=Age; DataItem=’Customer’ (HashCode=31884011); target element is ‘TextBox’ (Name=”); target property is ‘Text’ (type ‘String’) FormatException:’System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)’

TargetNullVaue to the Rescue

In the above example, the exception is thrown because of a type mismatch.  In WPF 3.0 and 3.5 I had a set of Nullable ValueConverters for my applications to handle this problem.
Another great feature introduced in .NET 3.5 Framework Service Pack 1 is the BindingBase TargetNullValue property.  This property can be used to handled the type mismatch problem when converting an empty string from a TextBox to Nothing (null) when the binding pipeline sets the target Nullable property.
Let’s have a look at the two below TextBoxes.
<TextBox
    Grid.Column="1"
    Grid.Row="1"
    Margin="0,11,11,11"
    VerticalAlignment="Top"
    Text="{Binding Path=NumberOfComputers,
            TargetNullValue={x:Static sys:String.Empty},
            StringFormat=\{0:D\}}" />

<TextBox
    Grid.Column="1"
    Grid.Row="2"
    Margin="0,11,11,11"
    VerticalAlignment="Top"
    Text="{Binding Path=Age, StringFormat=\{0:D\}}" />
These TextBoxes are both bound to Nullable properties.  The first TextBox takes advantage of the TargetNullValue property and works as expected.  The second does not.   The data binding pipeline will throw an exception when the second TextBox is changed to an empty string and it attempts to assign the value of String.Empty to the Target property.
Here is a potential problem.  If the exception gets thrown and swallowed because the code didn’t check for this, the user thinks they cleared a value but the property the TextBox is bound to never gets changed due to the exception being thrown.

How To Create Crystal Report In C#

1). Create XML File That Used In this Reports.
So,How To Create That XML File.
1). To Creating that XML Using Dataset.
2). First Fill Dataset From DataAdapter.After That there is one property WriteXMLSchema Of Dataset.In this Property write the XML FIle Name.
2). After Creating that XML File.Right Click On Project And Click On  Add New Item.While Click On that One Open Dialog Box Appear.From that Dialog Box Click On Crystal Report.That will Add One Crystal Report On your Solution.
3). After Creating Rpt File Follows That Following Steps.
1). Add Datasource Of that newly created Crystal Report And Click On Database Expert… link.











2). Click On That One Dialog Box Appear that Describe below.
 


















3). When Expand that Database files Option It will ask the Location Of that XML give.Give the location Of that XML File.


















4). After Click On Open Button This Screen Appear.From That Choose the Table that will see on that Report.



















4). All This Task Complate That Write the below code For Bind the Data To ReportViewer .
ReportDocument rdoc = new ReportDocument();
// Path Of That Report Document File In Load Function Parameter.
rdoc.Load(@”C:\Documents and Settings\xosysadmin\My Documents\Visual Studio 2005\Projects\GivingXMLToRpt\GivingXMLToRpt\Testrpt.rpt”);
// Give the Dataset Name That Assing To Report Document
rdoc.SetDataSource(ds);
// Viewer Name . ReportSource = That Report Document Object Name
crystalReportViewer1.ReportSource = rdoc;

Create Thumbnail Images In C#

A thumbnail is a small sized image. Creating a thumbnail using .NET is extremely simple. In this article, we will explore how to create a thumbnail image and display the thumbnail in our application. Follow these steps:
  1. First Add Windows Form In your Application. After that Drag & drop 1 Label ,  1 TextBox , 2 Buttons , 1 PictureBox & 1 OpenfileDialogBox Controls From Toolbox. Now change all the names of the controls that mention belowed.
  2.    1: TextBox Name = 'txtPath'
       2: 1st Button Name = 'btnOpen'
       3: 2nd Button Name = 'btnGenerate'
       4: PictureBox Name = 'picthumb' And Set Height & Width = 100,100
  3. After renaming All the controls On the ‘btnOpen’ click display the File Open dialog box and accept the selected .jpg file in the ’txtPath’ textbox.
  4.    1: private void btnOpen_Click(object sender, EventArgs e)
       2:         {
       3:             if (openFileDialog1.ShowDialog().ToString() == "OK")
       4:             {
       5:                 txtPath.Text = openFileDialog1.FileName;   
       6:             }
       7:         }
  5. Next, on the ‘btnGenerate’ click, add the following code:
  6.    1: private void btnGenerate_Click(object sender, EventArgs e)
       2:         {
       3:             Image Img = null;
       4:             Img = Image.FromFile(txtPath.Text);
       5:             Image ImgThumbs = Img.GetThumbnailImage(100, 100, null, new IntPtr());
       6:             if (ImgThumbs != null)
       7:             {
       8:                 picthumb.Image = ImgThumbs;
       9:             }   
      10:         }
    The code creates an Image object from the image supplied in the textbox. Using the Image.GetThumbnailImage(), the code then creates a thumbnail image with a size of 100*100.
    The Image.GetThumbnailImage() takes in four arguments :
       1: Width : in pixel of the thumbnail image that is to be generated
       2: Height : in pixel of the thumbnail image that is to be generated
       3: Callback : a Image.GetTumbnailImageAbort delegate to prematurely cancel execution
       4: CallbackData : of type IntPtr to represent a pointer or a handl

Download Latest Version of AJAX Control Toolkit Version 3.0

Download Latest Version of AJAX Control Toolkit Version 3.0

Latest version of AJAX Control Toolkit V 3.0 includes

New controls
This release includes three important new controls:
  • HTMLEditor
    The HTMLEditor control allows you to easily create and edit HTML content. You can edit in design mode, as a rich text editor, or in source view to edit the HTML markup directly.

  • ComboBox
    The ComboBox control provides a DropDownList of items, combined with TextBox. Different modes determine the interplay between the text entry and the list of items.
    Many thanks to Dan Ludwig for building this.

  • ColorPicker
    The ColorPicker Control Extender can be attached to any ASP.NET TextBox control. It provides client-side color-picking functionality with UI in a popup control.
    Many thanks to Alexander Turlov for building this.