понедельник, 27 декабря 2010 г.

Find Tables With Foreign Key Constraint in Database

This is very long query. Optionally, we can limit the query to return results for one or more than one table.

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='something'WHERE FK.TABLE_NAME='something'
WHERE PK.TABLE_NAME IN ('one_thing', 'another')
WHERE FK.TABLE_NAME IN ('one_thing', 'another')

суббота, 25 декабря 2010 г.

ASP.NET HttpPostedFile Image Resize

Many websites have forums and other features where members can upload an avatar image or photo of themselves. One of the most common problems with this is that people upload images that are too big.

You can work around this by specifying one parameter in your tags, a width property. This will automatically constrain the displayed image to your required size. However, it does not change the size of the uploaded image file. To do that, you must resize the image the user has uploaded before saving it.

This handy ImageResizer class does just that.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

namespace PAB.ImageResizer
{
///


/// A class to resize uploaded images
///

public class ImageResizer
{
private int _imgQuality;
private int _maxHeight;
private int _maxWidth;
private PAB.ImageResizer.ImageFormat _outputFormat;

///
/// Initializes a new instance of the class.
///

public ImageResizer()
{
this._maxWidth = 800;
this._maxHeight = 800;
this._imgQuality = 80;
this._outputFormat = PAB.ImageResizer.ImageFormat.Jpeg;
}

///
/// Initializes a new instance of the class.
///

/// Maximum Width .
/// Maximum Height
/// The image quality.
public ImageResizer(int maxWidth, int maxHeight, int imgQuality)
{
this._maxWidth = 800;
this._maxHeight = 800;
this._imgQuality = 80;
this._outputFormat = PAB.ImageResizer.ImageFormat.Jpeg;
this._maxHeight = maxHeight;
this._maxWidth = maxWidth;
this._imgQuality = imgQuality;
}

///
/// Resizes the specified source image.
///

/// The source image.
///
internal System.Drawing.Image Resize(System.Drawing.Image sourceImage)
{
System.Drawing.Image source = new Bitmap(sourceImage);
int width = sourceImage.Width;
int height = sourceImage.Height;
if (width > this.MaxWidth)
{
height = (height * this.MaxWidth) / width;
width = this.MaxWidth;
}
if (height > this.MaxHeight)
{
width = (width * this.MaxHeight) / height;
height = this.MaxHeight;
}
if ((width != sourceImage.Width) || (height != sourceImage.Height))
{
source = new Bitmap(source, width, height);
}
return source;
}

///
/// Resizes by specified image path.
///

/// The image path.
public void Resize(string imagePath)
{
this.Resize(imagePath, imagePath);
}

///
/// Resizes the specified posted file.
///

/// The posted file.
///
public byte[] Resize(HttpPostedFile postedFile)
{
if (postedFile.ContentLength == 0)
{
return new byte[0];
}
System.Drawing.Image sourceImage = System.Drawing.Image.FromStream(postedFile.InputStream);
System.Drawing.Image image2 = this.Resize(sourceImage);
sourceImage.Dispose();
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (longthis.ImgQuality);
ImageCodecInfo encoder = ImageCodecInfo.GetImageEncoders()[(int) this.OutputFormat];
MemoryStream stream = new MemoryStream();
image2.Save(stream, encoder, encoderParams);
byte[] buffer = stream.GetBuffer();
image2.Dispose();
stream.Close();
return buffer;
}

///
/// Resizes the specified original image path.
///

/// The original image path.
/// The resized image path.
public void Resize(string originalImagePath, string resizedImagePath)
{
System.Drawing.Image image;
try
{
image = System.Drawing.Image.FromFile(originalImagePath);
}
catch
{
if (!File.Exists(originalImagePath))
{
throw new Exception("File " + originalImagePath + " doesn't exist; resize failed.");
}
throw new Exception("File " + originalImagePath + " is not a valid image file or No read permission on the file; resize failed.");
}
System.Drawing.Image image2 = this.Resize(image);
image.Dispose();
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (longthis.ImgQuality);
ImageCodecInfo encoder = ImageCodecInfo.GetImageEncoders()[(int) this.OutputFormat];
try
{
image2.Save(resizedImagePath, encoder, encoderParams);
}
catch (Exception exception)
{
string userName;
try
{
userName = Environment.UserName;
}
catch
{
userName = null;
}
if (String.IsNullOrEmpty( userName))
{
userName = "'ASPNET' or 'Network Service'";
}
userName = userName + " windows account";
throw new Exception("Could not save resized image to " + resizedImagePath + "; resize failed.\r\n" + exception.Message + "\nTry the following:\r\n1. Ensure that " + resizedImagePath + " is a valid file path.\r\n2. Ensure that the file " + resizedImagePath + " is not already being used by another process.\r\n3. Ensure that " + userName + " has write/modify permission on " + resizedImagePath + " file.\r\n");
}
finally
{
image2.Dispose();
}
}

///
/// Resizes the specified posted file.
///

/// The posted file.
/// The resized image path.
public void Resize(HttpPostedFile postedFile, string resizedImagePath)
{
postedFile.SaveAs(resizedImagePath);
this.Resize(resizedImagePath);
}

public int ImgQuality
{
get
{
return this._imgQuality;
}
set
{
if ((value < 2) || (value > 100))
{
this._imgQuality = 80;
}
else
{
this._imgQuality = value;
}
}
}

///
/// Gets or sets the max height.
///

/// The max height.
public int MaxHeight
{
get
{
return this._maxHeight;
}
set
{
this._maxHeight = value;
}
}


///
/// Gets or sets the max width.
///

/// The max width.
public int MaxWidth
{
get
{
return this._maxWidth;
}
set
{
this._maxWidth = value;
}
}

///
/// Gets or sets the output format.
///

/// The output format.
public PAB.ImageResizer.ImageFormat OutputFormat
{
get
{
return this._outputFormat;
}
set
{
this._outputFormat = value;
}
}
}
}


To use this, you can apply it's Resize method directly to the HttpPostedFile object:

if (FileUpload1.HasFile)
{
PAB.ImageResizer.ImageResizer resizer = new PAB.ImageResizer.ImageResizer();
resizer.MaxHeight = int.Parse(txtMaxHeight.Text);
resizer.MaxWidth = int.Parse(txtMaxWidth.Text);
resizer.ImgQuality = 100;
resizer.OutputFormat = PAB.ImageResizer.ImageFormat.Gif;
byte[] bytes = resizer.Resize(FileUpload1.PostedFile);
File.WriteAllBytes(Server.MapPath("~/test.gif"), bytes);
Response.Redirect("Default.aspx",true);
}

Then you simply save the new image file. You can even specify the Image Format you want - Bmp, Gif, Jpeg, or Png.

I have put in several overloads of the Resize method that allow you to load an image from a path and resize it, along with resizing from an HttpPostedFile object directly after an upload.

The downloadable Visual Studio 2010 Solution has a sample ASP.NET project with a web page that will allow you to upload an image, have it resized, and it will then display the saved image on the page.

вторник, 7 декабря 2010 г.

Update from a Select


I know many people won't find this new, but it's the first time I've had to do it today.
I needed to update one table, from another table, and here's how I did it: -
UPDATE C
SET C.Phone = O.[Tel No],
C.Fax = O.[Fax]
FROM Outputs O
JOIN Contacts C
ON C.MemberId = O.MemberId

пятница, 3 декабря 2010 г.

Using Coordinated Universal Time (UTC) to Store Date/Time Values


Introduction


Many data-driven applications have date/time values that are automatically populated with the current date and time. For example, in an online messageboard, whenever a user makes a post the current date and time is recorded and saved with that post. Another example is in applications that track created on or last modified dates. For these types of applications, whenever a new record is created or an existing one modified, the current date and time are written into these respective fields.
Such auto-entered timestamp values can be stored in the database in either server time or Coordinated Universal Time (UTC). If you use SQL Server's built-in getdate() function or DateTime.Nowproperty to determine the current time, then you are using server time and saving the date and time respective to the web or database server's time zone settings. Alternatively, if you use SQL Server's built-in getutcdate() function or DateTime.UtcNow property then you are storing the values in UTC.
There are a number of advantages in storing such date/time values in UTC rather than server time. In this article we will explore those advantages as well as look at a simple sample application that illustrates how to save dates in UTC and still display them relative to the time zone's offset.
What is UTC?
UTC, or Coordinated Universal Time, is the standard international time that all time zones are expressed as offsets of. UTC does not get adjusted for daylight savings. To compute local time from UTC, simply add the time zone offset and then add an additional hour if daylight savings time is in effect.
As I write this sentence, the time in UTC is Friday, August 3, 2007 18:18:36. California has a UTC offset of -8 and is in daylight savings time. Therefore my local time is Friday, August 3, 2007 11:18:36. To compute the local time I simply subtracted eight hours then added an hour back in for daylights savings.

Why and When You Should Use UTC


UTC should be used in situations when date/time values are automatically entered by the system to record when a record was added or last updated. For example, in an eCommerce website, when an order was placed you'd want to record the date and time the order was made.
The primary advantage of storing date/time values in UTC is that it makes the data transportable. To see what I mean, imagine that following scenario: you have an eCommerce website that is being hosted in a web server located in the Pacific time zone (UTC -8) and this application stores the date and time orders were placed in server time. Say a user, Bob, makes an order on August 1, 2007 at 9:00 AM UTC -8. After many months of phenomenal growth, you decide to switch to a larger web hosting company, one on the east coast where the time zone is UTC -5. Since the date/time is stored in server time, Bob's previous order still shows that it was made on August 1 2007 at 9:00 AM. But since we are now in UTC -5, it is as if Bob's order was made three hours earlier than it really was (since when it was 9:00 AM on August 1, 2007 in the west coast it was really 12:00 noon on the east coast).
One way around this, you might contend, is to execute a SQL query that adds three hours to the order date for all records in the table. Something like:
UPDATE Orders SET
   OrderDate = DATEADD(hh, 3, OrderDate)

And such an approach would suffice... for this situation. But imagine that you moved to a web hosting company situated in the US state of Arizona, where daylight savings is not observed. Eep. Now you would have to write a more complex UPDATE statement that adjusted the hours based on whether the order date fell within daylight savings. Ick.
Another pitfall of server time is if you have multiple servers in multiple time zones. Now the values for each server's date/time fields is relative to that server's geographical location. What UTC buys you is a single reference point.

Other Challenges of Date/Time Values


There are numerous other date/time-related challenges that I am going to ignore at this point. The thrust of this article is to highlight UTC, how to use it in your data-driven applications for auto-generated timestamp-like date/time values, and its advantages in that arena.
Other challenges of date/time values include displaying dates relative to one's time zone and daylight savings. This adds some complexity as you must know the user's time zone offset and whether they are in a location that observes daylight savings and whether the date/time value being displayed falls within the boundaries of daylight savings. But UTC is still a better format to save dates than server time because it makes this complication a bit simpler. For example, if I know a user's time zone offset is UTC -4 and I am storing date/time values in UTC, then I can simply subtract four hours to get the correct non-daylight savings time. If I am using server time, then I have to determine the difference between my server time and the users time zone and determine whether the server time is in daylight savings time and if the user's time zone is observing daylight savings time. Double ick.

Getting the Current Time in UTC


Both the .NET Framework and Microsoft SQL Server provide functions to return the current time in UTC. In the .NET Framework, use the DateTime.UtcNow property, like so:
' VB (use instead of DateTime.Now)
Dim currentTime As DateTime = DateTime.UtcNow

// C# (use instead of DateTime.Now)
DateTime currentTime = DateTime.UtcNow;

For SQL Server, use the getutcdate() function.
-- MS SQL (use instead of GETDATE())
DECLARE @currentTime datetime
SET @currentTime = GETUTCDATE()

Converting from UTC Time to Server Time


Given a time in UTC, the .NET Framework makes it easy to convert it to server time. Just use the DateTime class's ToLocalTime() method, like so:
' VB
Dim currentServerTime As DateTime = DateTime.UtcNow.ToLocalTime()
currentServerTime = CType(Eval("DateCreated"), DateTime).ToLocalTime()

// C#
DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
currentServerTime = ((DateTime) Eval("DateCreated")).ToLocalTime()

A Complete Example


To further illustrate using UTC to store auto-entered date/time values, let's examine a sample application that has fields to track when a record was created and last updated. This application, which is available at the end of this article, has a single database table, Employees, with a very simple schema:
Employees
ColumnData Type
EmployeeIDint - Primary Key and AutoIncrement
FullNamevarchar(50)
Salarymoney
DateCreateddatetime
DateUpdateddatetime

In the download you'll find a single ASP.NET page, UTCFunctions.aspx, that contains a DetailsView control for adding new employees and a GridView for listing and editing existing employees. Both are wired up to a SqlDataSource on the page that contains the associated INSERTUPDATE, and DELETE statements. (For more information on working with data in ASP.NET 2.0, see my multi-part article series Accessing and Updating Data in ASP.NET 2.0.)
As you can see from the screen shot above, the DetailsView does not allow the user to enter values for the DateCreated or DateUpdated fields. Instead, it populates these with the current date/time in UTC. The INSERT statement used by the SqlDataSource control follows:
INSERT INTO [Employees] ([FullName], [Salary], [DateCreated], [DateUpdated])
VALUES (@FullName, @Salary, @DateCreated, getutcdate())

For the DateUpdated value, the built-in SQL Server function getutcdate() is used. For the DateCreated value, a parameter is specified (@DateCreated) and its value is specified programmatically in the DetailsView control's ItemInserting event handler:
' VB
Protected Sub dvNewEmployee_ItemInserting(sender As Object, e As DetailsViewInsertEventArgs)
   e.Values("DateCreated") = 

DateTime.UtcNow


End Sub

// C#
protected void dvNewEmployee_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
   e.Values["DateCreated"] = DateTime.UtcNow;
}

I used both techniques - getutctime() and DateTime.UtcNow - to illustrate both options. In practice you'd probably want to choose one approach and use it for both parameters.
The GridView displays the DateUpdated and DateCreated values in UTC time. These are the raw values from the database. The two fields' values are also converted to local time and displayed in columns in the grid. This conversion is done using the ToLocalTime method. In particular, a TemplateField is used to show the local times and the ToLocalTime method is used directly within the Label control's Text property:
' VB

   
      
   



// C#

   
      
   

Lastly, note that the GridView's editing interface does not allow the date fields to be modified. Whenever a record is edited the DateUpdated field is updated to the current date/time (in UTC) via theUPDATE statement:
UPDATE [Employees] SET
   [FullName] = @FullName,
   [Salary] = @Salary,
   

[DateUpdated] = getutcdate()


WHERE [EmployeeID] = @EmployeeID

Conclusion


UTC time provides a universal point of reference by which all time zones are offsetted from. Therefore, UTC is an ideal choice for storing date/time formats in a web application when the web server and its users might reside in different time zones. Things like daylight savings further complicate working with dates and times, but UTC does not observe any time zone, simplifying things a tiny bit. In short, working with dates and times in a web application is one of those things that is harder than it should be and has a lot of wrinkles that make the whole thing a bit of a mess. One step in the right direction, however, is to make sure you are storing auto-entered timestamp-like date and time values in UTC rather than in server time.
For guidance on displaying date and time values, see Advice for Storing and Displaying Dates and Times Across Different Time Zones.
Happy Programming!

понедельник, 29 ноября 2010 г.

Нумерованные и маркированные списки в Microsoft Office

Нумерованные и маркированные списки в Word

В этом уроке вы узнаете, как. вставить нумерованный или маркированный список в свой документ

Для чего нужны нумерованные и маркированные списки

Нумерованные и маркированные списки — полезные инструменты форматирования для создания списков данных в тексте, которые вы уже много раз встречали в этой книге. Word может автоматически создавать списки любого из этих типов. Применяйте маркированные списки для связанных между собой, но неупорядоченных данных. Нумерованные списки используйте для однотипных данных, которые можно упорядочить и пронумеровать. Когда вы создаете нумерованный или маркированный список, каждый абзац считается отдельным элементом списка и ему присваивается его порядковый номер или метка.

Создание нумерованного или маркированного списка

Вы можете создать список на основе существующего текста или по мере набора. В первом случае выполните следующее.
1. Выделите абзацы, которые войдут в список.
2. Выберите команду Формат -> Список для открытия диалогового окна Список.
3. В зависимости от типа списка, который вы хотите создать, откройте вкладку Нумерованный или Маркированный. На рис. 19. 1 показана вкладка Нумерованный, а на рис. 19.2 — вкладка Маркированный.
4. Выберите тот стиль списка, который импонирует вам больше всего.
5. Щелкните на кнопке ОК.
191.jpg
Рис. 19. 1. Стили нумерованных списков во вкладке Нумерованный
Чтобы нумерованный или маркированный список создавался по мере набора текста, выполните следующее.
1. Установите курсор в начало списка. Если нужно, нажмите клавишу , чтобы начать новый абзац.
2. Выберите команду формат -> Список для открытия диалогового окна Список.
3. В зависимости от типа списка, который вы хотите создать, откройте вкладку Нумерованный или Маркированный.
4. Выберите стиль нового списка, щелкнув на пиктограмме с его изображением.
5. Щелкните на кнопке ОК.
6. Набирайте элементы списка, нажимая клавишу в конце каждого абзаца. Каждый новый абзац автоматически становится элементом нумерованного или маркированного списка.
7. В конце последнего абзаца нажмите дважды.
192.jpg
Рис. 19. 2. Стили маркированных списков во вкладке Маркированный
193.jpg

Использование многоуровневых списков

Многоуровневый список содержит два и более уровней маркированного или нумерованного списка в пределах одного общего списка. Например, нумерованный список может включать в себя части, помеченные буквами под каждым пронумерованным элементом, или же каждый уровень может быть пронумерован отдельно, как в режиме просмотра структуры документа. Вот как создать многоуровневый список.
1. Выберите команду Формат -> Список для открытия диалогового окна Список.
2. Щелкните на корешке вкладки Многоуровневый, чтобы просмотреть виды многоуровневых списков (рис. 19. 3).
3. Щелкните на изображении того списка, который вам понравится, а затем щелкните на кнопке ОК.
4. Набирайте список, нажимая после каждого его элемента.
5. После нажатия клавиши нажмите клавишу <ТаЬ> для перехода на новый вложенный уровень или же клавиши для перехода на один уровень вверх. В противном случае, новый элемент списка окажется на том же уровне, что и предыдущий.
6 Набрав последний элемент списка, нажмите клавишу , а затем щелкните на кнопке Нумерованный список панели форматирования для завершения списка.
Вы можете преобразовать обычный текст или одноуровневый нумерованный или маркированный список во многоуровневый список. К тому же вы можете поменять стиль уже существующего многоуровневого списка. Вот как это сделать.
1. Выделите все абзацы, которые вы хотите включить в новый список, или изменить их форматирование.
2. Выберите команду Формат -> Список, а затем щелкните на корешке вкладки Многоуровневый.
3. Выберите стиль списка по своему усмотрению, затем щелкните на кнопке ОК.
4. Установите курсор на той позиции списка, уровень которой вы хотите изменить.
5. Щелкните на кнопке Уменьшить отступ или Увеличить отступ на панели форматирования для изменения уровня элемента списка.
6. Повторите пп. 4 и 5, если нужно изменить уровни других элементов списка.
194.jpg
Рис. 19. 3. Использование вкладки Многоуровневый диалогового окна Список для создания многоуровневого списка

Преобразование нумерованного или маркированного списка в обычный текст

Выполните следующие действия, чтобы удалить номера или метки из списка, преобразовав тем самым текст списка в обычные абзацы.
1. Выделите абзацы, которые хотите преобразовать. Это может быть весь список или же только его часть. Соответствующая кнопка на панели форматирования (Нумерация или Маркеры) будет нажата.
2. Щелкните на нажатой кнопке панели форматирования.

Изменение формата нумерованного или маркированного списка

Вы можете изменить формат уже существующего нумерованного или маркированного списка, соответственно изменив стиль цифр или меток. Для этого выполните следующее.
1. Выделите абзацы, в которых вы хотите изменить метки списка. Это может быть как весь список, так и часть его.
2. Выберите команду Формат -> Список для открытия диалогового ок на Список.
3. Если у вас маркированный список — откройте вкладку
Маркированный и выберите нужный стиль. Для того чтобы убрать метки, щелкните в поле Нет.
4. Для нумерованного списка откройте вкладку Нумерованный и выберите стиль для этого списка либо щелкните в поле Нет для удаления нумерации из списка.
5. Щелкните на кнопке ОК.

Добавление позиций в нумерованный или маркированный список

Добавить новые позиции в нумерованный или маркированный список можно так.
1. Установите курсор в той позиции списка, куда вы хотите внести новый элемент.
2. Нажмите клавишу для начала нового абзаца. Word автоматически вставит новую метку или номер и перенумерует весь список в случае необходимости.
3. Введите новый текст.
4. Если это многоуровневый список, щелкните на кнопке Уменьшить отступ или Увеличить отступ на панели форматирования, если вам нужно изменить уровень введенной позиции.
5. Повторите все предыдущие пункты для каждой новой позиции.
В этом уроке вы узнали, как создавать нумерованные и маркированные списки. В следующем уроке вы научитесь вставлять различные специальные символы в свой документ.

воскресенье, 28 ноября 2010 г.

SharePoint Integration with Team Foundation Server

The purpose of this sticky post is to bring together information you will need when integrating SharePoint Products with Team Foundation Server 2010. This information includes links to relevant technical articles, help topics, blog posts, and other content. This post is a living document that will be updated with additional links as soon as new content is published.

- Where to find documentation about all things SharePoint Integration - Click here
- How to create a project portal for an existing team project - Click here
- Troubleshooting guide for SharePoint Integration issues - Click here
- TF252031: A SharePoint site could not be created for the team project collection. (HRESULT: 0x80040E09) - Click here

вторник, 9 ноября 2010 г.

HRESULT: 0x80070057 (E_INVALIDARG)

Issue:
When trying to debug an ASP.net website in Visual Studio you get the following error message:

Could not load file or assembly 'your project' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

Solution:
Clear out the temporary framework files for your project in: 

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\ 

Update: 

For Windows 7, the path is:
C:\Users\[username]\AppData\Local\Temp\Temporary ASP.NET Files\

For 64 bit systems with 'Framework' in the path the full path is:
C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\

суббота, 6 ноября 2010 г.

C# Stopwatch Samples

You want to measure the time required for your programs written in the C# language. This could be for a micro-benchmark or for routine and continuous performance monitoring. This document contains several tips and samples on Stopwatch in the C# language, which is very useful for this purpose.
Use Stopwatch to perform benchmarks of methods and statements.
It is built into the .NET Framework.
It can be used to produce timings per iteration.

Using Stopwatch

First, Stopwatch is a class in the .NET framework that is ideal for timing any operation in your C# programs. You must create Stopwatch as an instance. This makes it useful in multithreaded applications or websites.
=== Program that uses Stopwatch (C#) ===

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static void Main()
    {
        // Create new stopwatch
        Stopwatch stopwatch = new Stopwatch();

        // Begin timing
        stopwatch.Start();

        // Do something
        for (int i = 0; i < 1000; i++)
        {
            Thread.Sleep(1);
        }

        // Stop timing
        stopwatch.Stop();

        // Write result
        Console.WriteLine("Time elapsed: {0}",
            stopwatch.Elapsed);
    }
}

=== Output of the program ===

Time elapsed: 00:00:01.0001477
Description. The code includes the "using System.Diagnostics" namespace at the top. This is where the Stopwatch class is defined in the framework. You can see the Stopwatch is created with the new operator in Main.
It calls the Start method. The Start method tells the Stopwatch object to store the current time internally. Essentially, it queries the Windows performance code to find the current tick count of the system. This is extremely accurate.
It executes some slow code. The calls to Thread.Sleep in the loop are not useful and are just for the example. You can ignore them, except to note that they take about one second to complete.
It calls the Stop method. We call the Stop() method on the instance Stopwatch. This tells the Stopwatch to capture the current tick count of the system, also very accurate.
It displays the results. The Console.WriteLine method is called to output the time of the Stopwatch instance. The Elapsed property on Stopwatch is a TimeSpan struct, which overrides the ToString method. It outputs the final line.

Using Stopwatch.StartNew

For your benchmarks or diagnostics code, you probably will prefer the StartNew method. This uses a creational design pattern to return a new instance from a static type method. It eliminates typing and simplifies your code.
=== Program that uses StartNew (C#) ===

class Program
{
    static void Main()
    {
        // Create new stopwatch
        var stopwatch = System.Diagnostics.Stopwatch.StartNew();

        // Do something
        // [omitted]

        // Stop timing
        stopwatch.Stop();

        // Write the results [omitted]
    }
}
Description. We see the StartNew() method is called to create a new instance of StopWatch. For the example, I also show the var syntax, which is a shorthand for the type declaration. Also, I access the System.Diagnostics namespace directly in the statement.

Frequency and IsHighResolution

The Stopwatch class has some static properties and fields on it, including Frequency and IsHighResolution. These can be used to determine the internal configuration of Stopwatch, which depends on the machine and the installation of the .NET runtime.
Stopwatch.Frequency
This is a static field that tells you the number of ticks the Stopwatch uses
per second. You will want to use this to convert an elapsed ticks value, ElapsedTicks,
to a figure in seconds. Additionally, you can find values in milliseconds with this.
[Stopwatch.Frequency Field - MSDN]

Stopwatch.IsHighResolution
This is a static bool that tells you whether the Stopwatch is using high resolution
timing. Stopwatch isn't as useful when this is false.

Using ElapsedTicks

Here we see an example of using the ElapsedTicks instance property on Stopwatch. This is internally a readonly signed System.Int64 value. When you capture ElapsedTicks, you will have to manually do the calculations yourself to convert the values to seconds.
=== Program that uses ElapsedTicks (C#) ===

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Create a new Stopwatch
        var stopwatch = Stopwatch.StartNew();

        // Capture the elapsed ticks and write them to the console
        long ticks1 = stopwatch.ElapsedTicks;
        Console.WriteLine(ticks1);

        // Capture the ticks again. This will be a larger value
        long ticks2 = stopwatch.ElapsedTicks;
        Console.WriteLine(ticks2);
    }
}

=== Output of the program ===

11
7092 <-- This means the Console.WriteLine took over 7000 ticks
Description. The example code first creates a new Stopwatch with StartNew, and then captures the ElapsedTicks long property twice. The values are printed to the screen. The Console.WriteLine here was the most expensive operation. It took 7081 ticks.
Stopwatch ticks versus DateTime.Ticks. The ElapsedTicks value from Stopwatch is not normally the same as the DateTime.Ticks value. Stopwatch ticks are far more accurate, when the IsHighResolution property is true. Otherwise, they are equivalent.

Reset method

Here we note that the Reset instance method on Stopwatch effectively erases all the previous timer information to zero. You can usually simply create a new Stopwatch if necessary, which might result in simpler code.

IsRunning property

In this section, we note that Stopwatch also has an IsRunning property. This is only useful if your code uses the Stop or Reset methods in unpredictable ways. For most micro-benchmarks, it is not necessary.

GetTimestamp and static properties

Here in this final example we see possible values of several static properties and methods. The sample shows the Frequency property as well as IsHighResolution and GetTimestamp().
Stopwatch.Frequency:        14318180
Stopwatch.IsHighResolution: True
Stopwatch.GetTimestamp():   174412139895
Description of the values. These values were determined by printing the output of the expressions on the left. The Frequency indicates the number of ticks per second. GetTimeStamp() indicates the total elapsed ticks on the system.

Overhead

In this part, we address the performance impact caused by instantiating a Stopwatch. The Stopwatch class is slower than many operations in C# .NET. This applies when you are using Stopwatch throughout the lifetime of your application for routine monitoring. Using a Stopwatch is more expensive than string concatenations by a factor or two or three in my short test. This means it isn't extravagantly expensive.

Summary

Here we reviewed information about the Stopwatch class in the .NET Framework and C# programming language. Stopwatch is an incredibly useful class to use when performing diagnostics or benchmarks. One way I recommend using Stopwatch is for constant performance monitoring of your applications, not just with benchmarks.

Interface DataSources with ASP.NET 4's QueryExtender -- Visual Studio Magazine

"As far as ASP.NET developers are concerned, the Microsoft .NET Framework 3.0 and 3.5 were effectively 'no upgrade' releases, with the exception of two controls: the DataList and Pager. The .NET Framework 4, on the other hand, offers a number of new features aimed directly at a key issue for ASP.NET developers building business applications and managing data. The most interesting is the QueryExtender, which does two things. First, it substantially extends what filtering and sorting you can do with the LinqDataSource and the EntityDataSource. Second, it makes the two DataSources look alike when it comes to specifying what data you want."

IEnumerable Distinct comparer example

"The following example shows how to implement an equality comparer that can be used in the Distinct method."

ASP.NET Site-Map Security Trimming

"A common security requirement for Web sites is to allow only some members or other authenticated users to see certain pages. ASP.NET role management provides a way to restrict access to Web files based on security roles. Site-map security trimming provides a way to hide navigational links in a site map, also based on security roles. For information about role-base security, see Understanding Role Management."

Binding Stored Procedure Result from Entity Framework to ObjectDataSource Control

Binding Stored Procedure Result from Entity Framework to ObjectDataSource Control: "Not too long ago someone asked me how can they bind data returned from stored procedure to a gridview control. There are several ways to achieve that. You can either use EntityDataSource or ObjectDataSource Control. I find it easier to use ObjectDataSource control because it allows me to encapsulate logic inside my classes. The basic steps are as follows

1. Bring the Stored Procedure into the storage model.

2. Import the stored procedure into conceptual model. This will result in a method getting exposed on your derived object context.

3. Create a class that you can bind to ObjectDataSource control. On the class expose a method that returns data returned from the method created on your derived Object Context."

пятница, 5 ноября 2010 г.

Use varchar(max) instead of text in SQL Server

As you may know on SQL Server a varchar column can hold up to 8000 characters (each row can hold up to 8K, so it depends on the size of other columns), when you need to store more it is common to use the text or ntext datatypes. The problem with the text datatype however is that you can't call most string functions on the column, they also require more IO due to how they are stored internally.
In SQL Server 2005 Microsoft added support for varchar(max) and nvarchar(max), this new datatype can be used anywhere a regular length limited varchar can, but lets you store up to 2GB of data. Behind the scenes the varchar(max) stores up to the as much of the text as it can in the row (up to 8K), and then creates additional pages for any additional text. So in a lot of cases the text content will fit in the row, requiring much less disk IO.
Microsoft is said to be deprecating the text and ntext in future releases.
I also found an interesting blog entry which finds that when you alter a column from ntext/text to nvarchar(max)/varchar(max) the text content will still be stored in the external page, you should run UPDATE tableName SET columnName=columnName which will cause SQL server to store text more efficiently.

среда, 3 ноября 2010 г.

Why do I have to XmlInclude derived classes in order to serialize?

I have a shallow, but wide class heirarchy.  I have one base class with several derived classes.
During serialization, I pass a reference to the XmlSerializer.  The reference never points to the base class; it points to one of the derived classes.

So when I attempt to serialize

public class Base

public class Derived1 : Base
public class Derived2 : Base
public class DerivedN : Base


XmlSerializer ser = new XmlSerializer(typeof(Base));
StreamWriter writer = new StreamWriter(sFilename);
ser.Serialize(writer, DerivedClassFactory.CreateRandom() );
//DerivedClassFactory can create any of the derived classes..



On this last line, the execution fails with a run time error:
"The type LibraryName.Classname was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

I took this suggestion and added
    [System.Xml.Serialization.XmlInclude(typeof(Derived1))]
    [System.Xml.Serialization.XmlInclude(typeof(Derived2))]
    [System.Xml.Serialization.XmlInclude(typeof(DerivedN))]

to the Base class definition.  The code now executes fine.  The problem is, what if I do not own the base class definition?  What if I do not have access to the base class definition?  Isn't there a better way to do this????




You can achieve the same by using different XmlSerializer ctor, the one that takes an univerce of “known” types:   public XmlSerializer(Type type, Type[] extraTypes){..}

In your case: new XmlSerializer(typeof(Base), new Type[] { typeof(Derived1), ..});

вторник, 2 ноября 2010 г.

regex for csv in c# .net

After much searching, this is the best RegEx I can find for splitting a line of text from a CSV file:
(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)

Here is the magical working code:
protected virtual string[] SplitCSV(string line)
      {         System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline) 
            | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
         Regex reg = new Regex("(?:^|,)(\\\"(?:[^\\\"]+|\\\"\\\")*\\\"|[^,]*)", options);
         MatchCollection coll = reg.Matches(line);
         string[] items = new string[coll.Count];
         int i = 0;
         foreach(Match m in coll)
         {
            items[i++] = m.Groups[0].Value.Trim('"').Trim(',').Trim('"').Trim();
         }
         return items;
      }

How To: Reading and Writing Text Files in C# .Net

Introduction

Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy. The following sequence outlines the basic steps necessary to work with text files:
  1. Open the file
  2. Read/Write to the file
  3. Close the file
It's that simple.  Listing 1 shows how to write text data to a file.

Writing to a Text File

Listing 1: Writing Text Data to a File: TextFileWriter.cs
using System;using System.IO;
namespace csharp_station.howto
{
    class TextFileWriter
    {
        static void Main(string[] args)
        {
            // create a writer and open the file            TextWriter tw = new StreamWriter("date.txt");
            // write a line of text to the file
            tw.WriteLine(DateTime.Now);
            // close the stream
            tw.Close();
        }
    }
}
This program creates a text file when it runs. In the directory where the executable program is located, you'll find a file named date.txt. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran:
2/15/2002 8:54:51 PM
The first task in Listing 1 is to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, the StreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding. Here's the line that opens the date.txt file:
            TextWriter tw = new StreamWriter("date.txt");
Using the TextWriter instance, tw, you can write text info to the file. The example writes the text for the current date and time, using the static Now property of the DateTime class. Here's the line from the code:
            tw.WriteLine(DateTime.Now);
When you're done writing to the file, be sure to close it as follows:
            tw.Close();

Reading From a Text File

Listing 2 shows how to read from a text file:
Listing 2: Reading Text Data from a File: TextFileReader.cs
using System;using System.IO;
namespace csharp_station.howto
{
    class TextFileReader
    {
        static void Main(string[] args)
        {
            // create reader & open file            Textreader tr = new StreamReader("date.txt");
            // read a line of text
            Console.WriteLine(tr.ReadLine());

            
// close the stream            tr.Close();
        }
    }
}
In Listing 2, the text file is opened in a manner similar to the method used in Listing 1, except it uses a StreamReader class constructor to create an instance of a Textreader. The StreamReader class includes additional overloads that allow you to specify the file in different ways, text format encoding, and buffer info. This program opens the date.txt file, which should be in the same directory as the executable file:
            Textreader tr = new StreamReader("date.txt");
Within a Console.WriteLine statement, the program reads a line of text from the file, using the ReadLine() method of the Textreader instance. The Textreader class also includes methods that allow you to invoke the Read() method to read one or more character or use the Peek() method to see what the next character is without pulling it from the stream. Here's the code that reads an entire line from the text file:
            Console.WriteLine(tr.ReadLine());
When done reading, you should close the file as follows:
            tr.Close();

Summary

This article showed how to write text to a file and read it back out. For more details on additional methods, consult the .NET Frameworks reference on the StreamWriterStreamReaderTextWriter, andTextreader classes.