.Net
2013 has started great and the SQL community is already brimming with events. At some of these events you can come say hi. I’ll be glad you do! These are the events with dates and locations that I know I’ll be speaking at so far. February 16th: SQL Saturday #198 - Vancouver, Canada The session I’ll present in Vancouver is SQL Impossible: Restoring/Undeleting a table Yes, you read the title right. No, it's not about the usual "one table per partition" and "restore full backup then copy...
What better way to end the summer and start those productive autumn days ahead than with a fresh new version of the SSMS Tools Pack.
This is a big release with two new features that are huge productivity boosters.
First new feature are Tab Sessions. Every SQL tab you open is saved every N (default 2) minutes and is stored in a session. This works similar to internet browser sessions. Once you reopen SSMS you can restores your last session with a click of a button. You even get every window connected to the server it was previously connected to. The Tab...
SQLBits: April 7th - April 9th 2011 in Brighton, UK
Free community event on Saturday (April 9th) with a paid conference day on Friday (April 8th) and a Pre Conference day full of day long seminars (April 7th).
It'll be a huge event with over 800 attendees and over 20 MVPs. I'll be presenting on Saturday April 9th.
SQL in the City: July 15th 2011 in London, UK
One day of free SQL Server training sponsored by Redgate. Other MVP's that'll be presenting there are Steve Jones (website|twitter), Brad McGehee (blog|twitter) and Grant Fritchey (blog|twitter)
At both conferences I'll be presenting about database testing.
In...
SQL injection is a method by which a hacker gains access to the database server by injecting specially formatted data through the user interface input fields. In the last few years we have witnessed a huge increase in the number of reported SQL injection attacks, many of which caused a great deal of damage.
A SQL injection attack takes many guises, but the underlying method is always the same. The specially formatted data starts with an apostrophe (') to end the string column (usually username) check, continues with malicious SQL, and then ends with the SQL comment mark (--) in order...
WMI is Windows Management Instrumentation infrastructure for managing data and machines. We can access it by using WQL (WMI querying language or SQL for WMI). One thing to remember from the WQL link is that it doesn't support ORDER BY. This means that when you do SELECT * FROM wmiObject, the returned order of the objects is not guaranteed. It can return adapters in different order based on logged-in user, permissions of that user, etc… This is not documented anywhere that I've looked and is derived just from my observations.
To get network adapters we have to query the Win32_NetworkAdapter class....
Today I had an interesting problem.
If I rebuilt my solution every thing would succeed but after that if i pressed F5 (build) the whole solution would get built again but it would error out. Now this doesn’t make any sense because the difference between Build and Rebuild is that Rebuild always compiles and links all files + all dependencies, while Build only compiles and links files that have changed since the last build. So everything should be fine. The thing about our solution is that the we have some post build events that do some IL merge, etc… the...
There are times when you want to have one .cs file in multiple projects. However if you do Add existing item you’ll notice that the file is copied to each project’s folder. This is not what we want.
The solutions is of course pretty simple once you know where to look. In the Add existing item dialog you have to add the file as a Link as is shown on the picture:
And there you go. you can have one file in multiple projects.
A while back we had an interesting problem at work. We were calculating MD5 hashes for some values in both .Net and SQL Server and although the input values were all the same our MD5 hashes were different. After some time spent looking dumbfounded at the code I’ve realized what the bug was and started laughing. I saw that HashBytes function was the “culprit”. HashBytes function was introduced in SQL server 2005 to simplify creating hashes in the database. It can convert values to MD2, MD4, MD5, SHA, or SHA1 formats. HashBytes' result depends on the input text’s data type...
With this new version you can use it for SQL Server Management Studio 2008 and SQL Server Management Studio 2008 Express.
I've added a new feature to Search through the Database data. There are times when you'd like to find some value but can't remember in which table it is.
Also the SQL Query History Log Viewer has been remodeled. I'm open to suggestions on how to improve it further.
You can also have the SSMS Tools Pack installed for both SSMS 2005 and SSMS 2008 on the same machine, however they don't share the same settings.
I would also like to...
Let us start with a simple question: What is the goal of software development, be it database or .Net (or any other language)? The first answer would be: Customer satisfaction! And you'd be right. However there's more to customer satisfaction then the immediate product delivery effect. We have to think about future change requests, maintenance periods, etc... Almost every business application out there consists of 2 basic parts: database back end and some kind of front end that consumes the data. In our case the front end is anything with access to the database. In regard to future code...
On Monday I've finally installed the VS 2008 on my system. I put the installation DVD in, choose custom install, pressed run and went to lunch. After I returned, my computer was one VS 2008 richer. And this is where the fun started. We use command line MSBuild and when I fired up the Visual Studio 2008 Command Prompt I got this:
Setting environment for using Microsoft Visual Studio 2008 x86 tools.
\Utilities\Bin\x86";C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\ATI Technologies\
ATI Control Panel;C:\Program Files\IDM Computer Solutions\UltraEdit-32;C:\Program Files\Microsoft SQL Server\8
0\Tools\BINN;C:\Program Files\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Server\90\Too
ls\binn\;C:\Program Files\Microsoft SQL Server\90\DTS\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\Bin
n\VSShell\Common7\IDE\;C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;C:\Program Fi
les\QuickTime\QTSystem\;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Program Files\Microsoft...
This is an implementation of the Grayscale Immersion Watershed Segmentation in C# based on the
Vincent-Soille immersion watershed algorithm
Read Full Post.
In 2007 I've worked a lot with NUnitForms. It contains all major controls testers and you can easily create
your own ones for e.g. a Data Grid or a 3rd party control. I had to create one for Janus GridEx and it wasn't really
that hard. A little reflection went a long way :) Lately, the whole project was at a standstill for some time but now it seems
it's revitalizing nicely with new people on board. So if you haven't yet go take look. This is just one open source GUI testing platform
and I'm sure there are others... I haven't...
Today I feel a bit evil minded so I thought I'd share this little prank-friendly function.
If you put this into a .Net Assembly you import to SQL Server as a function or a stored procedure
you can wreck some real havoc :)
private static void SQLPrank()
{
Random r1 = new Random(DateTime.Now.Millisecond);
int lowerBound = r1.Next(1000, 2000);
int upperBound = r1.Next(3000, 4000);
int randomNumber = r1.Next(1000, 4000);
/*
1000 2000 ...
UPDATE:
After i've been proven wrong in the comments below I have to say this:
Go take a read of this article to see how circular references are really handled.
While Delegate.GetInvocationList() really is a great and usefull thing and it could be used in clearing up events,
there's no need for it since you can do that as easily by simply unsubscribin from the event when
you want to dispose your class.
You can read this post on, but know that this example is WRONG, except for the last part about
Observer pattern and WeakEvent pattern.
Maybe you should read this post since...
I can't believe these properties aren't already natively implemented. Come on Microsoft... we do live in the year 2007 you know!!
I know that you can do this using P/Invoke and SendMessage but i wanted a nice managed way of finding
the current line and column of the Caret position in a multiline TextBox.
After a bit of experimenting i've come up with this extended class:
public class TextBoxEx : TextBox
{
public TextBoxEx()
{ }
public void GoTo(int line, int column)
{
if (line...
We're all familiar (i hope :)) with this construct:try
{
// ... some code here ...
}
catch (Exception ex)
{
// one of these 2 lines are usually seen
throw; // presereves the full call stack
//throw ex; // changes the origin of exception to this method
}
finally
{
// more stuff here
}
It's a standard error catching routine in .Net.
But what if you want to pass some user info back to the caller method with the Exception being thrown?
Reader... meet Exception.Data. Exception.Data... meet reader.
Now that you're both properly aquainted...
I haven't been using this function at all. Who knows why... maybe because i didn't know about it :)
But in my latest pet project i had to do something really quickly on a lot of items in a list.
After a bit of research into foreach and for loops, i saw the List<T>.ForEach method.
Did some testing and sure thing List<T>.ForEach proved to be faster than others.
I thought about posting the whole setup and how i've tested it, but then i saw that Dustin Russell Campbell
did exactly the same thing a bit more thoroughly, so why double it up, right?
Read it, like...
A negative Width value??
I can hear it now:
Are you insane Mladen?? Do you want our apps going around looking ugly??
Well... of course I do! It means i can go around fixing them for big bucks :))
But joking aside, -1 and -2 width values are very usefull.
Setting the width to be -1 means that the column will have the width of the longest item in it.
Setting the width to be -2 means that the column will have the width of the column heading.
Pretty cool, no?
Tests are a pretty much a must in today's world of programming. There's even a whole Test Driven Development methodology that deals with this.
There comes a time when we have to test how our app interacts with the database.
More here
Arity is the number of arguments that a method takes.
For example
void MyMethod(int i1, int i2)
has an arity of 2, since it takes 2 arguments.
In C# the arity is marked with `
"So why is this important?", you might ask.
Well it isn't. Until you deal with reflection. :)
A while ago I had to create some code using CodeDOM and i was getting a few errors that the ` in code isn't correct
when i tried to compile the code.
Here's an example of how arity is shown using reflection:
List<string> list = new List<string>();
Console.WriteLine(list.GetType().ToString());
// output: System.Collections.Generic.List`1[System.String]
Dictionary<int, string> dict = new Dictionary<int, string>();
Console.WriteLine(dict.GetType().ToString());
// output: System.Collections.Generic.Dictionary`2[System.Int32,System.String]
You can...
Now this is something i really didn't think it would compile in C#.
private int _someVar = 0;
private void DoStuff1()
{
int _someVar = 0;
_someVar = 6;
// ... code that uses _someVar
}
private void DoStuff2()
{
_someVar = 5;
// ... code that uses _someVar
}
We should at least get a warning if you ask me...
One learns something new every day.
This is something i assumed was common knowledge, but apparently it isn't.
If you want to have a method in your derived class with the same name as the one in the base class and the base class one isn't marked
as virtual you can use the NEW keyword.
This is also the default behaviour and the compiler treats the child class method as new, however you get a warning for this.
Some code to illustrate this:
public class BaseClass
{
public BaseClass()
{ }
public void IAmANonVirtualMethod()
{
Console.WriteLine("IAmANonVirtualMethod...
I've written an article about Multiple Active Result Sets (MARS) and it's published on SQLTeam.com
Multiple Active Result Sets is a new SQL Server 2005 feature that, putting it simply, allows the user to run more than one SQL batch on an open connection at the same time.
More here.
I have written before about running Windows Forms GUI tests on a compiled application exe here.
And i must say that it works GREAT!
I had a few problems of which the most annoying was the Drag and Drop functionality. If you have it enabled with AllowDrop = true
on your controls or any other 3rd party controls the moment your control gets loaded you will get this error:
System.InvalidOperationException: DragDrop registration did not succeed. --->
System.Threading.ThreadStateException: Current thread must be set to single thread apartment (STA) mode
...
I just hate having nulls in my DateTime columns. Having them always mean you also have to handle them in some way in your app.
The most common way is something like this:
public DateTime SomeDate
{
get
{
if (dr["SomeDate"] == DBNull.Value)
return DateTime.MinValue;
else
return (DateTime)dr["SomeDate"];
}
set
{
...
A while ago i explained why do you need a [Flags] attribute on the Enum here. We'll since then i was happy with my flags until i got to the point of having 16 flags. So why is that a problem? Well it's not really but 2^16 is how much? If you had to open the all mighty calculator you see my point. I stop counting powers of 2 after 4096 = 2^12. I see no reason to remember those. That's why I wanted to write my enums a bit simpler. Like saying this is 2 to the power of 1, 2,...
NUnitForms is a pretty awsome tool for GUI unit testing.
However it lacks one major thing. You can't test a whole exe or dll.
For example if you have a MyTestApp.exe with various win forms etc., you can't just run it and test it's gui.
And i really wanted to do it because our app sets a lot of other stuff and it's pretty complex so you can't just
call Form.Show() and start playing with it.
So with a lot experimenting and reading and going through NUnitForms source code I've come up with a way to do it.
The first thing to know is how NUnitForms...
Ever missed a Prod(columnName) function that works like a sum but it multiplies the column values?
If you have then you probably know that there's a workaround using a bit of high school math knowledge about base 10 logarithms.
It goes like this:
SELECT exp(sum(log(c1))) as MultiplicationResult FROM test
However this little helper doesn't yield correct results for a large enough set, because it goes from integer to decimal.
So there's a possibilty of an error.
This is also a perfect example of a user defined aggregate that can be implemented in CLR. And becuase there's no int to deciaml transition
it yields correct results.
This...
If you're reading this blog you're probably familiar with ADO.Net and it's SqlCommand object.
Now this SqlCommand object has a CommandTimeout property that specifies the number of seconds
after which the command will terminate. The default value is 30.
Now we get to the SqlConnection and the connection string. in the connection string you can specify
Connection Timeout = numberOfSeconds
after which the connection timeouts.
We also have to set the SqlConnection object to the SqlCommand.Connection property.
Nothing special so far.
Now my question is:
If we set the Connection Timeout in our connection string to higher value than the SqlCommand.CommandTimeout's is,
WHY DOESN'T the SqlCommand.CommandTimeout get set to that higher...
Enums are a great tool. They give meaning to meaningless numbers. I love using them as flags since it couldn't be simpler. So i always used the [Flags] attribute on my enums But why do we need that attribute? You can bitwise non [Flags]'d enums just the same. The difference lies in the Enum.ToString() method. If your enum has the [Flags] attribute set then the ToString() will return a CSV separated list of bitwised enum values. If there's no [Flags] attribute ToString() will return a number for every bitwised value. As always it's best ilustrated with an example:[Flags]
enum StateWithFlags
{
...
A SELECT tag is what a DropDowList in Asp.Net renders to in HTML and it's a standard web control. If you ever had to pop up a DIV over it (a menu in most cases) then you know that in IE6 and below and FireFox 1.x the select tag showed over the div tag. This was/is annoying as hell. There was a hack for this by putting an IFrame into a DIV but this introduced problems with linking etc... Now FINALLY this is fixed in IE7 and FireFox 2.x. I'm glad! Aren't you? :)
I was playing with some historical data (family tree) and i wanted to store data in sql server. When looking into family trees you reach the minimum datetime value of 1753-01-01 very soon. But .Net can save dates from 1.1.0001 on. So i went looking into using SQL CLR user defined datatype (UDT).
UDT's are interesting because you have to serialize them.
There are 3 ways of doing that:
- Format.Native
- Format.UserDefined
- Format.Unknown
When Format.Native is used you can only use blittable datatypes. Bol says these are:
bool, byte, sbyte, short, ushort, int, uint, long, ulong, float, double, SqlByte, SqlInt16, SqlInt32, SqlInt64, SqlDateTime,...
In a previous post I've shown how to use High precision timer.
That method had a drawback of working for whole server not distiguishing between connections.
So if you ran the time measurement in 2 different windows in SSMS the times would be incorrect.
You'd get the correct time in the window which was run last.
This of course isn't very usefull for proper performace diagnosys.
So with little experimenting i've managed to fix the timer to work properly for each connection.
The code is self explanatory. For each function run I return the spid to which it belongs and i store the HiPerfTimer objects in a...
Update: I've created a muliti connection version which can be found here.
Usually time measuring in sql server is done in 2 ways: with the help of GetDate() function or with SET STATISTICS TIME ON.
For doing hardcore performance analysis where any time reduction counts you need more precise measuring capabilities and the two mentioned are only accurate to a milisecond order.
In SQL Server 2000 there was no practical way to change this.
SQL server 2005 to the rescue. It has DMV's which hold time in microseconds which is better. but they can't be always used to measure the duration of the statement. You...
A coworker found this in code generated by Visual Studio 2005:
this.sqlSelectCommand2.CommandText = "SELECT columnName1, columnName2, columnName3, columnN" + "ame4, columnName5, columnName6 FROM MyViewFromMa" + "nyTables"
Searching for...
Ever since I discovered the ?? colaesce operator I embraced it with full force.
Today I discovered another usefull use:
// this:
string[] arrayOfStrings1 = new string[] { "arr1s1", "arr1s2", "arr1s3" };
foreach (string str in (arrayOfStrings1 ?? new string[0]))
{
// do some stuff on the array elements
}
// equals to this:
string[] arrayOfStrings2 = new string[] { "arr2s1", "arr2s2", "arr2s3" };
if (arrayOfStrings2 != null)
{
foreach (string str in arrayOfStrings2)
{
// do some stuff on the array elements
}
}
// in terms of what it does
This...
I had so much "fun" with viewstate last weekend.
I'm developing a site that has a master page Master.aspx and a few child pages (Page1.aspx, ..., pageN.aspx).
Now when rendering HTML that is displayed an ASP.NE rendering engine first reads the child page
then takes the master page and incorporates it's contorls into the child page control hierarchy so the
child page actually becomes the overall master. A master page is treated as a user control, after all it
is derived from UserControl class. All this happens on the pre Init part of the Page creation.
So now comes in the viewstate. I won't...
I've come accross this these articles which i think are
a must read before starting to design any kind of a serious application
Designing and building a robust data access layer
Managing SQL exceptions in .NET applications
Very nice.
I had some fun this weekend with ASP.Net 2.0 Master pages and submit buttons when pressing Enter key. The catch here is that with the introduction of Master pages there's only one form per page which is specified in the master page.
UI simplicity for users has been pressing the Enter key when they wanted to submit the form data.
In older versions of ASP(.Net) you could put any number of forms on the page. The only rule was that they couldn't be nested. When you were in a form and you pressed Enter the browser used the submit button of that form...
I've written about bulk insert methods for text files in sql server 2005.
.Net 2.0 brings the SqlBulkCopy Class in System.Data.SqlClient namespace.
Speed wise it can't even compare to native sql server methods but it's usefull
if it's the only viable solution.
SqlBulkCopy.WriteToServer has 4 overloads:
SqlBulkCopy.WriteToServer (DataRow[])
Copies all rows from the supplied DataRow array to a destination table specified by the
DestinationTableName property of the SqlBulkCopy object.
SqlBulkCopy.WriteToServer (DataTable)
Copies all rows in the supplied DataTable to a destination table specified by the
DestinationTableName property of the SqlBulkCopy object.
SqlBulkCopy.WriteToServer (IDataReader)
Copies all rows in the supplied IDataReader to a destination...
In my previous post i showed how a generic comparer class in .net C# 2.0 can be made with the use of reflection.
This is the version 2. Faster, preetier, better. :))
It uses IL code generation in runtime with the use of a new .Net 2.0 class DynamicMethod.
More here.
I've been doing a "bit" of .net development lately and i had a problem where i would get
a variable of type object and it's type in a string. So I wondered how to convert it to proper type at runtime.
The solutions is one of those things that is unbeliveably hard to find because you don't really know what
to search for, but when you find it, it seems unbeliveably simple. :)
Here it is:
string sType = "System.Int32";
object o1 = "123";
object o2 = Convert.ChangeType(o1, Type.GetType(sType));
Type t = o2.GetType(); // this returns Int32 Type
I often wondered why is there no ISortable interface of somekind in .Net.
I recently needed to sort items in the context menu in alphabetical order.
Sorting them was the begining of a journey which produced this class.
It sorts simple objects like int, string, etc... as well as complex objects
that have properties you wish to sort on.
EDIT: 2006-07-06
I've removed the code because I published version 2 of this class which is better and can be found here.
I had to convert a project from .Net 1.1 to .Net 2.0 this week.
It built ok with a few warnings. Amongst others there was this one:
Warning: 'System.Threading.WaitHandle.Handle' is obsolete: 'Use the SafeWaitHandle property instead.'
That's cool, no problem, right? As it turns out it's not just replacing one property with another.
Handle property is IntPtr type and SafeWaitHandle is a class.
So .Net 2.0 has a new class called SafeWaitHandle which represents a wrapper class for a wait handle.
Why it's there is well explained on BCLTeam's blogs here.
So what to do?
It preety simple in the end.
instead of
_Event.Handle;
just use
_Event.SafeWaitHandle.DangerousGetHandle();
where _Event is...
If there was one thing that was going preety steadily on my nerves in VS2005 was region collapsing/opening with mouse.
So i was determined to find a shortcut for it.
And I found so much more...
Every shortcut there is in Visual Studio 2005 is listed here.
All SSMS keybard shortcuts are listed here.
These two pages are the holy grail of fast development if you ask me :))
oh and by the way.... collapsing/opening a region is CTRL + M + M. Yes, hit M twice while holding CTRL.
And do try CTRL + I... it's pure pleasure. a hint: Incremental Search :) <-- select text...
This is a good explanation on how to acctually bill a customer for your service over a credit card in your web application.
More here.
Visual studio's DataSet visualizer is ok but it's not that great :))
This one is excellent and if you do a lot of db development (which you do if you're reading blogs on SQLTeam :)) you need this.
You can get it here.
I've posted an article about WebDAV protocol and my use of it for accessing MS Exchange store. WebDAV is based on HTTP 1.1 and is based on sending XML requests to find, set, remove and search for item properties.
Microsoft recommends that Exchange access from .Net is made with WebDAV. This MS article explains more.
It also works with Office documents...
More here.
If you do a lot of managed/unmanaged code interaction with COM objects
then this is a page you must bookmark.
http://www.pinvoke.net/
I saw this operator in use today in a code example. I must say when I figured what it does my geek side went "YES!!!!".
It resembles an old "if" abbreviation:
(condition ? true result : false result);
now what ?? does is a null check same as the SQL Servers Coalesce function. It returns the first non null parameter.
function test(class1 variable)
{
if (variable == null)
variable = new class1();
// equals to
variable = (variable ?? new class1());
}
I'm starting to use this and giving a "What!?!???" moment...
why is there no reverse string function in c#?? Is there realy no need for that function??
there are of course a few ways to make your own reverse function. most favorite is definitly the one using recursion with substring. that's preety cool i thought why not... and then i remembered something that i learned in my first year of college... bitwise operations. i knew that there was a handy little way of switching 2 values using something with XOR without using a 3rd variable. i just couldn't remember it... so i went googling... it sure was faster than going through...
Well we decided we should do some unit testing on our asp.net project. We used NUnit.Asp. i must say the thing works realy great. the whole thing is based on xml document model of the page. so accesing tags and their attribs is preety simple. the only "drawback" i could think of is that every tag you want to get has to have an id. all in all i must say the thing is quite usefull. i build some wrapper classes that we needed and we could test anything you can think of, except javascripts that executed on the client...