Archive for the 'c#' Category
Visual Studio 2008 Impressions
VS 2008 and the accompaning c# 3.0 has virtually changed the way I write code. I know that’s a lot to say about a product, but I feel that strongly about it. It has simplified my writing by exciting me to go back and look at how I write code.
I’ll start with Lambda Expressions because they have made the most difference in my code. For those who need a starter course, a good article on them is here. What I love about them is ability to create action functions with them. An example would be the following:
_listofWidgits.ForEach(t =>
{
//Do something to each widgit.
}
No defining some method, just do it. Another alternative would be to define a method that takes a widgit as the only parameter and phrase it as follows:
_listofWidgits.ForEach(SomeMethod); //No need to spell out the fact that you are passing a widgit to the method. Intellisense does it for you.
How’s that for shortening your code. Anyway, I’ll talk more about LINQ and c# 3.o soon.
No commentsUltraWinGrid and bound DataSource
I found a nice trick for the Infragistic’s UltraWinGrid. The UltraGridRow has a property ListObject which can be cast to the original datasource object. An example would be the following:
IList<CustObjectBE> orders = new List<CustObjectBE>();
UltraWinGrid grid = gridOrders; <– Grid on a form.
grid.DataSource = orders;
UltraGridRow row = grid.ActiveRow;
CustObjectBE order = row.ListObject as CustObjectBE;
if (order != null)
{
//Do something here.
}
This method provides a convenient way to get the bound object to a row in the grid.
No commentsC# 3.0 LINQ Wow!
I just read this months article in the MSDN magazine (C# Evolution) and I’m excited about this addition to C-Sharp in the next version. I have worked as a DBA and find adding the from, where, select, orderby, group by, let, and join to objects in .NET most interesting. Alot of times, I’ve used techniques like this to accomplish the goals but the verbage becomes lengthy. C# 3.0 solves this problem.
LINQ has the following parts:
- Lambda Expressions are a language feature that is similar in many ways to anonymous methods. The basic idea is that you can treat code as data.
StaticMethods.Where(customers, c => c.ZipCode == 91822);
- Extension methods are basically static methods that are callable through an instance syntax.
- The above Where method would be an Extension Method. It would be exposed on an instance member though. customers.
- public static IEnumerable<T> Where<T>(this IEnumerable<T> items, Func<T, bool> predicate)
- Anonymous Types and Implicitly Typed Local Variables can be used together to specify types “On the fly” inside a method.
- Instead of create a placeholder class (Customer name and address) for each time you want to pull something out of a collection, you declare a var variable and use an anonymous type to populate it.
- val custAddress = new { FullName = c.FirstName , HomeAddress = c.Address };
- Object initializers basically allow the assignment of multiple properties or fields in a single expression.
- Create an instance of a class without overloading the constructor a million times.
- Customer customer = new Customer() { Name = bob, Address = Wilco Way };
- These all lead up to Query Expressions. SQL like ways of accessing .NET objects.
-
var locals = from c in customers
where c.ZipCode == 91822
select new { FullName = c.FirstName, HomeAddress = c.Address };
-
var locals = from c in customers
Coming from both a coding and dba background, I find these enhancements in “Orcas” wonderful. It could save a ton of time in coding.
Do yourself a favor and go checkout C# 3.0 and “Orcas”.
No commentsHow to use Windows Certificate Authority to Strong Name Assemblies
I recently wanted to use the internal Certificate Authority for all our code signing requirments. After several hours of pain I was able to get it to work but thought I’d document the procedures so other’s won’t have the same problems.
- Ensure a Certificate Authority is installed and running on the Active Directory domain.
- The windows certificate authority uses a web based request form so open IE and browse to the site. (ex http://someserver/certsrv)
- When requesting the certificate, you will need to choose advanced for certificate type and select code signing as the type. Also ensure you choose Microsoft Enhanced Cryptographic Provider and not the Basic or RSA provider. (I’ll explain below) Figure 1
- Choose to Mark Keys as Exportable and choose a password. Save the file with a *.pvk extension.
- Click submit. You will be prompted to save the pvt and then click to save the certificate. Do not save the full certificate path as strong naming does not support certificate chaining.
- Open a Visual Studio command prompt and navigate to the location you saved the files.
- Type cert2spc yournewfile.cer yournewfile.spc where yournewfile is the filename you gave the pvk when saving it. This will convert the cer to a compatible spc file.
- Type pvk2pfx -pvk yournewfile.pvk -spc yournewfile.spc A wizard will open, follow prompts making sure to check the box to make the private keys exportable.
- The new *.pfx file can be used to sign assemblies and the computers inside the network will be able to verify the certificate against the internal Certificate Authority.
You will receive the dreaded “Error Importing Key - Object already existing” error when trying to compile if you choose the wrong provider, ie the provider is incompatible with Visual Studio code signing.
Figuring this was a straight forward procedure, I requested a certificate and private key pair from the Certificate Authority and that’s where the trouble started.
Dot Net Framework 3.0 RTM
Yeah!!!! it’s finally RTM.. I’ve worked with Windows Workflow Foundation throughout the beta program and I find it to a real accet to the several projects I’ve used the foundation in. The tracking store and monitor support for runtime applications is wonderful for showing the progress of business transactions to end users.
Do yourself a favor and try the new .Net Framework out. HERE
No commentsCSharp Text Parser to String Variable
I regularly find myself creating constant strings or including Sql statements in c# source files. I like everyone else hate sitting there putting quotes around the lines of text, so I setup a web page with a parser to do it for you.
Very easy instructions.
- Specify the name of the variable you want to use.
- Paste or enter the text into the Input Code text area.
- Hit convert.
- Copy rendered code from Output Code text area.
- Your done.
Simple easy and works for almost all strings. I’ll be adding special character support and fixed width wrapping soon, but give it a try and see if it doesn’t save you some time.
I’ve added a link at the top of the page or here.
Whoops…. BUG in firefox doesn’t see the line breaks correctly. I’ll be testing and fixing this weekend.
No commentsCSharp IExtenderProvider with ExpandableObjectEditor for ValueLists
I’ve recently found a solution to a common problem of form development. Value lists or “CodeSets” for controls on user forms. Most of the time a programmer will write a stored procedure or statement to return some dataset and bind the results to a combo box, listview or similar control. I have several problems with this pattern.
- Can cause multiple queries to the database for a single form to load.
- Requires the programmer to write code for every control with an associated lookup table or value list.
- Could be implemented inconsistently.
What are our goals?
- Should require no code on the part of the programmer.
- Should cache the values of the codesets at runtime to avoid multiple database queries.
- Should be expandable to show both the name and id of the codeset.
So let’s solve this problem. I’m using Enterprise Library’s cache manager for caching and also EntLib’s data libraries for data access.
You’ll need 2 tables in the database:
- Codesets: The list of codeset identifiers and their descriptions.
- Codeset_Details: The list of values, it’s display value and the codeset identifier.
We create a custom component that implements IExtenderProvider that exposes a property called Codeset of type CodesetProperty.
The CodesetProperty class has a int and string member to store the id and name of the codeset to load into the control.
We need a custom typeeditor to show the available codeset values. NOTE: You will need to ensure you have access to the connection string for the current database. I do this through a registry setting pointing to our standard development directory which contains our app.config.
The last part is a custom typeeditor to return an InstanceDescriptor which the CodedDomSerializer will use to generate the Intialization code.
We then add a CodesetProvider to a form. In my case any combobox, listbox, dropdown and comboeditor will show a property “Codeset on codesetProvider1″. This is an expandable property so you’ll see the values listed but by dropping down the list on the property you will get a list of the available codesets and then at runtime this property will be used to load the combo box with the values.
No commentsDesignMode and Checking Design Mode on a WinForm
DesignMode checking can be troublesome with form inheritance. An example would be a base form has an OnLoad that does something
private void OnLoad(object sender, EventArgs e)
{
if (!DesignMode)
{
//Do something here.
}
}
Where the trouble starts is when the derived form is loaded in the visual studio designer. DesignMode solving to true in the base form is not always guaranteed, therefore an acceptable solution would be the following:
///
/// Indicates if the current view is being utilized in the VS.NET IDE or not.
///
public new bool DesignMode
{
get
{
return (System.Diagnostics.Process.GetCurrentProcess().ProcessName == “devenv”);
}
}