Thursday, December 25, 2008

MS SQL Server Common Table Expressions

MS SQL Server 2005 introduced Common Table Expression (CTE) which is temporary result set with a name that will be used in SELECT query statement by FROM clause. It makes the queries simpler and better for future maintenance. CTE defines a virtual view that will be used in another data manipulation language (DML) statement, for example in a SELECT.

CTE main elements:
Name of CTE, It comes after WITH keyword.
List of columns, it's optional.
Query that defines the CTE temporary result set,
The quesry sits after AS keyword and inside open and close paranteses.

It's not possible to use COMPUTE, COMPUTE BY, ORDER BY (unless TOP
is used) in a CTE.

For example, in AdventureWorksLT database sample (is available
in CodePlex web pages, you can download it from following here. Product table keeps information about products and category of the products are available in ProductCategory table. The following example provides a temporary result set in the name of CheapProducts which is derived from Product table and those products' price is less than $100 (Ooops, I know, $100 is not cheap thing, just take it easy). Then query that comes after, request for BLACK products with their names and their category.

WITH CheapProducts (ProductName, ProductColor, ProductPrice, ProductCategoryID)
AS
(
   SELECT [name], [color], [listprice], [ProductCategoryID]
   FROM [AdventureWorksLT].[SalesLT].[Product]
   WHERE [listprice] < 100
)
SELECT chpPrd.ProductName, chpPrd.ProductPrice, prdCtg.Name as ProductCategory
   FROM CheapProducts as chpPrd
   JOIN [AdventureWorksLT].[SalesLT].[ProductCategory] as prdCtg
      ON chpPrd.ProductCategoryID = prdCtg.ProductCategoryID
   WHERE chpPrd.ProductColor = 'BLACK'

This one was a simple sample, but when we have a little more
complex queries CTE can really be a good hand to make it simple.
Next example lists the QUANTITY of PRODUCTS (and the products' CATEGORY) which are RED and their price is less than $100, ordered by companies:

WITH PrdAndCat (PrdID, PrdName, PrdColor, PrdPrice, PrdCategory)
AS
(
SELECT prd.[ProductID], prd.[name], prd.[color], prd.[listprice], prdCtg.[Name]
FROM [AdventureWorksLT].[SalesLT].[Product] as prd
JOIN [AdventureWorksLT].[SalesLT].[ProductCategory] as prdCtg
   ON prd.ProductCategoryID = prdCtg.ProductCategoryID
)
SELECT cstmr.CompanyName, ordrHdr.OrderDate, ordrDtl.OrderQty,
pNc.PrdName, pNc.PrdCategory
FROM [AdventureWorksLT].[SalesLT].[SalesOrderHeader] as ordrHdr
JOIN [AdventureWorksLT].[SalesLT].[SalesOrderDetail] as ordrDtl
   ON ordrHdr.SalesOrderID = ordrDtl.SalesOrderID
JOIN [AdventureWorksLT].[SalesLT].[Customer] as cstmr
   ON ordrHdr.CustomerID = cstmr.CustomerID
JOIN PrdAndCat as pNc
   ON pNc.[PrdID] = ordrDtl.[ProductID]
WHERE pNc.PrdColor = 'RED' AND pNc.PrdPrice


Bulk Discount Store 2004-06-01 3 Sport-100 Helmet, Red Helmets
Metropolitan Bicycle Supply 2004-06-01 1 Sport-100 Helmet, Red Helmets
Many Bikes Store 2004-06-01 2 Sport-100 Helmet, Red Helmets
Riding Cycles 2004-06-01 6 Sport-100 Helmet, Red Helmets
Action Bicycle Specialists 2004-06-01 10 Sport-100 Helmet, Red Helmets
Eastside Department Store 2004-06-01 10 Sport-100 Helmet, Red Helmets
Professional Sales and Service 2004-06-01 3 Sport-100 Helmet, Red Helmets

Share/Bookmark

Monday, November 3, 2008

Remembering NULL-Coalescing operator

It's A clean and smart operator to deal with null values to make a
decision on them. Nullable types since .NET 2.0 brought opportunity
to work with value type which can be null too. To make a value type
"Nullable" we can add a ? follwoing the type like:
...
int? height = null;
...
Well now that we have nullable types, we can check null value and use
Coalesce Operator for a conditional assignment. ?? means if left side is
null, then give the right side value.

The ?? operator returns the left-hand operand if it is not null, or else it
returns the right operand.
...
string firstName = this.getFirstName();
Console.WriteLine( firstName ?? "No name" );
...
?? operator is also protecting it. It makes us able to assign a nullable type
to a non-nullable type with correcting the value if its null.
...
int? i = null;
int x = i ?? -1; // x = -1
...
string txtMsg = null;
string outMsg = txtMsg ?? "Hello world!"; // outMsg = "Hello world!"
...

?? is the same as ISNULL in Transact-SQL which implemented
in .NET but it's not popular between developers.
ISNULL ( check_expression, replacement_value )
Share/Bookmark

Friday, October 17, 2008

MS Silverlight 2 released

A programmable web browser plug-in which enables features like Audio-Video, graphic, animation, and more based on .NET framework by Microsoft, Silverlight. Silverlight tries to compete with Adobe Flash, JavaFx, Javascript, and ... in making applications rich with interactive and graphical features on the web.
MS Silverlight 2 released October 14, 2008, you can try it out!

http://silverlight.net/default.aspx
Share/Bookmark

Sunday, September 28, 2008

Pixie a fast and tiny color picker utility

Pixie is an easy-to-use color picker. Just simply point to a color and it will tell you the hex, RGB, HTML, CMYK and HSV values of that color. Pixie works on Windows 95/98/Me/NT/2000/XP/Vista, any body who is dealing with web programming or design needs to have such a simple and perfect tool to make it easy on Internet life. Pixie will also show the current x y position of your mouse pointer. If you need to work with colors, then it's the tool which you need.
To download Pixie for free: http://www.nattyware.com/pixie.html
Share/Bookmark

Friday, September 26, 2008

How to get Tables' name, Columns' name, and Column's type in Sql 2005

In MS Sql Server 2005, if you open SSMS (SQL Server management
Studio), in Object Explore under "Views" node for your DataBase,
you can find "System Views". sys.tables keeps information about
your created tables and sys.columns contains info about columns
(Fields) of your tables in the DataBase.

Then to get the columns and data type of them in tables which
have been created in the DataBase, the following code would be
a good example to start and play around it to explore more about
data of the data or the meta data:


select tbl.name as tableName,
      clmn.name as columnName,
      typ.name as typeName
            from sys.columns as clmn
            inner join sys.tables tbl
               on clmn.object_id = tbl.object_id
            inner join sys.types typ
               on clmn.system_type_id = typ.system_type_id
   order by tbl.name

Share/Bookmark

Cropper - Point and Shoot Screen Captures

Cropper is a great screen capture tool which is written by Brian Scott in C#.NET

Point, Crop, and Save any area which you like just for free.
Share/Bookmark

Thursday, September 25, 2008

JR Screen Ruler - A tool to measure a picture size

JR Screen Ruler is a handy and free tool which help you to find out the size of an image that is located on screen. Everybody who is dealing with web pages knows how much it worth. To get it for free, go to the following URL:


http://www.spadixbd.com/freetools/index.htm
Share/Bookmark

Monday, September 22, 2008

How to limit the number of rows to enter in DataGridView

In a DataGridView if the number of rows should be limited to a
predefined value, we can switch AllowUserToAddRows to "true"
or "false", it will let the user be able to add new rows or stop
the user for entering more new rows.

RowLeave event is the place to count number of Rows and if it's
equal to limit, then we need to stop adding more. on the other hand
if user delete some row(s), it opens new room for adding new ones.

In the following part of code I considered to have just 20 rows in
our DataGridView control:


private void dgv1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
  if (dgv1.Rows.Count >= 20)
      dgv1.AllowUserToAddRows = false;
}
private void dgv1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
  if (dgv1.Rows.Count < 20)
      dgvTmp.AllowUserToAddRows = true;
}

Share/Bookmark

Sunday, September 21, 2008

How to make Visual Studio Full Screen

When I want to change Visual Studio from normal size To Full screen,

I use Shift+Alt+Enter, then I will have just menu and almost all the
screen will occupy by code which help us to have a good area to deal
with the code lines.

It works like F11 in Internet Explorer to show your web page in full screen.
Share/Bookmark

Saturday, September 20, 2008

How to clear "Recent Projects" in Visual Studio

Well, to clear list of projects in "Recent Projects" in start
page of Visual Studio simply just we need to clear something
in registry.

1- Run registry editor in Windows:
Start->Run->RegEdit

2- Goto the following area in registry file:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\ProjectMRUList
"8.0" is for Visual Studio 2005, depend on the Visual Studio version
which you installed, this number can be something else.

3- Remove any one of unnecessary values in above area, the key value
name starts with "file" like: file1, file2, ...

Another solution:
1- Add the following lines in a text file and save it in any name which you
like with ".reg" extention:
[-HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\ProjectMRUList]
[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\ProjectMRUList]
"8.0" is for Visual Studio 2005, depend on the Visual Studio version
which you installed, this number can be something else.

2- Anytime which you like to clear the list of projects in "Recent Projects",
double click on the created .reg file.
Share/Bookmark

Sunday, September 14, 2008

How to add images for a Node in TreeView control

To add images in a Node for treeview control

1- Add new ImageList component to your form
2- Add bitmap images (normally 16 x 16) to your project (Project->Add new Item).
3- Select your ImageList and poulate Images property with each o images (Images Collection Editor form).
4- Set ImageList property of your TreeView control to your ImageList component.
5- Add nodes to your treeview control with using ImageIndex, Image Index starts from 0
Example:
myTreeNode = new TreeNode(myMovie.movieName, 0, 0);
treeViewMovies.Nodes.Add(myTreeNode);
for next image you can use 1 and so .
Look at "TreeNode.ImageIndex Property" in MSDN

Share/Bookmark

Saturday, September 13, 2008

Change ForeColor of a TextBox control

When we disable a TextBox, we can change its BackColor but if we change the ForeColor, it doesn't apply. To solve the problem, I created a new class based on TextBox and changed the OnPaint method to do the ob for me:

- Add a new class to your solution
- Define your new class based on TextBox
public class MyTextBox : TextBox
{
public MyTextBox()
{
this.SetStyle(ControlStyles.UserPaint, true);
}

protected override void OnPaint(PaintEventArgs e)
{
SolidBrush myDrwBrush = new SolidBrush(Color.Black);
e.Graphics.DrawString(this.Text, this.Font, myDrwBrush, 0F, 0F);
}
}
- Instantiate an object from the new class on your form
- Customize its properties
- Add it to your form controls like this:
MyTextBox myTxtBox = new MyTextBox();
myTxtBox.Location = new System.Drawing.Point(12, 36);
myTxtBox.Name = "myTxtBox";
myTxtBox.Size = new System.Drawing.Size(260, 20);
myTxtBox.Text = "This is a test text box";
this.Controls.Add(myTxtBox);
- Disable it in your code to see the effect:
this.Controls["myTxtBox"].Enabled = false
In addition, I found another similar solution in the following URL:
http://austinleng.spaces.live.com/Blog/cns!6F894DC66A2F0AFF!454.entry

Share/Bookmark

How to search a text in Nodes of a TreeVew control?

The following methods can help to search a text in Nodes of a TreeView control recursively:

public TreeNode srchTxtInTreeView(TreeView trvToSrch, String strToSrch)
{
// check if the treeView is not NULL
if (trvToSrch == null)
return null;

// loop through the nodes in the treeview's root nodes
for (int i = 0; i < trvToSrch.Nodes.Count; i++)
{
TreeNode trvNode = srchTxtInTreeViewNode(trvToSrch.Nodes[i], strToSrch);
if (trvNode != null)
return trvNode;
}
return null;
}

public TreeNode srchTxtInTreeViewNode(TreeNode trvNode, String strToSrch)
{
// check if the treeView is not NULL
if (trvNode == null)
return null;

if (trvNode.Text == strToSrch)
return trvNode;

// loop through the nodes in the treeview's sub nodes
for (int i = 0; i < trvNode.Nodes.Count; i++)
{
// recursive call to itself to check lower level nodes
TreeNode retTrvNode = srchTxtInTreeViewNode(trvNode.Nodes[i], strToSrch);
if (retTrvNode != null)
return retTrvNode;
}
return null;
}

To call the method, I tested it by a Button control:

private void button1_Click(object sender, EventArgs e)
{
TreeNode retNode = srchTxtInTreeView(this.trvJust4Test, "Hello");
if (retNode != null)
MessageBox.Show(retNode.ToString() + "Node Found!");
}

Share/Bookmark

Sunday, August 24, 2008

SQL Server 2008 Express

Since yesterday available for download:
https://www.microsoft.com/express/sql/download/default.aspx

As I heard today, it's faster than version 2005, let's try it, Cheers.
Share/Bookmark

Saturday, August 23, 2008

AutoRecover in VS2005

To protect your solution in Visual Studio 2005 against crashing system, losing power,
unwanted restart, or ... there is an option for autorecover which
has been set to save information for every 5 minites and keep them
for 7 days as default.

It creates some backup files under visual studio folder:
.\Visual Studio 2005\Backup Files

To set it properly or to turn it off you can go in:
Tools\Options/Environment/AutoRecover


To check it in MSDN:
http://msdn.microsoft.com/en-us/vs2005/aa718517.aspx
Share/Bookmark

Wednesday, August 20, 2008

CHM reader for FireFox


Even though that Microsoft Compiled HTML Help files (CHM) with attention to some security risks are not so popular but there are a lot of documents which have been compiled, or converted to CHM. To read a CHM file in FireFox, it's possible to add CHM Reader as a FireFox Add-on and enjoy using the content of those compiled help format files.

To find other FireFox Add-ons use the following URL:
https://addons.mozilla.org/en-US/firefox/
Share/Bookmark

Sunday, August 17, 2008

Get Tables & Columns using Information Schema views (Sql 2005)

The Information Schema is an ANSI standard set of read-only views which
provide access to metadata in a relational database. Metadata is data about data and it contains information about all of the tables, views, columns, constraints, procedures, routines, and more.


According to MSDN, Information Schema Views (Transact-SQL)
"Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables."



Each information schema view contains metadata for all data objects stored in that particular database.

Show all Tables in a Database:


SELECT * FROM AdventureWorksLT.information_schema.tables
WHERE table_type = 'Base Table'



The following T-SQL give us back the list of tables and related columns:

Because we needed to collect info about user generated tables, 'U' for 'xtype'
has been used in the code:

* xtype has two values - ‘U’ or ‘S’
* U = User generated tables
* S = System generated tables


USE AdventureWorksLT

SELECT table_name,
    column_name,
    data_type,
    character_maximum_length
FROM Information_Schema.columns
WHERE table_name IN (Select name FROM sysobjects WHERE xtype = 'U')
ORDER BY table_name



If you need to have access to other columns about the tables, please look at the available columns in Information_Schema.columns.

SQL Server 2005 System Tables and Views
SQL Server 2005 System Tables and Views
Using the Information Schema Views


Share/Bookmark

Tuesday, August 12, 2008

Visual Studio 2008 SP1 released


As I could find in news, Visual Studio 2008 SP1 comes with a lot of bug fixes and new features. To install you need to have the original media which you installed your VS 2008 from it.

In addition there is
.NET Framework 3.5 Service Pack 1 too, those together offer a lot new as someone thinks VS 2009 is better name for it. Mary-Jo Foley has posted about it in ZDNet
http://blogs.zdnet.com/microsoft/?p=1523


V
isual Studio 2008 SP1 delivers:
  • Improved WPF designers
  • SQL Server 2008 support
  • ADO.NET Entity Designer
  • ... and more
The .NET Framework 3.5 SP1 delivers:
  • Performance increases 20-45% for WPF-based applications – without having to change any code
  • WCF improvements that give developers more control over the way they access data and services
  • ... and more
Downloads:
Share/Bookmark

Sunday, August 10, 2008

Activate Administrator account in Vista


Well, because of some security matters Administrator account is disabled as default for Windows Vista, to enable it you can simply follow the steps:

- Logon to Vista with your username and password
- Right click on Start->All Programs->Accessories->Command Prompt
- Select "Run as administrator" from context menu
- In command line type "Net user administrator /active:yes" then enter
- Check the message : The command completed successfully
- Switch User, Log Off, Restart, or Shut Down and boot your system again!
- Logon as Administrator

P.S. To hide Vista Administrator account use the following command:
Net user administrator /active:no
Share/Bookmark

AdventureWorks sample database for SQL server 2005 Express


When I wanted to install AdventureWorks sample database in SQL server 2005 Express on my Windows Vista home premium machine, I encountered with an error about lack of permission, I could install it after configuring permission.

First download the AdventureWorks:
- Use the following URL to download AdventureWorksLT.msi file:
http://www.codeplex.com/MSFTDBProdSamples/Release/ProjectReleases.aspx?ReleaseId=4004
- Click on AdventureWorksLT.msi to save the file on your favorite location in your machine.
- Click on Run once the download is complete

Permission configuration:
- Run Windows Explorer (Windows Key + E)
-
Use
"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data" as path
- Right click on AdventureWorksLT_Data.mdf and select Properties
-
Then Security->Edit->Add
-
In "Enter the object names ... " textbox enter your login name
- Click on Check Names, the entered name changes to MACHINENAME/Login then click OK
-
Select your login name from Groups or username list and choose Full control then click OK and OK
-
Repeat the same sequence for
AdventureWorksLT_Log.ldf

Sql Server Management Studio:
- If you don't have
Microsoft SQL Server Management Studio Express,
download it from (Microsoft Download Center) the following URL:
http://www.microsoft.com/downloads/details.aspx?FamilyId=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en
- Lunch
Sql Server Management Studio Express and connect to your local server.
- Right click on Databases in Object explorer and click on Attach
- click on Add and select AdventureWorksLT_Data.mdf and again click on OK
- finally click on OK and now you can find it in Object Explorer
Databases > AdventureWorksLT

Hope it helps if you encountered the same problem


Share/Bookmark

Thursday, August 7, 2008

Microsoft SQL Server 2008 released


I received this news by Microsoft TechNet newsletter, SQL Server 2008 is available as of today to MSDN and TechNet subscribers.

SQL Server 2008
Resources about SQL Server 2008 features, pricing and editions.
SQL Server 2008 TechCenter
Resources for IT Professionals who deploy, manage, and administer SQL Server.
SQL Server 2008 Developer Center
Resources for developers who develop applications that work with SQL Server.
Download the SQL Server 2008 Trial Software
Evaluate Microsoft SQL Server 2008 download, the 180-day trial software.
Share/Bookmark

Saturday, August 2, 2008

.NET News - dotNetCat.com

Another good source for .NET and other stuff, I started with dotnetcat because I found it just right now, hope it helps for
the readers too.
Share/Bookmark

Shiretoko - Firefox 3.1 Alpha


Right after Firefox 3.1 now you can wait for a new one with some interesting features, it'll come end of 2008!

Some new features: Visual Tab Switcher which offers previews of pages, changes the sorting order based on which tab was most recently open. The advantage of dynamic ordering is quick jumps between recently visited tabs.

For futhur info look at Firefox 3.1 Alpha preview
Share/Bookmark

iBorn2Code


"i Born 2 Code" is a virtual place to present some technical, technological, informative news, daily photos, and interesting information in computer, programming, technology, art! and or may be wired fields! Tons of information all around makes the job difficult to present the best ones, anyway It will try to be cool and informative. Then let's go.

"i Born 2 Code" first content generated in saracafe in North Vancouver.
Share/Bookmark