CAT | Examples
23
Adding Domain Users to a Server 2008 R2 Domain
No comments · Posted by Larry.Smithmier in Active Directory, Command Line, Domain Controller, dsadd, Examples, Script, Server 2008 R2
I have a long list of users to add to an existing domain, and using the Active Directory Users and Computers GUI:
is an easy way to add a couple of users:
but with over 40 to add, it would take too long. How can I speed this up? dsadd to the rescue! The command line you would use to add a new user is:
dsadd user "CN=First Last,CN=User,DC=corp,DC=productiveedge,DC=com" -samid first.last -pwd qwerty123! -mustchpwd yes
so you can create a script to add users to a domain relatively easily. Note the:
-mustchpwd yes
at the end of the line. That is added to require the user to change their password on the first login.
Active Directory · Add User · Command Line · Domain Controller · dsadd · Example · Script · Server 2008 R2
4
Looking up Stored Procedures Containing ‘%x%’
No comments · Posted by Larry.Smithmier in Examples, Snippit, SQL
This isn’t really big news, but I have had to look it up twice in the last quarter. To find which stored procedures contain a specific text string, use:
SELECT Name, OBJECT_DEFINITION(OBJECT_ID) FROM sys.procedures sp WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Language%'
Example · SELECT · SQL Server · Stored Procedures · sys.procedures
2
Mystery Constants: Maintainability
No comments · Posted by Larry.Smithmier in C#, Examples, IntelliSense, Legacy, Maintainability, Visual Studio
Working with legacy code is always one of my favorite things to do. I believe it helps me write more maintainable code, and the little mysteries are always quite engaging. The most recent example that I feel compelled to share is related to the setting of a database value based on the selection made in a radio button group. In this particular instance, a set of custom localization routines help cloud the issue by abstracting the text from the code, but the central fault is more universal. There was an undocumented naming convention that was initially followed within the database, but the constraints on columns were not always put in place to enforce the convention and the code itself was not designed to assist in any way.
On to specifics (altered to insure confidentiality).
- Initially, in the UI there are three radio buttons that correspond to an integer column in the database (color). The value is set on a public property of an object that corresponds to the table (widgets) in the database. There is a corresponding dimension table (widgetColorCode) in the database, but there is a missing foreign key constraint and the naming convention doesn’t make it easy to track down the dimension domain.
- Time passes.
- A new UI is built for a new company that only manufactures red Widgets. The combo boxes are removed, and the value is set upon submission to the constant 1.
- A derivative of the new UI is commissioned that is for a company only supplying blue Widgets. There is nothing in the code to help the programmer find what value this property should have.
So the code for the Widget class looks something like this:
public class Widget
{
public int Color { get; set; }
}
I am a firm believer in having enumerations corresponding to all dimensions in a project. There is a performance hit for converting an enumeration to an integer, but it is far outweighed by the increased maintainability of the code. By explicitly setting the values for the enumeration and adding an XML comment relating it to the dimension table, you can greatly increase the maintainability of the code. When starting from scratch on a project, I will typically have something along the lines of:
////// corresponds to the Widget fact table /// public class Widget { public WidgetColor Color { get; set; } } ////// corresponds to the WidgetColorCode dimension table /// public enum WidgetColor { Red = 1, White = 2, Blue = 3 }
But, that is a personal preference, and refactoring the entire code base at this point can’t be justified. What can be done quickly to lessen the impact of this when further maintenance is required? Visual Studio comes to the rescue! By simply adding an XML comment to the property, we can define the dimension so that hovering over the property will display the dimension information (Please excuse the missing pointer in the image, trust me, I am hovering over the Color property.):
////// corresponds to the Widget fact table /// public class Widget { ////// corresponds to the WidgetColorCode dimension table /// 1: Red, 2: White, 3: Blue /// public int Color { get; set; } }
C# · DotNet · enumerations · Example · IntellliSense · Legacy code · Maintainability · Visual Studio
I have a project that requires me to send contracts that are stored in SQL Server to customers and I started poking around for the best way to do it. First, I found a quick code snippet that sends an email using sp_send_dbmail:
EXEC msdb.dbo.sp_send_dbmail @recipients = 'lsmithmier@productiveedge.com', @body = 'Just testing the mail', @subject = 'Sending Mail using Database Mail' ;
When I first ran it on my database server (SQL Server 2008 R2) I got the following error:
Msg 15281, Level 16, State 1, Procedure sp_send_dbmail, Line 0 SQL Server blocked access to procedure 'dbo.sp_send_dbmail' of component 'Database Mail XPs' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Database Mail XPs' by using sp_configure. For more information about enabling 'Database Mail XPs', see "Surface Area Configuration" in SQL Server Books Online.
So I cranked up Microsoft SQL Server Management Studio and set email up:
1. Open up the Management section and right click on the Database Mail item:
2. Choose Configure Database Mail
3. Click Next
4. Click Next
5. Click Yes
6. Set the Profile name and choose Add an SMTP account:
7. Enter your settings:
8. Set the profile as both Public and Default:
9. Click Next
10. Click Finish
11. Click Close
and it is all setup! Really easy compared to the old way of setting email up with SQL Server. Then I re-ran the query and got the following response:
Mail queued.
But then what? I ran a quick query and found that the email wasn’t sent correctly:
use [msdb] SELECT * FROM sysmail_mailitems GO SELECT * FROM sysmail_log GO
so I looked back over my settings and updated the port number to hit the outgoing relay and everything started working!
12
Creating a Telerik RadUpload User Control For Use in a RadGrid
No comments · Posted by Larry.Smithmier in .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, C#, Examples, RadGrid, RadUpload, Telerik, Visual Studio
I have been working with Telerik controls for a little over two months (the ASP.NET AJAX suite) and have been continuously impressed with the quality and power they provide. I am working on a project that requires the upload of several different file types which need to be displayed in a grid once uploaded. The cleanest solution I could think of was to create a User Control to handle the uploads and embed it within the grid through the EditFormSettings FormTemplate. So first, I created a simple upload User Control as follows:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UploadControl.ascx.cs"
Inherits="WebApplication1.UserControls.UploadControl" %>
Submit
with the code behind set up to store the uploaded files in the database using LINQ:
protected void btnSubmit_Click(object sender, EventArgs e)
{
LinerModelDataContext dataContext = new LinerModelDataContext();
foreach (UploadedFile file in RadUpload1.UploadedFiles)
{
byte[] bytes = new byte[file.ContentLength];
file.InputStream.Read(bytes, 0, file.ContentLength);
Attachment attachment = new Attachment();
attachment.FileName = file.GetName();
attachment.BinaryAttachment = bytes;
attachment.CustomerID = this.CustomerID;
dataContext.Attachments.InsertOnSubmit(attachment);
}
dataContext.SubmitChanges();
}
I then just added the EditFormSettings section to RadGrid1 and I was able to upload files:
But my grid wasn’t refreshing and I wasn’t getting any notification that the upload was complete. So, to provide the user experience I wanted, I exposed an event to the grid from the upload control by modifying the code behind of the UserControl. I added a delegate, and exposed the event as follows:
public delegate void UploadHandler();
public partial class UploadControl : System.Web.UI.UserControl
{
...
public event UploadHandler Upload;
protected void btnSubmit_Click(object sender, EventArgs e)
{
LinerModelDataContext dataContext = new LinerModelDataContext();
foreach (UploadedFile file in RadUpload1.UploadedFiles)
{
byte[] bytes = new byte[file.ContentLength];
file.InputStream.Read(bytes, 0, file.ContentLength);
Attachment attachment = new Attachment();
attachment.FileName = file.GetName();
attachment.Attachment1 = bytes;
attachment.CustomerID = this.CustomerID;
dataContext.Attachments.InsertOnSubmit(attachment);
}
dataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
if (Upload != null)
{
Upload.Invoke();
}
}
and changing the FormTemplate to be:
(please note that the syntax highlighter I am using mangled the code by changing OnUpload to be onupload in the above source) and adding the handler to the main page:
protected void UploadControl1_Upload()
{
RadGrid1.MasterTableView.IsItemInserted = false;
RadGrid1.Rebind();
}
Event · Example · Telerik · UserControl
7
Debugging Code: Always Break for Thrown Exceptions
No comments · Posted by Larry.Smithmier in .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, C#, Examples, Visual Studio
I love working with legacy code, really I do. I find the effort of trying to put myself mindset of the people who originally coded the applications enjoyable. It is somewhat satisfying to be able to get enough of a feel for the code to get a feel for what they were attempting to do as well as what got done. In most cases, it is quite easy to see which libraries and sections were implemented first, and which were either rushed to completion or tacked on as an afterthought. It often makes me spend the extra 15 minutes to fully implement something rather than simply patching over a flaw and planning on implementing the ‘real code’ at some mythic future date. Coming in cold to a project, doing a search for TODO is a good start, but I have also found a lot of cases where that isn’t good enough; so, I have begun setting Visual Studio (VS) to break on any thrown exception. If you aren’t familiar with how to change the way VS handles exceptions in debug mode, here is where you can make the changes:
Doing this helps me track down gems like this (from actual code, I made minor changes to keep from exposing client specific information):
//TEMPORARY - make sure the ID contains at least one alpha
try
{
int i = int.Parse(newID);
newID = newID.Remove(4, 1).Insert(2, "X");
}
catch { }
To be fair to the coder, TryParse has only been in the framework since 2.0, and this code could well have have begun life as a 1.1 application, but the TEMPORARY in the comment was obviously overly optimistic. My solution was to replace the above with:
int i;
//make sure the ID contains at least one alpha
if (int.TryParse(newID, out i))
{
newID = newID.Remove(4, 1).Insert(2, "X");
}
6
Comma Delimited List in TSQL
No comments · Posted by Larry.Smithmier in Examples, Snippit, SQL, Uncategorized
I am often tasked with making modifications to existing UIs, and tend to try and limit the impact I have by pushing a lot of the formatting and BL into the database. One piece of code that I regularly have to look up is the code to convert a result set into a comma delimited list. Here is the SQL 2005/2008 code that I just created for use in a client environment:
CREATE FUNCTION [dbo].[fn_LinkedString]
(
-- Add the parameters for the function here
@ID varchar(10)
)
RETURNS nvarchar(1000)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result nvarchar(1000)
-- Add the T-SQL statements to compute the return value here
SELECT @Result= x.List
FROM
(
SELECT
L1.ID,
List = SUBSTRING((SELECT (', '+ LinkedID)
FROM Linked L2
WHERE
L1.ID = L2.ID
ORDER BY
ID,
LinkedID
FOR XML PATH('')
), 3, 1000) FROM Linked L1
GROUP BY ID
) x
WHERE
x.ID = @ID
-- Return the result of the function
RETURN @Result
END
I wrapped the code in a scalar valued function to make it easier to use and to keep the code clean when used.
I occasionally need to get some representative values from a table for testing and thought my solution might be something worth sharing. I tend to think in nested selects and go back and clean up code into joins where appropriate. Below you will see that I am using a group by and a min function to identify single instances of different types, and then pulling the required data in an outer select:
SELECT UserName FROM Users WHERE UserID in ( SELECT MIN(UserID) FROM USERS WHERE Active = 1 GROUP BY TypeCode )
Example · SQL Server · TSQL
8
Exploring the .NET 4.0 framework in C#: System.Diagnostics.Contracts
No comments · Posted by Larry.Smithmier in .NET 4.0, Contracts, Examples, il, ildasm, rewrite, Visual Studio
Tightly-coupled, loosely bound. This has been my mantra for enterprise software development for the past 7 or so years. I have always been in favor of compile time over run time errors at (nearly) any cost. I don’t feel that I am dogmatic about it, I understand the need for flexibility in internal interfaces and early in a projects life cycle. But, at the point you have down stream systems that depend on your application to perform, the rules change. You are reading this entry using an application that has a loosely coupled, forgiving interface with the content it receives for rendering (see Joel’s discussion of inherent folly of this choice http://www.joelonsoftware.com/items/2008/03/17.html), so large systems don’t require the level of synchronization I prefer to function. I believe, however, they require it to function well.
Apparently, I am not alone in my belief. The .NET 4.0 framework now has an mscorlib level component that helps enforce the coupling at compile time. The System.Diagnostics.Contracts namespace contains a suite of static classes that, coupled with a post-processing code re-writer, provides static and run time implementations of preconditions, post-conditions, and invariants. In this post I am going to start with some simple examples of how the syntax works. In future posts, I hope to delve into the implications of this system as well as how our best practices need to be updated to take advantage of the power of these structures.
The first thing you need to do is to install the new contract tool set as outlined in http://blogs.msdn.com/bclteam/archive/2010/01/26/i-just-installed-visual-studio-2010-now-how-do-i-get-code-contracts-melitta-andersen.aspx. Please note that unless you are using Premium or Ultimate, you will not get Static evaluation, only run time.
You then turn static checking on in the settings in Project Properties > Code Contracts and select “Perform Static Contract Checking” so it looks like this:
Through static checking, we should see compile time errors. Unfortunately, the combination of VS 2010 RC I am using along with the Release 1.2.30312.0 of the Code Contracts for .NET doesn’t have the static version working properly. So for this example we are going to have to look at run time errors. That is set on the same Project Property page:
Lets start with a simple sample program with some properties.
class Program
{
public string Name { get; set; }
public int Age { get; set; }
static void Main(string[] args)
{
Program program = new Program();
program.Age = -7;
program.Name = "jon";
}
}
Within the program above, we can see a common pattern for properties. If we look at the underlying IL of one of the setter methods, we see what we should expect:
.method public hidebysig specialname instance void
set_Age(int32 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld int32 Contracts.Program::'k__BackingField'
IL_0007: ret
} // end of method Program::set_Age
After modifying the code to include the required using statement:
using System.Diagnostics.Contracts;
and updating the property to have the following contract statement:
public int Age
{
get { return _age; }
set
{
Contract.Requires(value >= 0);
_age = value;
}
}
When a command line program is run with a bad argument, the following exception is thrown:
Unhandled Exception: System.Diagnostics.Contracts.__ContractsRuntime+ContractException: Precondition failed: value >= 0 at System.Diagnostics.Contracts.__ContractsRuntime.TriggerFailure(ContractFailureKind kind, String message, String userMessage, String conditionText, Exception inner) in :line 0 at System.Diagnostics.Contracts.__ContractsRuntime.ReportFailure(ContractFailureKind kind, String message, String conditionText, Exception inner) in :line 0 at System.Diagnostics.Contracts.__ContractsRuntime.Requires(Boolean condition, String message, String conditionText) in :line 0 at Contracts3.Program.set_Age(Int32 value) in c:\Contracts\Program.cs:line 19 at Contracts.Program.Main(String[] args) in c:\Contracts\Program.cs:line 33
and looking at the IL I find where the rewrite has added wrappers to handle the pre-conditions:
.method public hidebysig specialname instance void
set_Age(int32 'value') cil managed
{
// Code size 74 (0x4a)
.maxstack 3
IL_0000: ldsfld int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
IL_0005: ldc.i4.4
IL_0006: bgt IL_003c
.try
{
IL_000b: ldsfld int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: stsfld int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
IL_0017: ldarg.1
IL_0018: ldc.i4.0
IL_0019: clt
IL_001b: ldc.i4.0
IL_001c: ceq
IL_001e: ldnull
IL_001f: ldstr "value >= 0"
IL_0024: call void System.Diagnostics.Contracts.__ContractsRuntime::Requires(bool,
string,
string)
IL_0029: nop
IL_002a: leave IL_003c
} // end .try
finally
{
IL_002f: ldsfld int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
IL_0034: ldc.i4.1
IL_0035: sub
IL_0036: stsfld int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
IL_003b: endfinally
} // end handler
IL_003c: nop
IL_003d: ldarg.0
IL_003e: ldarg.1
IL_003f: stfld int32 Contracts3.Program::_age
IL_0044: br IL_0049
IL_0049: ret
} // end of method Program::set_Age
The re-writing is being done by ccrewrite, and can be conditionally compiled in. There is also a structure set up to allow runtime code to catch the contract exception to be handled internally.
links: http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts(v=VS.100).aspx
No tags
8
Examining .NET 4.0 with C#: ExpandoObject
No comments · Posted by Larry.Smithmier in .NET 4.0, Examples, IntelliSense, Visual Studio
public string Name { get; set; }
syntactic sugar, it still isn’t as clean or concise as Ruby:
class Person attr_accessor :first_name, :last_name end
or what he envisioned for Java:
//context of another class Person p = new Person(); p.firstName := "John";
where the getter and setter are automatically appended to the Person object by the compiler.
Well, .NET 4.0 still isn’t quite as cool and concise, but it is getting closer with the introduction of the ExpandoObject. By adding the following using statement:
using System.Dynamic;
you now get the ability to write code like:
dynamic p = new ExpandoObject(); p.firstName = "John";
Oh, and did I mention that you get IntelliSense with it as well?
- When using ExpandoObject(s) with .NET 4.0 and C#, you get IntelliSense for all of the dynamically generated fields.
link: http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=VS.100).aspx
No tags



