Interesting programming ideas, solutions, and logic that I have used to solve problems or have come across throughout my career.
About Me
- William Andrus
- Northglenn, Colorado, United States
- I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).
Tuesday, December 18, 2007
BizTalk Blogs
RSS: http://biztalkblogs.com/RssDoc.xml
Spell Checker for your code's comments
A spell checker for your comments in Visual Studio 2005 and Visual Studio 2008. This is a nice tool, I hate looking stupid because of stupid spelling mistakes. When you build your project(s) the spelling mistakes show up under "Messages" (third tab in the Error List). Brought to you by: http://blogs.msdn.com/webdevtools/archive/2007/12/13/spell-checker-for-html-asp-net-jscript-vb-c-css-and-c-for-visual-studio-2005-and-2008.aspx#comments
Monday, December 17, 2007
Powershell and BizTalk
Powershell is a really nice feature and I believe anyone that has any basic UNIX/Linux knowledge should be able to pick up the basics real quick.
Wednesday, November 07, 2007
Bug?? Reference variable arrays
1 public static int[] MainArray = new int[2] { 0, 0 };
2 static void Main(string[] args)
3 {
4 GetArray();
5 }
6 private static void GetArray()
7 {
8 MakeNewArray(MainArray);
9 }
10 private static void MakeNewArray(int[] p)
11 {
12 p[0] = 1;
13 Console.WriteLine("p[0]:" + p[0].ToString());
14 Console.WriteLine("MainArray[0]:" + MainArray[0].ToString());
15 Console.ReadLine();
16 }
Result:
p[0]:1
MainArray[0]:1
He wanted a copy version of the integer array, but instead it was acting like it was being reference. The response of the code seems wrong since you would expect it to make a seperate array and not reference the MainArray.
What seems to be happening is that since these are arrays, and of the type Reference. Then the arrays are placed on the heap, with the variable names placed on the stack (some what). So, when making a call to a seperate method, the new variable p is then placed on the stack, but pointing to MainArray's values on the heap. Giving a reference type behavior. The solution is to make a copy of the array.
1 public static int[] MainArray = new int[2] { 0, 0 };
2 static void Main(string[] args)
3 {
4 GetArray();
5 }
6 private static void GetArray()
7 {
8 MakeNewArray();
9 }
10 private static void MakeNewArray()
11 {
12 int[] p = new int[MainArray.Length];
13 Array.Copy(MainArray, p, MainArray.Length);
14 p[0] = 1;
15 Console.WriteLine("p[0]:" + p[0].ToString());
16 Console.WriteLine("MainArray[0]:" + MainArray[0].ToString());
17 Console.ReadLine();
18 }
Result:
p[0]:1
MainArray[0]:0
Tuesday, November 06, 2007
Upgrading from .Net Framework 1.0 to 3.5
- source: http://blogs.msdn.com/pandrew/archive/2007/10/25/how-to-upgrade-from-net-framework-1-0-to-net-framework-3-5.aspx
- First upgrade your code from .NET 1.0 to .NET 1.1 using Visual Studio 2003. It has a project upgrade tool with some assistance.
Next use Visual Studio 2008 to upgrade the project from .NET 1.1 to .NET 2.0. The upgrade wizard here does not change your code. It will show you warnings for things that you have to change but you will have to go change them. You also have to fix all your new compile errors and do a full retest.
Once you're at .NET 2.0 the migration to .NET 3.0 and .NET 3.5 is easy. It's primarily just about using the new features available in these new versions of the framework. All your existing code should work fine, in fact you most likely wont even need to recompile.
The .NET 1.1 -> .NET 2.0 breaking changes are detailed here: http://msdn2.microsoft.com/en-us/netframework/aa570326.aspx
Here's a helpful blog entry from Brad Abrams on upgrade experience:
http://blogs.msdn.com/brada/archive/2007/01/15/real-world-customer-experience-in-migrating-from-net-framework-1-1-to-2-0.aspxHere's another great post on this topic deom Daniel Moth:http://www.danielmoth.com/Blog/2007/10/migrating-from-net-framework-v1x-to.html
So, I guess they make the transition from 1.0 to 3.5 look easy. Just hope I never have to do it. <^_^>
Monday, November 05, 2007
SQL Server 2008 Date and Time data types
Here are the new data types for SQL Server 2008:
Data type | Format | Range | Accuracy |
time | hh:mm:ss[.nnnnnnn] | 00:00:00.0000000 through 23:59:59.9999999 | 100 nanoseconds |
date | YYYY-MM-DD | 00001-01-01 through 9999-12-31 | 1 day |
smalldatetime | YYYY-MM-DD hh:mm:ss | 1900-01-01 through 2079-06-06 | 1 minute |
datetime | YYYY-MM-DD hh:mm:ss[.nnn] | 1753-01-01 through 9999-12-31 | 0.333 second |
datetime2 | YYYY-MM-DD hh:mm:ss[.nnnnnnn] | 0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999 | 100 nanoseconds |
datetimeoffset | YYYY-MM-DD hh:mm:ss[.nnnnnnn] [+-]hh:mm | 00001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999 (in UTC) | 100 nanoseconds |
Source: http://blogs.msdn.com/usisvde/archive/2007/11/05/get-a-date.aspx
Friday, November 02, 2007
WCF Tutorial
I did change the language to C# for my version, since I perfer it over VB.Net. There were some changes that I had to go about in a different way to get it to be successful.
Example:
Dim t As Type = GetType(ServiceLib.HelloService)
vs.
ServiceLib.HelloService hs = new ServiceLib.HelloService();
Type t = Type.GetTypeArray(new object[]{hs})[0];
Tuesday, October 30, 2007
Parallel Processor Programming
I really like this concept because it is easier to understand, implement and faster performance compared to threading.
http://msdn.microsoft.com/msdnmag/issues/07/10/Futures/default.aspx
Beware of AJAX update panel
http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/
He discusses the concept of the Update Panel. When you are doing a simple update inside the panel, you have to remember that it acts like a refresh but only returning the necessary data to that panel. This is obviously a huge load on the server.
Instead try using the web service method with the AJAX library to get a cleaner result.
I'm more of the old school ASP.Net 2.0 where I'm use to the asynccallback method. In thinking that the update panel was a simpler, quicker solution was nice though, but this just makes more sense.
String Sort vs. Word Sort in .Net
In the two sorting styles these would be equal:
String Sort: 'co-op' vs. 'co_op'
Word Sort: 'co-op' vs. 'coop'
In the string sort the minus and underscore are treated as symbols which are given the same "weight".
In the word sort the minus and underscore are treated as "special" symbols with differ weights.
//
// Sorting Flags.
//
// WORD Sort: culturally correct sort
// hyphen and apostrophe are special cased
// example: "coop" and "co-op" will sort together in a list
//
// co_op <------- underscore (symbol)
// coat
// comb
// coop
// co-op <------- hyphen (punctuation)
// cork
// went
// were
// we're <------- apostrophe (punctuation)
//
//
// STRING Sort: hyphen and apostrophe will sort with all other symbols
//
// co-op <------- hyphen (punctuation)
// co_op <------- underscore (symbol)
// coat
// comb
// coop
// cork
// we're <------- apostrophe (punctuation)
// went
// were
//
Now there is a problem that occurs when using a hypen (‐) U+2010 vs. hypen-minus U+002d (-) in string comparisons. The hypen-minus is treated as a minus, which could cause confusion.
So be careful when using the String.Compare function.
Interesting Note: StringCompare is used in SQL-Server for sort keys.
Source: http://blogs.msdn.com/michkap/archive/2007/09/20/5008305.aspx
So basically use the default for a lingusitc sort, but use CompareOptions to do a ordinal sort.
Source: http://msdn2.microsoft.com/en-us/library/system.globalization.compareoptions.aspx
Monday, October 29, 2007
3 common ASP.Net AJAX mistakes
Source: http://encosia.com/2007/10/24/are-you-making-these-3-common-aspnet-ajax-mistakes/
In summary:
- Page_Load executes during every partial postback, same as regular postbacks.
- Use IsPostBack and IsInAsyncPostBack to avoid accidental execution of Page_Load code during partial postbacks.
- In conjunction with __doPostBack, __EVENTTARGET may be used to limit UpdatePanel life cycle event execution to only the targeted panel.
- Control events, such as Click and SelectedIndexChanged, fire after Load events.
By using PreRender instead of Load, you can allow control events to be handled before your code executes.
Friday, October 26, 2007
Ramp Up
I just hope they will have one for VS 2005 to VS 2008 soon.
Thursday, October 25, 2007
Optimize your regular expressions
She went into the issue that if you don't optimize your regular expressions, the run time can be increase exponentially as the size of the string increases.
The reason for this, is because the regular expression is a NFA (Non-Deterministic Finite Automata)
Her example:
given the string: helloworldhelloworld
using regex: ([a-z]+)*= versus [a-z]*
given the string: abcde
Regexp: (abe|abc)(dg|dc|de) versus ab(e|c)d(g|c|e)
The long version
The order of execution here will be something like
a matches a in abe
b matches b in abe
c doesn't match e in abe, backtrack to try with the next expression
c matches c in abc - done with first part
d matches d in dg
e doesn't match g in dg, backtrack to try with the next expression
e doesn't match c in dc, backtrack to try with the next expression
e matches e in de - done with the regular expression
She recommends to avoid/decrease
- nested quantifiers (*, +, {m,n})
- backtracks
- ambiguous matches (i.e. in this case the number of combinations that cause a positive match for part of the string)
Friday, October 19, 2007
Debugging Tools for Windows 32-bit version
http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx
Thursday, October 18, 2007
Wednesday, October 17, 2007
Funny, but true: Tester's Translation Table
"It seems to me that lots of people are experiencing lots of confusion regarding what lots of the testing terms we throw around signify. In an effort to remedy this circumstance I have applied my investigatory powers to observe what people really mean when they say these words. Forthwith, the answers which I have compiled:"
http://blogs.msdn.com/micahel/archive/2007/10/17/ATestersTranslationTable.aspx
Concat strings in Javascript performance.
So basically they are fixing the performance speed it takes to concat strings in javascript for the next release of IE. The improvement is very significant.
Monday, October 15, 2007
Command Line short-cut variables
%systemroot% = value from GetWindowsDirectoryW
%systemdrive% = first two characters from GetWindowsDirectoryW
%systemdir% = value from GetSystemDirectoryW
%username% = value from GetUserNameW
%programfiles% = value from ShGetFolderPathW(..., CSIDL_PROGRAM_FILES, ...)
%userstartmenu% = value from ShGetFolderPathW(..., CSIDL_STARTMENU, ...)
%allstartmenu% = value from ShGetFolderPathW(..., CSIDL_COMMON_STARTMENU, ...)
%userdesktop% = value from ShGetFolderPathW(..., CSIDL_DESKTOPDIRECTORY, ...)
%alldesktop% = value from ShGetFolderPathW(..., CSIDL_COMMON_DESKTOPDIRECTORY, ...)
%userfavorites% = value from ShGetFolderPathW(..., CSIDL_FAVORITES, ...)
%allfavorites% = value from ShGetFolderPathW(..., CSIDL_COMMON_FAVORITES, ...)
%userappdata% = value from ShGetFolderPathW(..., CSIDL_APPDATA, ...)
%allappdata% = value from ShGetFolderPathW(..., CSIDL_COMMON_APPDATA, ...)
%allusersprofile% = value from GetAllUsersProfileDirectoryW
%userprofile% = value from GetUserProfileDirectoryW
%appexedir% = value from GetModuleFileNameW
Optimizing SQL Server CPU Performance
Some interesting FYI facts from the article:
- In performance value: high-end dual-core processor > RAM > fibre optics > disk drive
- A data page in SQL Server is 8KB.
- An extent in SQL Server is made up of eight 8KB pages, making it equivalent to 64KB.
- Pulling a data page that is already cached from the buffer pool, at peak performance, should take under half a millisecond; retrieving a single extent from disk should take between 2 and 4 milliseconds in an optimal environment.
Check CPU utilization with PerfMon by monitoring: % Processor Time (<80%),>
Some optimizations are:
Query plan reuse
Reducing compiles and recompiles
Sort operations
Improper joins
Missing indexes
Table/index scans
Function usage in SELECT and WHERE clauses
Multithreaded operation
Resources for information on query plan reuse:
Batch Compilation, Recompilation, and Plan Caching Issues in SQL Server 2005 (microsoft.com/technet/prodtechnol/sql/2005/recomp.mspx)
Optimizing SQL Server Stored Procedures to Avoid Recompiles (sql-server-performance.com/rd_optimizing_sp_recompiles.asp)
Query Recompilation in SQL Server 2000 (msdn2.microsoft.com/aa902682.aspx)
HL7 Schema Generation Tool
http://www.microsoft.com/downloads/details.aspx?FamilyID=94877261-1f04-40b7-8c6d-cf92f38d09a3&DisplayLang=en
The tool they use to make HL7(v2.0) into XML.
Pre-req: BizTalk Server 2006 R2 or BizTalk Server 2006
Tuesday, October 09, 2007
Developing Tools to use with VS
Process Monitor -
"shows real-time file system, Registry and process/thread activity. It combines the features of two legacy Sysinternals utilities, Filemon and Regmon, and adds an extensive list of enhancements including rich and non-destructive filtering, comprehensive event properties such session IDs and user names, reliable process information, full thread stacks with integrated symbol support for each operation, simultaneous logging to a file, and much more."
http://www.microsoft.com/technet/sysinternals/FileAndDisk/processmonitor.mspx
Process Explorer -
"shows you information about which handles and DLLs processes have opened or loaded."
http://www.microsoft.com/technet/sysinternals/utilities/processexplorer.mspx
Auto Runs -
"has the most comprehensive knowledge of auto-starting locations of any startup monitor, shows you what programs are configured to run during system bootup or login, and shows you the entries in the order Windows processes them. These programs include ones in your startup folder, Run, RunOnce, and other Registry keys."
http://www.microsoft.com/technet/sysinternals/utilities/autoruns.mspx
Sources:
http://www.microsoft.com/technet/sysinternals/default.mspx
http://blogs.msdn.com/progressive_development/archive/2007/10/09/motley-says-the-only-tool-i-need-is-the-debugger-part-1.aspx
WaterMark It
I have also included in installation the source files, just incase you want to make fun of my horrible programming. <^_^>
The source file will be placed in (by default): C:\Program Files\Andrus Development\WaterMarkSetup\Source
http://williamandrus.tripod.com/WaterMarkIt.html
Tuesday, October 02, 2007
Implementing Custom ToolTip in C#
Here is my tool tip class, which inherent:
1 class WaterMarkToolTip : ToolTip
2 {
3 public WaterMarkToolTip()
4 {
5 this.OwnerDraw = true;
6 this.Draw += new DrawToolTipEventHandler(OnDraw);
7
8 }
9
10 public WaterMarkToolTip(System.ComponentModel.IContainer Cont)
11 {
12 this.OwnerDraw = true;
13 this.Draw += new DrawToolTipEventHandler(OnDraw);
14 }
15
16 private void OnDraw(object sender, DrawToolTipEventArgs e)
17 {
18 DrawToolTipEventArgs newArgs = new DrawToolTipEventArgs(e.Graphics,
19 e.AssociatedWindow, e.AssociatedControl, e.Bounds, e.ToolTipText,
20 this.BackColor, this.ForeColor, new Font("Arial Unicode MS", 8.25f, FontStyle.Bold));
21 newArgs.DrawBackground();
22 newArgs.DrawBorder();
23 newArgs.DrawText(TextFormatFlags.TextBoxControl);
24 }
25 }
Here is the implementation into the toolstripbutton:
1 class WaterMarkToolStripButton : ToolStripButton
2 {
3 private WaterMarkToolTip toolTip;
4 private string _toolTipText;
5
6 public WaterMarkToolStripButton()
7 {
8 this.toolTip = new WaterMarkToolTip();
9 this.toolTip.UseAnimation = true;
10 this.toolTip.AutoPopDelay = 500;
11 this.toolTip.AutomaticDelay = 500;
12
13 this.MouseHover += new EventHandler(WaterMarkToolStrip_MouseHover);
14
15 }
16
17 void WaterMarkToolStrip_MouseHover(object sender, EventArgs e)
18 {
19 this.AutoToolTip = false;
20
21 this.toolTip.Show(this._toolTipText, Owner, 1500 );
22 }
23
24 /// <summary>
25 /// Get/Set ToolTipText for this control
26 /// </summary>
27 public new string WaterMarkToolTipText
28 {
29 get
30 {
31 return this._toolTipText;
32 }
33 set
34 {
35 this.toolTip.RemoveAll();
36 this._toolTipText = " " + value + " ";
37 }
38 }
39
40 }
Visual Studio 2005 Add-In: Code to HTML
http://www.jtleigh.com/people/colin/software/CopySourceAsHtml/
1 class WaterMarkToolTip : ToolTip
2 {
3 public WaterMarkToolTip()
4 {
5 this.OwnerDraw = true;
6 this.Draw += new DrawToolTipEventHandler(OnDraw);
7
8 }
9
10 public WaterMarkToolTip(System.ComponentModel.IContainer Cont)
11 {
12 this.OwnerDraw = true;
13 this.Draw += new DrawToolTipEventHandler(OnDraw);
14 }
15
16 private void OnDraw(object sender, DrawToolTipEventArgs e)
17 {
18 DrawToolTipEventArgs newArgs = new DrawToolTipEventArgs(e.Graphics,
19 e.AssociatedWindow, e.AssociatedControl, e.Bounds, e.ToolTipText,
20 this.BackColor, this.ForeColor, new Font("Arial Unicode MS", 8.25f, FontStyle.Bold));
21 newArgs.DrawBackground();
22 newArgs.DrawBorder();
23 newArgs.DrawText(TextFormatFlags.TextBoxControl);
24 }
25
26
27 }
Monday, October 01, 2007
Reminder: TSQL date only
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
since,
CONVERT(VARCHAR(20),GETDATE(),112) returns the wrong date sometimes.
-----A cool and faster way:
DECLARE @datemask bigint
DECLARE @timemask bigint
SET @datemask = 0xffffffffff000000
SET @timemask = 0x0000000000ffffff
SELECT CAST(CAST((CAST(getdate() as binary) & @datemask) as binary(8)) as datetime)
//IF you need to grab a date and a time from two different locations in the database and combine them into one datetime (ex: shifts(time) and payperiod(date)):
SELECT CAST(CAST((CAST(getdate() as binary) & (@datemask | (CAST((CAST(getdate() as binary) & (@timemask) ) as binary(8)))) ) as binary(8)) as datetime)
Friday, September 28, 2007
Choosing a programming language...
An interesting checklist to follow when starting out in computer science or developing one skills to get hired.
1) Is it a standards based language?
You will want to develop your skills in a language that is either supported very well or is a standard. Example of languages that have standards: C++, C#, C, Ada, Eiffel, Fortran, ECMAScript...
2) Does the language have strong corporate or community support?
An ideal language will have enough support for the following reason:
Career Placement - it is very important to be able to market yourself. Learning or honing your skills in a language that is dead or soon to be will limit your options. Go to a popular job searching website, like dice.com and do a search on your programming language. See how many hits do you get. Also while viewing the popularity of the language, also view what other support is needed for that job. For example, HTML might return a lot of hits, but usually there will be other web development requirements that follow such as javascript, asp.net, ajax, php, etc..
Developing Skills - when searching for a language it is also important to see how much support there is in developing your skills. Does the language come with some sort of Integrated Development Environment (IDE). The IDE should be easy to use, support multiple roles (developer, database, etc..), support tools (addins), support commercial interest (Game Design, App Development, Web Development, ...), and also implement features that make development less of a hassle.
3) What are you interested in developing?
Some languages are better suited for certain styles of commercial interest. A language that is suitable for game design, might not be the best for web development. While, some languages are solely used for a single purpose, like artificial intelligence, database design, etc... others are not. Some languages, such as C#, have a wide spectrum of uses that can be useful if you are having trouble fitting toward one type of interest. For example, if you want to develop window applications and develop interesting web pages.
4) How productive/robust is the language?
At this point, you might still have a list of several languages still to consider. One thing to look into is how productive and robust is the language. Some languages are very robust allowing you to have more options for developing more intrigued items, but it might take longer to develop in that environment. Some languages that are more productive will allow for quick turnover, but might be limited in what can be done.
You might also have to consider what other support the language might have from other languages. In web development: a language like javascript is a great support to other languages that don't have as much power. While asp.net might be very powerful on the server side, it needs the help of javascript to do some more robust options on the client side.
5) Do you want to be versatile/portable?
As you probably have noticed, that some languages are platform dependent. Developing in a language that is only supported toward one type of operating system, web browser, etc... is a tough decision. This is basically limiting your audience, or upsetting your users (like Linux users who have to switch over to Windows)
While a operating system like Windows is the most popular, do you want to also develop for *nix, Apple, HP, etc... Some languages are designed only for one operating system, while others are more versatile. Languages that are versatile and easily portable can be tougher to develop with. A language like C would probably work on most operating systems, but at a price where it is somewhat limited and tough to learn to develop with.
6) How easy is it to do maintenance?
A language that is maintainable is a very nice luxury. To be able to update, clean, and apply easy documentation should be something to look for to help save time (and money).
For example, in C# 2.0, a nice feature that is noticeable is when changing the name of a variable. The IDE basically ask the programmer if it is OK to go through the whole project, where the variable is in scope, if it should change the name there as well. In past, I would have to use a search and replace while stepping through each one checking if it should be replaced, or use a regular expression to limit the search pattern.
With that all said, I hope this is a decent check list to help find and target a language. It should be said, that some languages are easier to learn, if given a background in other languages.
A language like C was a gateway to other popular languages like C++, C#, Python, Java, etc... A programmer that learned one of these languages will have a quicker learning curve when introduce to these other languages. This might be a factor as the days of the C has been dieing down, but a programmer with this knowledge had a easier time switching to a more popular language and not becoming obsolete. Compare this to a language like COBAL which is not very popular and doesn't have any transition language that I know of.
Some steps when converting Dynamic tsql to Static
1) Remove quotes (carefully). - Going through and eliminated the outside quotes is the easy part. You do have to be careful of the single inner quotes, for example a single quote(s) might be necessary in a varchar statement.
2) Look over the convert statements. - A majority of the convert statements, especially the converting to varchar will need to be looked over and possibly removed in most cases.
3) Replace variables that dealt with parsing. - Some stored procedures might be sending in multiple data into one variable for example @Y = ('1,2,3,4,5') and being accessed like: WHERE x in @Y. This will need to be replaced with either a PATINDEX or CHARINDEX.
4) Remove unnecessary declarations - Some variables are going to end up not being used now, for example the varchar variable that was used to make the dynamic tsql string.
These are the tips, I might remember some more and add them later.
Thursday, September 27, 2007
Interesing line count of MS Dev Products
• Visual Studio 2005: 7.5 million lines
• SQL Server 2005: 3 million lines
• BizTalk Server: 2 million lines
• Visual Studio Team System: 1.7 million lines
• Windows Presentation Foundation: 900K lines
• Windows SharePoint Services: 750K lines
• Expression Blend: 250K lines
• SharePoint Portal Server: 200K lines
• Content Management Server: 100K lines
• Dynamics SL has 3.4 million Lines
Biztalk Apps
BizTalk SSO Configuration Data Storage Tool (http://seroter.wordpress.com/2007/09/21/biztalk-sso-configuration-data-storage-tool/) - A Single Sign-On App that sets access permissions for applications, account groups, etc..
CodePlex's BizTalk Open Source Apps (http://www.codeplex.com/Project/ProjectDirectory.aspx?TagName=BizTalk) - Dissambler, MicroSoft ESB Guidance, automated testing, distributed systems, biztalk server 2006 documenter, pipeline component wizard, tcpip adapter, wcf adapter, biztalk server 2006 orchestration profiler, biztalk extensions, pattern wizard, adapter wizard, lifecycle management, solution kits, app software factory, map tester, host configurator for applications, powershell, counters, etc........
Tuesday, September 25, 2007
Progressive Development Blog
http://blogs.msdn.com/progressive_development/default.aspx
Friday, September 21, 2007
Quick Reminder: Parsing in T-Sql
In this example the values are sent into the stored procedure's variable @atInvNum.
DECLARE @aInvNum varchar(4000)
SET @aInvNum = LTRIM(RTRIM(@atInvNum))
DECLARE @pos INT
DECLARE @piece varchar(500)
DECLARE @tInvNum TABLE (ID int)
IF right(rtrim(@aInvNum),1) <> ','
SET @aInvNum = @aInvNum + ','
SET @pos = patindex('%,%' , @aInvNum)
WHILE @pos <> 0
BEGIN
SET @piece = left(@aInvNum, @pos - 1)
INSERT INTO @tInvNum SELECT cast(@piece as int)
SET @aInvNum = stuff(@aInvNum, 1, @pos, '')
SET @pos = patindex('%,%' , @aInvNum)
END
---------------------A better way---------------------
IF (LEN(RTRIM(LTRIM(@atTaskIDs))) > 0)
SET @atTaskIDs = ',' + @atTaskIDs + ','
CHARINDEX(',' + Convert(varchar, SRT.TASK_ID) + ',', @atTaskIDs) > 0 )
Thursday, September 20, 2007
Regular Expression App
http://williamandrus.tripod.com/RegEx.html
Wednesday, September 12, 2007
Reminder: Bulk insert through a store procedure
This is accomplished by using XML in the store procedure and sending it in through the ADO.Net
In the C# code:
//Make xml
using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["connectionString"]))
{
SqlCommand cmd = new SqlCommand("insBulkFTSEDCFileDetail", conn);
cmd.CommandType = CommandType.StoredProcedure;
StringBuilder sb = new StringBuilder();
sb.Append("
foreach (oEDCItem item in edc)
{
sb.AppendFormat("
item.ModuleName, item.PartNumber, item.SerialNumber, item.TestPosition, item.SupplierName, item.EDC, item.Opt);
}
sb.Append("
cmd.Parameters.AddRange(new SqlParameter[] {
new SqlParameter("@EDCFileID", EDCFileID),
new SqlParameter("@LastUpdateUserID", UserID),
new SqlParameter("@XMLDOC", sb.ToString())});
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The stored procedure:
Create Procedure insBulkFTSEDCFileDetail
{
@EDCFileID int,
@LastUpdateUserID int,
@XMLDOC varchar(MAX)
}
AS
DECLARE @xml_handle int
EXEC sp_XML_preparedocument @xml_handle OUTPUT, @XMLDOC
INSERT INTO [TABLE]
(EDCFileID,
ItemType,
Model,
SerialNumber,
EDCPosition,
SupplierName,
EDC,
Options,
LastUpdateDate,
LastUpdateUserID)
SELECT @EDCFileID,
EDCXML.ItemType,
EDCXML.Model,
EDCXML.SerialNumber,
EDCXML.EDCPosition,
EDCXML.SupplierName,
EDCXML.EDC,
EDCXML.Options,
getUTCDate(),
@LastUpdateUserID
FROM OPENXML( @xml_handle, '/EDCItems/EDCItem')
WITH ( ItemType varchar(8),
Model varchar(50),
SerialNumber varchar(50),
EDCPosition varchar(50),
SupplierName varchar(50),
EDC varchar(50),
Options varchar(80)) AS EDCXML
EXEC sp_XML_removedocument @xml_handle
Tuesday, September 11, 2007
Quick reminder: Implement ICallbackEventHandler
The page source (client-side):
<script language="javascript" type="text/javascript">
function Save()
{
var message = '';
var context = '';
<%=sCallBackFunctionInvocation%>
}
function Result(result, context)
{
if(result != 'ok')
alert("Error: " + result + "\n\nFile was not saved.");
}
function OnError(message, context)
{
alert('An unhandled exception has occurred:\n' + message);
}
</script>
The code-behind (server-side):
public partial class EDCWUC : System.Web.UI.UserControl, ICallbackEventHandler
{
public string sCallBackFunctionInvocation;
protected void Page_Load(object sender, EventArgs e)
{
sCallBackFunctionInvocation = this.Page.ClientScript.GetCallbackEventReference(this, "message", "Result", "context", true);
}
#region ICallbackEventHandler Members
public string GetCallbackResult()
{
return sCallBackFunctionInvocation;
}
public void RaiseCallbackEvent(string eventArgument)
{
sCallBackFunctionInvocation = DoServerSideEvent();
}
#endregion
}
A good hint: If you need to do several callbacks, then set it up so that the eventArgument sends in the function name with its values, then all you need to do is split it, get the function name and send in the necessary values
For example:
FunctionName;<uniqueDelimeter>;Values
Saturday, September 08, 2007
Some Interview Questions given to me in the past.
2. What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
3. Demonstrate definition of a property in a class (in c#)
4. Demonstrate populating a dropdownlist from an xml file (in c#)
5. How do you assign a static IP Address to a Windows 2003 Server?
6. Draw out what the outcome of an Inner Join, Left Outer Join and Right Outer Join would be on two tables.
7. How would you access the database connection strings from a web.config file in VS 2003 and VS 2005?
8. Where would you setup “Impersonation” and when would it be a good time to use it?
9. How many static IP Addresses can a Windows 2003 Server have?
10. A client needs a web page that collects the following: first name, last name, phone number and then pushes the data to them via email. Please provide sample code of a form that sends that data to the client.
11. Demonstrate in Asp.Net how to pull a remote user’s IP Address, Referring URL, and the [cookieid] from a user’s machine for domain [SAN].
12. Please provide an example of a time when you have ever used web services.
13. How would you go about debugging a web service SOAP Message?
14. How do you view the methods and properties of a web service within Visual Studio?
1) What is a postback?
http://www.xefteri.com/articles/show.cfm?id=18 does a nice job in explaining what a postback is, in detail.
In my own words: In a standard postback a web page, with a web form is submitted and then processed on the server-side. The server-side then updates the page on the client-side by reposting the data. This is usually seen with something similar to a page refresh. (Which is why, if you are buying something on the web, it's a good idea not to hit refresh button or it would duplicate the last sent request.)
Now with, javascript and nowadays Ajax, it isn't necessary to refresh the whole page. It is possible to just refresh a certain control, allowing the user to see updated information without refreshing and redrawing other controls.
2) What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
In my own words:
A viewstate is a serializable hashtable of objects that are used to store information on the client-side. During a postback, the informatin is then used on the server-side before reposting to the client-side. This allows the data found in controls like a textbox to be repoulated, or to use the viewstate to store global variables which can be reused.
A viewstate is stored in base64, and encryption by default is set to auto. This means, as long as no control in the form does not need encryption, then the whole viewstate is unencrypted; otherwise the whole viewstate is encrypted. You can set the view state for each page:
<%@Page ViewStateEncryptionMode="Always" %>
, or you can set it for the whole website by using the web.config:
<configuration>
<system.web>
<pages ViewStateEncryptionMode="Always" />
</system.web>
</configuration>
3) Demonstrate definition of a property in a class
class MyClass
{
private string _name = “”;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}
4) Demonstrate populating a dropdownlist from an xml file
Not tested:
XML file:
<library>
<book>
<author>Dietel & Dietel</author>
<title>C how to program</title>
</book>
<book>
<author>William Shakespare</author>
</book>
</library>
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("Library.xml"));
XmlNodeList nodeList = doc.SelectNodes("library/book/"); //xslt path
foreach(XmlNode node in nodeList)
{
DropDownListTitle.Items.Add(new ListItem(node.SelectSingleNode("title").InnerText));
}
5) How do you assign a static IP Address to a Windows 2003 Server?
I personally don't know much about setting up servers, I'm a developer. So, I look it up:
http://technet2.microsoft.com/windowsserver/en/library/36c35b2c-8b8b-4517-812e-913a60ff551d1033.mspx?mfr=true
The basic info provided:
To configure TCP/IP for static addressing
1.
Open Network Connections.
2.
Right-click the network connection you want to configure, and then click Properties.
3.
On the General tab (for a local area connection) or the Networking tab (for all other connections), click Internet Protocol (TCP/IP), and then click Properties.
4.
Click Use the following IP address, and do one of the following:
•
For a local area connection, in IP address, Subnet mask, and Default gateway, type the IP address, subnet mask, and default gateway addresses.
•
For all other connections, in IP address, type the IP address.
5.
Click Use the following DNS server addresses.
6.
In Preferred DNS server and Alternate DNS server, type the primary and secondary DNS server addresses.
6) Draw out what the outcome of an Inner Join, Left Outer Join and Right Outer Join would be on two tables.
Can't draw
7) How would you access the database connection strings from a web.config file in VS 2005? (Don't care about VS 2003 anymore :P )
<appSettings>
<add key="sqlConn" value="Server=myPc;Database=Northwind" />
<add key="smtpServer" value="smtp.mydomain.com" />
</appSettings>
If I need to access it in the program:
this.sqlConnection1.ConnectionString = ((string)( System.Configuration.ConfigurationSettings.AppSettings.GetValues("sqlConn.ConnectionString"))));
8) Where would you setup “Impersonation” and when would it be a good time to use it?
Tuesday, September 04, 2007
Lorem Ipsum
The use of using this text for dummy text has been around since 1500, which was taken from a book "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC.
http://www.lipsum.com/
What is also cool about this site, it has a Lorem Ipsum generator.
Monday, August 27, 2007
How to programatically bind a value to a parameter in a ObjectDataSource
From here I just add the value:
protected void ObjectDataSource1_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
e.InputParameters["IP"] = Request.UserHostAddress;
}
Friday, August 24, 2007
File Download in ASP.Net
So on my download page I have:
protected void Page_Load(object sender, EventArgs e)
{
String filepath =
Request.Params.Get("Author") + "-" + Request.Params.Get("Title") + ".mp3";
if
(filepath.Length != 0)
{
Stream readStream =
MusicManager.GetSong(Int32.Parse(Request.Params.Get("file")));
int Length =
256;
Response.Clear();
Response.ContentType =
"application/octet-stream";
Response.AddHeader("Content-Disposition",
"attachment; filename=\"" + filepath + "\"");
Response.Flush();
Byte[]
buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0,
Length);
while (bytesRead > 0)
{
Response.OutputStream.Write(buffer,
0, bytesRead);
bytesRead = readStream.Read(buffer, 0,
Length);
}
Response.End();
readStream.Close();
}
}
Of course I have a page that sends in the query string with the necessary info
This seems all simple when it starts working, but it took me 2 hours to get the file to download correctly.
Wednesday, August 22, 2007
Tuesday, August 21, 2007
Interview question: What structure would you use to represent shapes in a database?
I then started thinking about this question, again. The idea of the question was to see what tables and columns would you set up to make this feasible. I wanted an easy solution with minimal work, so I avoided the polymorphism concept and went to a simpler definition of a shape (polygon).
I figure I would make 1 table called SHAPE with 2 columns and make the assumption that the shapes are defined as "simple polygons":
ID int, COORDINATES varchar
The ID is obviously the primary key for each shape.
The Coordinates is a order list of Cartesian coordinates going counter-clockwise.
Now, given a shape, the most common questions asked would be what is the perimeter and area of said shape. I could easily make 2 store procedures to find the perimeter and area.
To figure out the perimeter, I just need to add up the distance from each point, simple enough.To figure out the area of the polygon, I knew there had to be a formula that would do this for me, and thanks to wikipedia I found one:
"The formula was described by Meister in 1769 and by Gauss in 1795. It can be verified by dividing the polygon into triangles".
I was looking around, to see if others seen this question. I did find something similar at http://lists.mysql.com/mysql/207823
If I needed to query the table for certain shapes, then it would be good to add an additional column called: Points int
So, if I needed to query the table for triangles only then I can do a search on points = 3.
Monday, August 20, 2007
Efficient use of Iterators and Delegates
http://msdn2.microsoft.com/en-us/vcsharp/bb264519.aspx
Take the initial uneffecient example:
// First attempt:
public List
{
IEnumerable
List
foreach ( PhoneBookEntry ph in newYorkNumbers)
{
string name = string.Format(“{0} {1}”, ph.FirstName,
ph.LastName);
if ( RecognizePerson( name ) )
peopleIKnow.Add(name);
}
return peopleIKnow;
}
// Fifth attempt:public
IEnumerable
PeopleIKnowInNewYork()
{
IEnumerablenewYorkNumbers =
PhoneBook.FindListFor(“New York”);
IEnumerablenames = Transform (newYorkNumbers,
delegate(PhoneEntry entry)
{
return string.Format(“{0} {1}”, entry.FirstName, entry.LastName);
});
return Filter(names,
delegate(string name)
{
return RecognizePerson(name);
}
);
}
Friday, August 17, 2007
LINQ and AI?
var locals = (from c in customers
where c.ZipCode == 91822
select new { FullName = c.FirstName + “ “ +
c.LastName, HomeAddress = c.Address})
.Count();
What I find really interesting about the possibility of using LINQ, is the idea that the program can look at itself in an evaluation. If you add some artificial intelligence, this idea can be a great help in developing programs that can prove themselves correct in logic. I even think, that this concept can be used, with lots of time and planning, to develop a program that can write other programs given a set of parameters and acceptable outcomes.
The concept of using a database like language in a structure language is a very nice concept. If LINQ could be used to select all number of the type Int32 to represent integer numbers, would be something fun to play with. On this subject I might be a little too much in the dream world at the momement, but I do look forward to the possibilities.
Some sources on LINQ:
http://msdn.microsoft.com/msdnmag/issues/07/06/CSharp30/
http://blogs.msdn.com/charlie/archive/2007/07/26/visual-studio-2008-beta-2-released.aspx
Some info on Lambda Calculus:
http://en.wikipedia.org/wiki/Typed_lambda_calculus
Monday, August 06, 2007
Quick Reference: Raise Events in C#
Declare:
private delegate void OnMouseOverDelegate(object
sender, System.EventArgs e);
private event OnMouseOverDelegate OnMouseOver;
After InitializeComponent(); :
this.OnMouseOver += new OnMouseOverDelegate(my_MouseHover);
Function:
private void
my_MouseHover(object sender, System.EventArgs e)
{
}
Thursday, July 26, 2007
Changing Dynamic SQL to Static SQL
The store procedure might have a dynamic sql statement like:
SET @tsql = 'SELECT * FROM TABLE1
WHERE TABLE1.Name = ' + @Name
IF @ID <> ''
@tsql = @tsql + ' AND TABLE1.ID = ' + @ID
exec sp_executeSql @tSqlQuery
This would be changed to:
SELECT * FROM TABLE1 WHERE TABLE1.Name = @Name
AND( (@ID <> '' AND TABLE1.ID = @ID) OR
(@ID = '' ))
Now came the problem if they dynamically set a column to be sorted:
IF LTRIM(RTRIM(@sortColumn)) <> ''
@tsql = @tsql + 'ORDER BY ' + @sortColumn
This unfortunately had to be solved by making a case statement for all possible columns that are returned. So in this case this table returns only two columns (name and id):
SELECT NAME, ID FROM TABLE1
WHERE TABLE1.Name = @Name AND ((@ID <> ''
AND TABLE1.ID = @ID) OR (@ID = '' ))
ORDER BY
CASE @sortColumn WHEN 'ID' THEN ID ELSE NULL END,
CASE @sortColumn WHEN 'NAME' THEN NAME ELSE NULL END
The reason for the seperate case statements in the example is because it can only return one data type. If NAME is of varchar and ID is of int, then they have to be separated.
Well, that's a very basic and simple run down of what I've been doing. I do run into larger more complex store procedures and other situations. For example, when a dynamic sql statement is using a table name as a variable.
Friday, June 29, 2007
Wednesday, May 23, 2007
Rollbacks and Commits in Stored Procedures
Microsoft says:
If @@TRANCOUNT has a different value when a stored procedure finishes than it had when the procedure was executed, an informational error (266) occurs. This can happen in two ways:-- http://msdn2.microsoft.com/en-us/library/ms187844.aspx
A stored procedure is called with an @@TRANCOUNT of 1 or greater and the stored procedure executes a ROLLBACK TRANSACTION statement. @@TRANCOUNT decrements to 0 and causes an error 266 when the stored procedure completes.
A stored procedure is called with an @@TRANCOUNT of 1 or greater and the stored procedure executes a COMMIT TRANSACTION statement. @@TRANCOUNT decrements by 1 and causes an error 266 when the stored procedure completes. However, if BEGIN TRANSACTION is executed after the COMMIT TRANSACTION, the error does not occur.
DECLARE @LocalTransActive Bit
IF @@TRANCOUNT = 0
BEGIN
BEGIN TRANSACTION Trans_Discharge
SET @LocalTransActive = 1
END
For the commit part:
IF @LocalTransActive = 1
BEGIN
COMMIT TRANSACTION Trans_Discharge
END
For the rollback part:
IF @@TRANCOUNT > 0
BEGIN
IF @LocalTransActive = 1
BEGIN
ROLLBACK TRANSACTION Trans_Discharge
END
END
Monday, April 30, 2007
VB.Net: An editable combo box
In a custom made datagrid combo box column, which inherits from
DataGridColumnStyle. I have 3 functions that were mainly used in this custom datagrid combo box column. (BTW I also have a custom comboBox control, but nothing in that control that was needed to make this work):
Public Sub New(ByVal colName As String, ByVal dataSource As DataTable, ByVal displayMember As String, ByVal valueMember As String, ByVal dataGrid As DataGrid, ByVal editable As Boolean)
...
_ComboBox = New ctlComboBox
_ComboBox.Visible = True
_hasTextBox = editable
_dv = dataSource.DefaultView
_ComboBox.DataSource = _dv
_dataTable = dataSource
_dataTableAll = dataSource
_ComboBox.DisplayMember = displayMember
_displayMember = displayMember
_ComboBox.ValueMember = valueMember
_valueMember = valueMember
Me.Editable()
Dim _graphicsContext As Graphics = dataGrid.CreateGraphics
Dim _widest As Double = 1
Dim _stringSize As SizeF = New SizeF(0, 0)
Dim dr As DataRow
For Each dr In dataSource.Rows
_stringSize = _graphicsContext.MeasureString(dr(displayMember).ToString, dataGrid.Font)
If (_stringSize.Width > _widest) Then
_widest = _stringSize.Width
End If
Next
_ComboBox.DropDownWidth = CType(Math.Ceiling(_widest), Integer)
Me.Width = _ComboBox.DropDownWidth + 25
Me.MappingName = colName
Me.HeaderText = colName
dataGrid.Controls.Add(_ComboBox)
End Sub
--AND--
Private Sub _comboBox_MouseUp(ByVal sender As Object, ByVal e As System.EventArgs) Handles _ComboBox.SelectionChangeCommitted
If (_hasTextBox) Then
RaiseEvent ComboBox_Edit(Me._ComboBox.Text)
End If
End Sub
--AND--
Public Sub Editable()
Dim dropDownButtonWidth As Integer = 14
If _hasTextBox Then
_ComboBox.DrawMode = DrawMode.Normal
_ComboBox.DropDownStyle() = ComboBoxStyle.DropDown
_ComboBox.Show()
_ComboBox.Visible() = True
_ComboBox.Focus()
HideComboBox()
End If
End Sub
###
Okay, now in my form I have a function that handles the event I throw from the datagrid combo box:
###
Private Sub ComboBox_Edit(ByVal value As String) Handles colName.ComboBox_Edit
Try
Me.dvShifts.Table().Rows(Me.dgrShifts.CurrentRowIndex)("Name") = value 'Set the value selected
If (Me.colName.SelectedIndex > -1 AndAlso _
Not IsDBNull(dsShifts.Tables(1).Rows(Me.colName.SelectedIndex())("ID"))) Then
'Set the datagrid values based on the selected information if need to.
End If
'Make a new column to implement changes if edited
colName = New ctlDataGridComboBoxColumn("Name", dsShifts.Tables(1), "Name", "Name", Me.dgrShifts, True)
colName.MappingName = "Name"
colName.HeaderText = "Name"
Me.colName.SelectedValue() = value
Me.colName.DataSourceTable() = dsShifts.Tables(1)
colName.Width() = ResizeColumn("Name", "Name")
'Some other custom function calls
...
Catch ex As Exception
'adding new row to datagrid
If (Me.colName.SelectedIndex > -1 AndAlso _
Not IsDBNull(dsShifts.Tables(1).Rows(Me.colName.SelectedIndex())("Shift_ID"))) Then
Dim newDR As DataRow
newDR = Me.dsShifts.Tables(0).NewRow()
newDR.Item("Name") = value
... 'other custom stuff
End If
colName = New ctlDataGridComboBoxColumn("Name", dsShifts.Tables(1), "Name", "Name", Me.dgrShifts, True)
colName.MappingName = "Name"
colName.HeaderText = "Name"
Me.colName.SelectedValue() = value
Me.colName.DataSourceTable() = dsShifts.Tables(1)
Me.dgrShifts.Update()
colName.Width() = ResizeColumn("Name", "Name")
BindControl()
End Try
End Sub
That is the bare minimum without going into great detail of how to get an editable combo box in a datagrid column.