Sunday, November 30, 2008

Paging in SQL Server 2005 using OVER

Full detail of "OVER" can be found on following link:

Following is the code snippet to show how quick and simply pagination can be done using OVER:



USE northwind
DECLARE  @startIndex INT,
         @pageLength INT
SET @startIndex = 6
SET @pageLength = 5

SELECT *
FROM   (SELECT o.shipname,
               o.shipaddress,
               Row_number()
                 OVER(ORDER BY o.customerid DESC) AS rownumber
        FROM   orders AS o
               JOIN [order details] AS od
                 ON od.orderid = o.orderid
        WHERE  o.customerid = 'VINET') AS shipmentdetail
WHERE  rownumber BETWEEN @startIndex AND (@startIndex + @pageLength - 1)


Sunday, November 23, 2008

Creating a user and giving permissions in database

Sometimes we need to create special users for our database. For example, in one of my applications, I need to provide appropriate permissions for remote server window service (which is running as a local system account on remote server), so that it can connect to my database and can perform read-write operations. I found following links helpful for understanding basics of SQL server security:

http://vyaskn.tripod.com/sql_server_security_best_practices.htm

http://msdn.microsoft.com/en-us/library/ms187750.aspx

To cut long story short, following is SQL command to create and give read-write permissions to remote machine. Suppose remore server name is 'TESTDOMAIN\testserver'.


Go
IF NOT EXISTS (SELECT * FROM master.dbo.syslogins WHERE loginname = N'testdomain\testserver$')
CREATE LOGIN [testdomain\testserver$] FROM WINDOWS
GO

IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'testdomain\testserver$')
CREATE USER [testdomain\testserver$] FOR LOGIN [testdomain\testserver$] WITH DEFAULT_SCHEMA=[dbo]
GO
GRANT CONNECT TO [testdomain\testserver$]
EXEC sp_addrolemember 'db_datareader', 'testdomain\testserver$'
EXEC sp_addrolemember 'db_datawriter', 'testdomain\testserver$'
GO
GO

Saturday, November 15, 2008

Mime Types for Office 2007 documents

Sometimes you need to correctly set the mime type of file for uploading or downloading purpose. I found this link to help you in this situation, for you convienence, content types are below for docx file.

+---------------------------------------------------------------------------+-------+
| application/vnd.openxmlformats-officedocument.wordprocessingml.document | .docx |
| application/vnd.openxmlformats-officedocument.wordprocessingml.template | .dotx |
| application/vnd.openxmlformats-officedocument.presentationml.presentation | .pptx |
| application/vnd.openxmlformats-officedocument.presentationml.slideshow | .ppsx |
| application/vnd.openxmlformats-officedocument.presentationml.template | .potx |
| application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | .xlsx |
| application/vnd.openxmlformats-officedocument.spreadsheetml.template | .xltx |
+---------------------------------------------------------------------------+-------+

Example of IEnumerable and Yield

Following is very basic code snippet to create a simple IEnumerable class. (Question (1): what's the difference between IEnumerable and IEnumerator? Question (2): does anyone in this world still  implement IEnumerator?) 
using System;
using System.Collections;

public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }

    public string firstName;
    public string lastName;
}

public class People : IEnumerable
{
    private Person[] _people;
    public People(Person[] pArray)
    {
        _people = new Person[pArray.Length];

        for (int i = 0; i <>
        {
            _people[i] = pArray[i];
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        foreach (Person p in _people) 
yield return p;
    }
}

public class MyClass
{
public static void RunSnippet()
{
Person[] peopleArray = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };

        People peopleList = new People(peopleArray);
        foreach (Person p in peopleList)
            Console.WriteLine(p.firstName + " " + p.lastName);
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
#endregion
}

Thursday, October 16, 2008

Using Resource files in Web Service (.NET 3.5) and Regular expression with LINQ

/*
Those who has tried to use resource file in ASP.NET web service know well there is issue in using resource files in web service. Following code snippet targets 3 points:
1. Using resource file in web service or HttpHandlers.
2. Regular expression for converting resource strings with respective localized strings
3. LINQ integration in Regular expression.
Suppose placeholder for resource string in text is like ({BR[MyResourceString]BR}) . Following function will return localized string.
*/


public static string LocalizedHTML(string inputHtml)
{
if (string.IsNullOrEmpty(inputHtml)) return "";

Regex reg = new Regex(@"\(\{IA\[(.*?)\]IA\}\)", RegexOptions.Multiline | RegexOptions.Singleline
| RegexOptions.IgnoreCase | RegexOptions.Compiled);


System.Resources.ResourceManager RM =
new System.Resources.ResourceManager("Resources.Language",
global::System.Reflection.Assembly.Load("App_GlobalResources"));


return reg.Replace(inputHtml, m => (!string.IsNullOrEmpty(RM.GetString(m.Groups[1].Value)) ? RM.GetString(m.Groups[1].Value) : m.Value));

}

Monday, October 13, 2008

Finding installed FTS IFilters on SQL 2005

Following command can be used to find out installed IFilters on SQL2005:

select * from sys.fulltext_document_types

Saturday, August 30, 2008

10 Myths about Open Source Software in Business

ActiveState released this white paper on myths about Open Source Software.

Saturday, August 16, 2008

Easy log parsing with FileHelper

FileHelper is .NET library that provides a very easy and fast parsing methods for delimited or fixed length logs. You can import/export data in file, strings or steams. According to site:

The idea is very simple

You can strong type your flat file (fixed or delimited) simply describing a class that maps to each record and later read/write your file as an strong typed .NET array

Sunday, August 03, 2008

I want a better...

Ahh.. everybody is coming up with new idea and printing money. How about a site that have wish list of frustrated customers. Who knows you may get a new idea from the wish list. 'I-want-a-better' internet connection !!!

Every block - next level of public data processing

This site aggregates tons of public data source by geo location. You can search by various categories. For example, you can view all crime news local to your area in particular city. Currently site is supporting only few cities. According to site:

"EveryBlock is a new experiment in journalism, offering a Web "newspaper" for every city block in Charlotte, Chicago, New York, Philadelphia and San Francisco — with more cities to come. Enter any address, neighborhood or ZIP code in those cities, and the site shows you recent public records, news articles and other Web content that’s geographically relevant to you. To our knowledge, it’s the most granular approach to local news ever attempted."

Monday, July 28, 2008

Better searching with Cuil (hopefully)

Cuil was created by a former Google employee and has entirely different approach for indexing. Till now, this search engine has indexed 120 billion pages, 3 times of Google. Only the time will tell, how it goes, but its result formatting is much better than of Google. It gives results in magazine style formatting. One more thing I like - Home page with black background. I don't know whether it was intentional, but global warming fighter community will surely admire it.

Sunday, July 27, 2008

Reference Cards

Visit this site to get collection of really cool reference cards:
http://refcards.com/

I found reference of this site having SQL server cheat sheet.

Thursday, June 05, 2008

Web Development Helper

Another master piece from Nikhil Kothari, similar to firebug but also having http trace and script console utility.
Download link: http://www.codeplex.com/webdevhelper/Release/ProjectReleases.aspx?ReleaseId=11062

Monday, May 26, 2008

.NET Regex Balanced Grouping

Last time when I tried to understand balanced grouping from MSDN, it hurt my brain badly. Thanks to this guy, though he is not .NET coder, he explained balanced grouping very nicely. A must read for Regex lovers.

Friday, May 23, 2008

Google plays foul

Google hands over user information


Personally, I feel, if you don't like someone, you should not criticize him in filthy language. Being in democracy doesn't mean you strike someone below the belt, specially when someone is top public figure. In 110 crore population, all may not happy with Sonia's government. People should express their view in ethical way.

Whats wrong with Google. I am agree that boy should have not used foul language, but who gives rights to Google to hand over the information. This was not any terrorist activity. If Google thinks, user is using foul language, he should have simple blocked the user. Activity done by Google, simply indicates that they have nothing to do with providing a free social networking platform to public, its all about BUSINESS, its all about getting POWER, its all about MONEY. I read somewhere IBM helped Nazis in holocaust by providing data of Jews population. Google has not done that bad right!!! Well done Google!!.

Friday, February 08, 2008

You have seen Y2K, worse to come!!!

Y2038 Bug!!

According to computer scientists, Unix and Linux system will be massively affected. But of course, still having plenty of time. Surprisingly Perl 10 is Y2038 safe but thats not the reason why I love this language.

Read this:

It is explained that Unix and similar operating systems do not calculate time based on the Gregorian calendar. Instead, they are known to simply count time in seconds from their arbitrary "birthday", that is, GMT 00:00:00, Thursday, January 1, 1970. The accepted practice among software programmers is to use a 32-bit variable for this number (32-bit signed time_t). The largest possible value for the end integer in this calculation is 2**31-1 = 2,147,483,647. So, 2,147,483,647 seconds after Unix's birthday falls on Tuesday, January 19, 2038. And one second later, theoretically Unix systems will revert to their birth date (like an odometer switching back from 999999 to 000000).

See original Post.

Thursday, January 17, 2008

Definitions related with SQL Server

DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT, DELETE

DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.

Examples: GRANT, REVOKE statements

TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.

Monday, January 07, 2008

Fun with WWW::Mechanize

WWW::Mechanize is really a very handy module if you want to automate web page related tasks. Following PERL script downloads the Perl Cook Book pages in a directory. You can put this Perl script in a scheduler and all pages will be collected in few days.

use strict;
use WWW::Mechanize;

my $mech = WWW::Mechanize->new();
my $ouputDir = 'E:\work\documents\PerlCookBook';
my @urls = (
'http://www.perl.com/cookbook/perlckbk2/solution.csp?day=1',
'http://www.perl.com/cookbook/perlckbk2/solution.csp?day=2',
'http://www.perl.com/cookbook/perlckbk2/solution.csp?day=3',
'http://www.perl.com/cookbook/perlckbk2/solution.csp?day=4',
'http://www.perl.com/cookbook/perlckbk2/solution.csp?day=5'
);

foreach my $url (@urls) {
GetPage($url);
}

sub GetPage {
my $url = $_[0];
$mech->get($url);
if ( $mech->success() ) {
my $content = $mech->content();
if ( $content =~ /\<h2 class="head1"\>(.*)?\<\/h2>/ ) {
my $title = $1;

#$title =~ s/\s+//g;
my $filePath = $ouputDir . "\\PCB_" . $title . ".html";
if ( !-e $filePath ) {
open( WR, ">$filePath" ) or die "Can't create file $filePath\n";
print WR $content;
close WR;
print "File was created successfully\n";
}
else {
print "File already exists\n.";
}
}
}
else {
print "Reqeust was not successful\n";
}
}

Friday, January 04, 2008

Recompilation in SQL Server 2005

Before executing SQL statement, SQL server checks for the validity and correctness of the query and generates the execution plan if it's not all already available. No need to say compilation is very CPU intensive process. Before executing the already compiled SQL statement, SQL server perform several other checks and if any of these checks fails, SQL server perform again compilation of SQL statement. Such compilations are known as recompilations. Following are some reasons for recompilation:

  1. Schema change
  2. Statistics change
  3. Deferred compile
  4. SET option change
  5. Temporary table change
  6. Stored procedure created with RECOMPILE query hint or OPTION(RECOMPILE)

In SQL Server 2000, if you need to recompile a portion of stored procedure, you need to compile the whole stored procedure, however in SQL Server 2005, you can perform recompilation at statement level. Less recompilation means less CPU consumption and less contention.

For more information, see Identifying Recompilation

Wednesday, January 02, 2008

Considerations while designing own types

Though Value Types are created on stack and in some situation gives better performance as compare to Reference Types, we should not tempt with choosing Value Type for every situation. General misconception is that if we are not having complex functionality, we should choose Value Type. We should not forget that size of instance also does matter in copy operation. In functions, Value Types are passed by copying the instance as a parameter. Similarly if function is returning Value Type, that is also copied in caller function's memory space. We can make our type as Value Type in following situations:

  1. Type has no members that modify any of the type's instance field. In other words, type is immutable.
  2. Type should not lie in inheritance chain. That means, it should inherit from any other type and also any other type should derived from it.
  3. Instances of the type are small in size (16-20 bytes or less)
  4. Instances of the type are large (greater than 20 bytes) and are not passed as argument or return value in functions.

Most promising technologies in 2008

Welcome 2008. I see following technologies which can take a big leap in 2008:

  1. Microsoft Silverlight framework – facilitates you to run a desktop like application in Internet Explorer.
  2. Ultra Mobile PC (UMPC)- Size of a your hardback book, weight less than a Kg, no hard drive, only flash memory of approx 4 Gb. Visit Asus EEE
  3. ADSL2+: Broadband speed up to 24 Mbps (Of course not in India J)
  4. IPTV: Progress in this field was hampered in past. But now with the increase in broadband speed, this technology is ready to take off.