July 30, 2010

Filter data in a WPF ListBox

0 comments


In this post, I will demonstrate how to filter data from the list box in WPF. To do this, I am using LINQ to Collections.

Assuming you have a WPF project, add a class file ‘Employee’

class Employee
{
  public int EmpNo { get; set; }
  public string EmpName { get; set; }
}

In the MainWindow.Xaml, add the following code:

<Grid>
<ListBox Height="298" HorizontalAlignment="Left" Margin="80,55,0,0"
Name="lstEmpData" VerticalAlignment="Top" Width="252">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding EmpName}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="60,18,0,0"
Name="textBlock1" Text="Search Name"
VerticalAlignment="Top" Width="134" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="208,13,0,0"
Name="txtNameToSearch" TextChanged="txtNameToSearch_TextChanged"
VerticalAlignment="Top" Width="202" />
</Grid>


The xaml code shown above defines a ListBox which has ItemTemplate set to TextBlock. This TextBlock is bound with EmpName. The TextBox(txtNameToSearch) is used to define filter values.

In the Window_Loaded event, add the following code

ObservableCollection<Employee> lstEmployee =
new ObservableCollection<Employee>();

private void Window_Loaded(object sender, RoutedEventArgs e)
{
lstEmployee.Add(new Employee() { EmpNo = 1001, EmpName = "Mahesh" });
lstEmployee.Add(new Employee() { EmpNo = 1002, EmpName = "Amit" });
lstEmployee.Add(new Employee() { EmpNo = 1003, EmpName = "Vaibhav" });
lstEmployee.Add(new Employee() { EmpNo = 1004, EmpName = "Ashwin" });
lstEmployee.Add(new Employee() { EmpNo = 1005, EmpName = "Prashant" });
lstEmployee.Add(new Employee() { EmpNo = 1006, EmpName = "Vinit" });
lstEmployee.Add(new Employee() { EmpNo = 1007, EmpName = "Abhijit" });
lstEmployee.Add(new Employee() { EmpNo = 1008, EmpName = "Pankaj" });
lstEmployee.Add(new Employee() { EmpNo = 1009, EmpName = "Kaustubh" });
lstEmployee.Add(new Employee() { EmpNo = 1010, EmpName = "Mohan" });

lstEmpData.ItemsSource = lstEmployee;
}

The code shown above defines an Employee collection bound to the ListBox.

Now in the TextChanged event of the TextBox, add the following LINQ code which filters data from the collection and binds the result to the Listbox:

private void txtNameToSearch_TextChanged(object sender,
TextChangedEventArgs e)
{
  string txtOrig = txtNameToSearch.Text;
  string upper = txtOrig.ToUpper();
  string lower = txtOrig.ToLower();

  var empFiltered = from Emp in lstEmployee
  let ename = Emp.EmpName
  where
   ename.StartsWith(lower)
   || ename.StartsWith(upper)
   || ename.Contains(txtOrig)
   select Emp;

  lstEmpData.ItemsSource = empFiltered;
}
 
OUTPUT
image

July 29, 2010

Calculate the Size of a Folder/Directory using .NET 4.0

2 comments


.NET 4.0 introduces 7 New methods to Enumerate Directory and Files in .NET 4.0. All these methods return Enumerable Collections (IEnumerable<T>), which perform better than arrays. We will be using the DirectoryInfo.EnumerateDirectories and DirectoryInfo.EnumerateFiles in this sample which returns an enumerable collection of Directory and File information respectively.

Here’s how to calculate the size of a folder or directory using .NET 4.0 and LINQ. The code also calculates the size of all sub-directories.

C#

using System;
using System.Linq;
using System.IO;

namespace ConsoleApplication3
{
  class Program
  {
    static void Main(string[] args)
    {
      DirectoryInfo dInfo = new DirectoryInfo(@"C:/Articles");
      // set bool parameter to false if you
      // do not want to include subdirectories.
      long sizeOfDir = DirectorySize(dInfo, true);

      Console.WriteLine("Directory size in Bytes : " +
      "{0:N0} Bytes", sizeOfDir);
      Console.WriteLine("Directory size in KB : " +
      "{0:N2} KB", ((double)sizeOfDir) / 1024);
      Console.WriteLine("Directory size in MB : " + 
      "{0:N2} MB", ((double)sizeOfDir) / (1024 * 1024));

      Console.ReadLine();
    }

    static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
    {
       // Enumerate all the files
       long totalSize = dInfo.EnumerateFiles()
                    .Sum(file => file.Length);

       // If Subdirectories are to be included
       if (includeSubDir)
       {
          // Enumerate all sub-directories
          totalSize += dInfo.EnumerateDirectories()
                   .Sum(dir => DirectorySize(dir, true));
       }
       return totalSize;
    }
  }
}

VB.NET 10.0 (converted using online tool)

Imports System
Imports System.Linq
Imports System.IO

Module Module1

Sub Main()
   Dim dInfo As New DirectoryInfo("C:/Articles")
   ' set bool parameter to false if you
   ' do not want to include subdirectories.
   Dim sizeOfDir As Long = DirectorySize(dInfo, True)

   Console.WriteLine("Directory size in Bytes : " & _
    "{0:N0} Bytes", sizeOfDir)
   Console.WriteLine("Directory size in KB : " & _
    "{0:N2} KB", (CDbl(sizeOfDir)) / 1024)
   Console.WriteLine("Directory size in MB : " & _
    "{0:N2} MB", (CDbl(sizeOfDir)) / (1024 * 1024))

   Console.ReadLine()
End Sub

Private Function DirectorySize(ByVal dInfo As DirectoryInfo, _
   ByVal includeSubDir As Boolean) As Long
   ' Enumerate all the files
   Dim totalSize As Long = dInfo.EnumerateFiles() _
     .Sum(Function(file) file.Length)

   ' If Subdirectories are to be included
   If includeSubDir Then
     ' Enumerate all sub-directories
     totalSize += dInfo.EnumerateDirectories() _
      .Sum(Function(dir) DirectorySize(dir, True))
   End If
   Return totalSize
End Function

End Module


OUTPUT

I got the following output after running this code.

image

To confirm that the code worked as expected, I opened Windows Explorer > C Drive > Right clicked the folder > Properties. Here is the screenshot that matches the output we got from our code

image

July 28, 2010

Compare two List<string> using LINQ

0 comments


In this post, we will see how to compare two List<string> and list the elements found in one List<string> but not in the other. We will be using the Enumerable.Except method

C#

static void Main(string[] args)
{
List<string> lstOne =
new List<string>() { "Jim", "Jack", "Kate", "Nope" };

List<string> lstTwo =
new List<string>() { "Jack", "Nope", "Jim" };

IEnumerable<string> lstNew = null;

// Compare two List<string> and display items of lstOne not in lstTwo
lstNew = lstOne.Except(lstTwo, StringComparer.OrdinalIgnoreCase);

PrintList(lstNew);
Console.ReadLine();
}

static void PrintList(IEnumerable<string> str)
{
foreach (var s in str)

Console.WriteLine(s);
Console.WriteLine("-------------");
}

OUTPUT

image

Read some more tips in my article over here Some Common Operations using List<string>

July 27, 2010

Bind Enum to a WPF ListBox using ObjectDataProvider

0 comments


In programming languages, Enumeration has a specific role for storing values. The Enum.GetValues() method retrieves an array of the values of the constants in an Enum. Let us see how to use this method and bind an Enumeration to a WPF ListBox using the ObjectDataProvider.

Create a WPF project with the name of WPF_EnumBinding. In the WPF Project, open the MainPage.Xaml.cs and write an enumeration as shown below:

public enum Department
{
IT,
System,
HRD,
Accts,
Transport
}

Since ‘Enum’ is defined in mscorlib assembly, it is referred in the Xaml code shown below. The ObjectDataProvider is used to bind the Enumeration with the Xaml. The namespace under which enumeration i.e. WPF_EnumBinding is declared, is also referred in the Xaml. The Xaml code is as below:

<Window x:Class="WPF_EnumBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:System;assembly=mscorlib"
xmlns:data="clr-namespace:WPF_EnumBinding"
Title="MainWindow" Height="350" Width="525">
<
Window.Resources>
<
ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type src:Enum}" x:Key="dname">
<
ObjectDataProvider.MethodParameters>
<
x:Type TypeName="data:Department"></x:Type>
</
ObjectDataProvider.MethodParameters>
</
ObjectDataProvider>
</
Window.Resources>
<
Grid>
<
ListBox Height="294" HorizontalAlignment="Left"
Margin="32,17,0,0" Name="lstEnum" VerticalAlignment="Top"
Width="222" DataContext="{Binding Source={StaticResource dname}}"
ItemsSource="{Binding}">
</
ListBox>
</
Grid>
</
Window>

OUTPUT

image

July 26, 2010

List Common Elements between two List<string>

0 comments


Here’s a simple post that shows how to list common elements between two List<Strings>. Use the Enumerable.Intersect method

C#

class Program
{
static void Main(string[] args)
{
List<string> lstOne =
new List<string>() { "Jim", "Jack", "Kate", "Nope" };
List<string> lstTwo =
new List<string>() { "Jack", "Nope", "Jim" };
IEnumerable<string> lstNew = null;

// Compare two List<string> and display common elements
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase);
PrintList(lstNew);

Console.ReadLine();
}

static void PrintList(IEnumerable<string> str)
{
foreach (var s in str)
Console.WriteLine(s);
Console.WriteLine("-------------");
}
}

VB.NET


    Sub Main()
Dim lstOne As New List(Of String)() _
From {"Jim", "Jack", "Kate", "Nope"}
Dim lstTwo As New List(Of String)() _
From {"Jack", "Nope", "Jim"}
Dim lstNew As IEnumerable(Of String) = Nothing

' Compare two List<string> and display common elements
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
PrintList(lstNew)

Console.ReadLine()
End Sub

Private Sub
PrintList(ByVal str As IEnumerable(Of String))
For Each s In str
Console.WriteLine(s)
Next s
Console.WriteLine("-------------")
End Sub

OUTPUT


image


Read some more tips in my article over here Some Common Operations using List<string>

July 25, 2010

Web Camp Training Kit - Recent Microsoft Web Camps Presentations, Demos and Labs

0 comments


Microsoft recently released the July 2010 release of the Web Camps Training Kit.

The Web Camp Training kit includes all the content presented around the world at the recent Web Camps events; presentations, demos, labs and more. Inside the new kit you’ll find content that covers the following technologies:

  • ASP.NET MVC 2
  • ASP.NET 4 Web Forms
  • jQuery
  • Entity Framework
  • Visual Studio 2010

Download the Web Camp Training Kit

July 24, 2010

Understanding YSlow – A Firebug Extension to Analyze and Improve Webpage Performance

2 comments


Yahoo’s YSlow is a ‘must have’ Firefox add-on and is an extension (for performance) to the Firebug tool. YSlow analyzes web pages and suggests ways to improve the performance of web pages based on a set of rules for high performance web pages laid out by Yahoo. There are 34 rules laid out by Yahoo and YSlow is capable of testing 22 of them.

The 22 rules testable by YSlow and as listed in the YSlow user guide, are:

  1. Minimize HTTP Requests
  2. Use a Content Delivery Network
  3. Add an Expires or a Cache-Control Header
  4. Gzip Components
  5. Put StyleSheets at the Top
  6. Put Scripts at the Bottom
  7. Avoid CSS Expressions
  8. Make JavaScript and CSS External
  9. Reduce DNS Lookups
  10. Minify JavaScript and CSS
  11. Avoid Redirects
  12. Remove Duplicate Scripts
  13. Configure ETags
  14. Make AJAX Cacheable
  15. Use GET for AJAX Requests
  16. Reduce the Number of DOM Elements
  17. No 404s
  18. Reduce Cookie Size
  19. Use Cookie-Free Domains for Components
  20. Avoid Filters
  21. Do Not Scale Images in HTML
  22. Make favicon.ico Small and Cacheable

Assuming you have downloaded YSlow and installed it in Firefox, let us quickly run the YSlow tool on a website and then dissect the results to understand the tool better. Once installed, the YSlow tool can be invoked from Firefox. Just open your web page in Firefox and click the YSlow tool (lower right corner of the Firefox status bar). Here are the results of running YSlow on a sample webpage from my site.

image

As you can observe, the results consists of 4 Tabs – Grade, Components, Statistics and Tools. The screenshot also shows the rulesets applied as well as the the Grade received by the website. Let us understand these terms one by one.

Rulesets

Let us first understand the rulesets that YSlow uses to grade pages (we will understand grading shortly). There are 3 predefined rulesets that you can choose to apply on a webpage:

YSlow(V2) - This ruleset contains the 22 rules listed in the beginning of this article.

Classic (V1) - This ruleset contains rules from 1 to 13.

Small Site or Blog - This ruleset contains 14 rules that are applicable to
small websites or blogs. These are Rule 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 17, 20, 21 and 22.

In addition to these rulesets, you can also create your own set of rules. For more information on creating custom set of rules, read Customizing Rulesets.

Grade

‘Grade’ is one of the four tabs as shown below and depicts a report card on our page’s performance.

image

YSlow examines all the components of a webpage and then grades the web page based on one of three predefined ruleset or even a custom-defined ruleset, we discussed about in the Rulesets section. How the grading works, is when YSlow analyzes a webpage, it deducts points for every breach of a rule and then applies a grade to each rule. Here’s a sample screenshot of the grades received by the webpage for each rule and the suggestion for improvement, shown on the right.

image

Then a final grade is computed (in our case ‘B’) by summing up the values of the points gained for each rule, weighted by the rule's importance.

Components

Components is the second of the four tabs as shown below:

image

The Component tab shows the various components on the page (javascript, css etc) and information related to each component (click the ‘+’ icon or ‘Expand All’ link). This will give you an idea which component takes more time to load and you can consider to gzip it and improve performance.

Statistics

Statistics is the third tab and provides a graphical representation of the number of HTTP requests made to the server and the total weight of the page in kilobytes for both Empty Cache and Primed Cache scenarios.

image

The Empty Cache scenario is when the browser makes the first request to the page and the Primed Cache scenario is when the browser has a cached version of the page. In a Primed Cache scenario, the components are already in the cache, so this will reduce the number of HTTP requests and thereby the weight of the page.

Tools

Tools is the last tab and contains a list of various tools that YSlow suggests to run on the webpage resources (images, JavaScript, CSS) to improve the performance of the page.

image

With this, I hope this quick guide explained what YSlow is all about and how you can use it to analyze and improve the performance of your web pages. I am going to apply this tool on my web pages and follow the recommendations made by this tool to improve performance. I hope you do the same for your web pages too! You can read more about YSlow in the YSlow User Guide.

Link to Download YSlow

 

Copyright 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal