Split a String Collection into Groups using LINQ

I was recently working on an interesting problem which involved splitting a string collection into groups. We had a huge collection of email addresses stored in a string array. The task was to loop the array and select 10 emails at a time and send it for processing.

Here’s some LINQ code originally shared by Eric Lippert, that can be helpful if you have a similar requirement without using a loop for grouping.

static void Main(string[] args)
{
string[] email = {"One@devcurry.com", "Two@devcurry.com",
"Three@devcurry.com", "Four@devcurry.com",
"Five@devcurry.com", "Six@devcurry.com",
"Seven@devcurry.com", "Eight@devcurry.com"};

var emailGrp = from i in Enumerable.Range(0, email.Length)
group email[i] by i / 3;

foreach(var mail in emailGrp)
SendEmail(string.Join(";", mail.ToArray()));


Console.ReadLine();
}


static void SendEmail(string email)
{
// Assuming that you have code for sending mails here
Console.WriteLine(email);
Console.WriteLine("--Batch Processed--");
}

The code above uses the LINQ GroupBy operator to group 3 email addresses at a time and send it for processing. Note that a group...by clause translates to an invocation of GroupBy.

OUTPUT

Split String Collection

Change the Background Color of jQuery Datepicker

Here’s a simple way using CSS to change the Background Color of the jQuery UI Datepicker control

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Change Background Color of jQuery UI
DatePicker(from DevCurry.com)</title>
<
link type="text/css" rel="Stylesheet"
href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/themes/
smoothness/jquery-ui.css" />

<
style type="text/css">
.ui-datepicker {
background: #333;
border: 1px solid #555;
color: #EEE;
}
</style>

<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>
<
script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/jquery-ui.min.js">
</
script>


<
script type="text/javascript">
$(function () {
$("#datepic").datepicker();
});
</script>
</
head>
<
body>
<
input id="datepic"/>
</
body>
</
html>

As you can see, all that we are doing to change the background formatting for the Datepicker is to change the .ui-datepicker CSS class, as shown below.

<style type="text/css">
.ui-datepicker {
background: #333;
border: 1px solid #555;
color: #EEE;
}
</style>

Before:

jQuery UI Datepicker Default

After:

jQuery UI Datepicker Background

Check out some more similar jQuery DataPicker Tips

ASP.NET GridView Data Caching

Continuing my ASP.NET GridView Tips and Tricks series, here’s another one that shows how to adopt a caching mechanism in the ASP.NET GridView.

When it comes to caching data in the GridView, most developers do the mistake of caching the entire page. Now if you have an ASP.NET Page with a UserControl containing a GridView, and you have enabled OutputCaching on the entire page, then the functionality will work as expected, if the GridView does not have paging enabled.

However if the GridView has paging enabled on a page that uses OutputCaching and you try to navigate through the pages, you will find that the GridView behaves erratically.

So in order to enable caching on an ASP.NET GridView, use data caching on the DataSource. Here’s how to do it using the SqlDataSource.EnableCaching and ObjectDataSource.EnableCaching property respectively:

If GridView is bound to SQLDataSource

<asp:SqlDataSource ID="objProduct" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName] FROM [Product]"
EnableCaching="true" CacheDuration="3000" >
</
asp:SqlDataSource>

As quoted in the MSDN documentation: The SqlDataSource control supports data caching. While data is cached, the Select method retrieves data from the cache rather than from the underlying database. When the cache expires, the Select method retrieves data from the underlying database, and then caches the data again.

If GridView is bound to ObjectDataSource

<asp:ObjectDataSource ID="objProduct" runat="server" 
SelectMethod="GetProduct" SelectCountMethod="GetProductCount"
EnablePaging="True" TypeName="Product"
EnableCaching="true" CacheDuration="3000" >

As quoted in the MSDN documentation: The ObjectDataSource control supports data caching. While data is cached, calls to the Select method retrieve data from the cache rather than the ObjectDataSource creating an instance of the business object and calling its data method. When the cache expires, the Select method retrieves data from the business object, and then caches the data again.

Depending on your application, this simple trick can improve the performance of your application.

Note: The HTML markup is not cached when using this technique.

Read some more GridView Tips and Tricks over here

jQuery, ASP.NET, .NET and LINQ articles Link List – November 2010

Here’s a quick wrap up of the articles published on DevCurry.com in the month of November 2010.

jQuery and JavaScript Articles

Rounding Numbers in JavaScript - A very common question while dealing with Math methods in JavaScript is to round numbers. JavaScript provides 3 rounding methods: round(), ceil() and floor()

jQuery UI 1.8.6 Released - jQuery UI 1.8.6 is released. This update officially supports jQuery 1.4.3 and IE 9 and contains bug fixes and enhancements to jQuery UI Core, the Widget Factory, the Mouse widget and the Position utility as well.

Get Selected Items From DropDown control using jQuery - Here’s a very simple way to get the selected items in a DropDownList. Just use the jQuery change() method and write the results to a div control

Redirect a user from HTTP to HTTPS using JavaScript - Although a redirection is best done using your webserver or server-side code (for SEO purpose), here’s a simple way to redirect a page from Http to Https using JavaScript

Remove all White Space using JavaScript - Here’s how to remove all whitespaces (leading, trailing and in between) in a textbox using JavaScript

Loop Object literal using JavaScript - Here’s how to loop a JavaScript object literal and apply conditions to filter the object

Pass Function as a Parameter in JavaScript - You may at times need to pass a function as a parameter to another function. Here’s an example if you have a similar requirement

Generic Error Message in an Ajax call using jQuery - The jquery $.ajaxSetup() allows you to set default values for future Ajax requests. Here’s how to use this function to set a default generic error message

Highlight Elements on a Page using jQuery - Here’s a simple way to highlight elements on a page using jQuery. This example uses the Highlight effect of the jQuery UI library

ASP.NET Articles

Resolving ASP.NET 4.0 has not been Registered on the Web Server Error - While creating an ASP.NET Website in IIS 7 in Visual Studio 2008/2010, you may get the following error:“ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly, Press F1 for more details”. This post shows how to resolve the error.

Bind ASP.NET GridView to a Custom Object or Collection with Paging and Sorting - I find a lot of users asking how to bind a GridView to a Custom Class with Paging and Sorting enabled. Here’s some sample code that shows that.

Call ASP.NET Handler (ASHX) using JavaScript - I was working on an application which used AJAX and needed the XMLHttpRequest object to communicate with an ASP.NET Generic Handler (.ashx), which contained some server-side logic. Here’s a working prototype if you have a similar requirement

Set Width of GridView TextBox in Edit mode - To modify the width of a TextBox (inside the GridView control) when the GridView is in Edit Mode, use any of the two approaches shown in this post.

ASP.NET with Razor Syntax Beta 3 Free EBook and Tutorials - Microsoft recently released a free book and few samples to help you learn how to create dynamic Web content using ASP.NET Web Pages with the Razor syntax.

Merge GridView Header Columns - Continuing my ASP.NET GridView Tips and Tricks series, here’s another one that shows how to create a merged column in a GridView Header

Using the Deployment retail=true attribute - ASP.NET Settings - One of the most common errors while deploying ASP.NET websites into a production environment is to leave the Trace and Debug enabled or leave the custom errors attribute disabled.

Render Dynamic MetaTags in ASP.NET Page in Separate Lines – This post shows how to configure your code as that ASP.NET generate meta tags on separate lines.

LINQ and other .NET articles

Programmatically find CLR version for a .NET assembly - If you have to programmatically determine the CLR version of an assembly it was compiled against, then use the Assembly.ImageRuntimeVersion property as shown in this article

Rewrite Nested ForEach Loop in LINQ – Loop through two string array's of the same length without writing a foreach, using LINQ

List all .NET Attributes in the Loaded Assemblies - Here’s how to list all the .NET Attributes in the loaded assemblies.

Convert Date and Time to UTC - The TimeZoneInfo class in .NET contains two very useful methods called ConvertTimeToUTC() that converts the current date and time to UTC and ConvertTimeFromUTC() that converts a UTC to the time in a specified time zone.

F# November 2010 CTP available - The F# November 2010 CTP provides all the tools and resources needed to develop applications with the F# programming language

Check Database connection using C# or VB.NET - As a programmer, one of the most common tasks in your application is to connect to the database. Here’s a very simple way to check your database connection before you start any task or use this as a service to check the connection and pause tasks if the connection breaks.

Determine if your Laptop is Running on battery using C# or VB.NET - Here’s some code to programmatically find out if your laptop is currently running on battery power

Other Articles

Business Intelligence in SharePoint 2010 - Microsoft recently released a cool poster that gives an overview of the tools for Business Intelligence (BI) in SharePoint 2010.

USB 3.0 Support in Windows 7 - Did you know that USB 3.0 is not natively supported in Windows 7. So if you happen to plug in a USB 3.0 device and it does not get recognized, don’t be surprised! This post has some workarounds.

Share Visual Studio 2010 Layout Settings Between Machines - I would love to share my Visual Studio layout and other settings in between my two machines. Visual Studio provides just the option I need!

Render Dynamic MetaTags in ASP.NET Page in Separate Lines

I received a mail today from a DevCurry.com reader after reading my article SEO Enhancements with MetaKeywords and MetaDescription properties in ASP.NET 4.0. Her question was as follows:

In ASP.NET using code with the HTMLMeta class, we can define the HTML meta elements on an ASP.NET page. But the output is all mixed in one line. Can i separate it ?

Let me explain what she means. Here’s a sample code:

HtmlMeta metakeywrd = new HtmlMeta();
metakeywrd.Name = "keywords";
metakeywrd.Content = "add keywords here";

HtmlMeta metadesc = new HtmlMeta();
metadesc.Name = "description";
metadesc.Content = "add meta description here";

Page.Header.Controls.Add(metakeywrd);
Page.Header.Controls.Add(metadesc);

When the page renders, ASP.NET generates meta tags on the same line as shown below.

image

She wanted the meta tags generated on separate lines and I am not sure why!

Anyways the solution is to did this line of code wherever a separate line is needed.

Page.Header.Controls.Add(new LiteralControl("\n"));

Here’s the entire code again

Page.Header.Controls.Add(new LiteralControl("\n"));
HtmlMeta metakeywrd = new HtmlMeta();
metakeywrd.Name = "keywords";
metakeywrd.Content = "add keywords here";

HtmlMeta metadesc = new HtmlMeta();
metadesc.Name = "description";
metadesc.Content = "add meta description here";

Page.Header.Controls.Add(metakeywrd);
Page.Header.Controls.Add(new LiteralControl("\n"));
Page.Header.Controls.Add(metadesc);
Page.Header.Controls.Add(new LiteralControl("\n"));

image

As you can see now, the meta tags are generated on separate lines. If anyone knows a better way or knows the reason why is this really needed, I would love to hear it!

USB 3.0 Support in Windows 7

Did you know that USB 3.0 is not natively supported in Windows 7. So if you happen to plug in a USB 3.0 device and it does not get recognized, don’t be surprised!

There are however two solutions to it:

- Download and install the official drivers from the USB 3.0 manufacturer's site and Windows 7 should then recognize your USB drive.

- Alternatively, download the Windows 7 Service Pack 1 (RC). I am told that SP1 supports USB 3.0.

Business Intelligence in SharePoint 2010

Microsoft recently released a cool poster that gives an overview of the tools for Business Intelligence (BI) in SharePoint 2010. You can download the poster here

This poster gives an overview of Microsoft BI, SharePoint Server 2010 Insights and Architecture of SharePoint Server Service Applications for Business Intelligence. Here’s a sample screenshot of this poster.

image

Download the Choose a tool for business intelligence in SharePoint 2010 Poster

Highlight Elements on a Page using jQuery

Here’s a simple way to highlight elements on a page using jQuery. This example uses the Highlight effect of the jQuery UI library

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>jQuery Highlight Elements - DevCurry.com</title>
<
script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js">
</
script>
<
script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.6/jquery-ui.js">
</
script>
<
script type="text/javascript" language="javascript">
$(function () {
$("#btnHighlight").click(function () {
$("p.para").effect("highlight", {}, 4000);
});
});
</script>
</
head>
<
body>
<input id="btnHighlight" type="button"
value="Highlight Para 1 and 3" /><br /><br />
<
p id="para1" class="para">This is Para 1. This is Para 1.
This is Para 1.This is Para 1.This is Para 1.
</p>
<
p id="para2">This is Para 2. This is Para 2.
This is Para 2. This is Para 2. This is Para 2.
</p>
<
p id="para3" class="para">This is Para 3. This is Para 3.
This is Para 3. This is Para 3. This is Para 3.
</p>
</
body>
</
html>

As you can see, on the button click, we use the highlight effect on the paragraphs having the ‘para’ class. You can also checkout Click and Highlight Text in a TextBox using jQuery

image

See a Live Demo