Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, July 8, 2015

Provision additional lookup fields with CSOM

When you create a lookup field in SharePoint, you’ll have the option to add additional fields of the source list to your target list. When you create this from the UI, you check those fields on creation of the lookup field. But when you create this from your provision code, you can’t find any parameters on the lookup field itself.

The key for doing this in the code is the method AddDependentLookup on the Fields collection of the target list. To provision this lookup, I created the following method in my provisioner:

Please note that the lookupFieldId should be the fieldId of the field you want to add to your target list, and there should be another ‘primary’ lookup field configured between the two lists. The displayName is free to choose, this one will show up as column heading for instance in your target list.

Wednesday, February 19, 2014

Quickly update WebPart titles by CSOM

While entering content for a new SharePoint section on a SharePoint 2010 publishing site, the content editors added a related articles webpart on about 100 pages. Too bad they didn't bother to change the webpart title, so I was asked to change change these titles, which had their default value, from a rather functional description of the webpart to something that makes a lot more sense in on the pages. As it should be possible to do it in CSOM, I created a small console application to achieve this.

Thursday, August 4, 2011

Get Taxonomy terms from the user while configuring a WebPart

In my current SharePoint 2010 project we make use of Managed Metadata terms a lot. We want to be able to select taxonomy terms while configuring WebParts, but the setup of the taxonomy field isn't quite straightforward. For the configuration of WebParts with exotic controls, you need to implement a custom ToolPart and link it to your WebPart. Because I think we will create a lot of custom ToolParts, I created a base class for displaying these taxonomy fields.

   1:  /// <summary>
   2:  /// This class makes it easier to work with Taxonomy data in a <see cref="Microsoft.SharePoint.WebPartPages.ToolPart">ToolPart</see>
   3:  /// </summary>
   4:  public class TaxonomyToolPart : ToolPart
   5:  {
   6:      /// <summary>
   7:      /// Gets or sets the name of the term store.
   8:      /// </summary>
   9:      /// <value>
  10:      /// The name of the term store.
  11:      /// </value>
  12:      public string TermStoreName { get; protected set; }
  13:      /// <summary>
  14:      /// Gets or sets the name of the term group.
  15:      /// </summary>
  16:      /// <value>
  17:      /// The name of the term group.
  18:      /// </value>
  19:      public string TermGroupName { get; protected set; }
  20:      /// <summary>
  21:      /// Gets or sets the name of the term set.
  22:      /// </summary>
  23:      /// <value>
  24:      /// The name of the term set.
  25:      /// </value>
  26:      public string TermSetName { get; protected set; }
  27:      /// <summary>
  28:      /// Gets or sets a value indicating whether multiple terms can be selected.
  29:      /// </summary>
  30:      /// <value>
  31:      ///   <c>true</c> if multiple terms can be selected; otherwise, <c>false</c>.
  32:      /// </value>
  33:      public bool MultiSelect { get; protected set; }
  34:   
  35:      private TaxonomyWebTaggingControl TaxonomyControl { get; set; }
  36:   
  37:      /// <summary>
  38:      /// Called by the ASP.NET page framework to notify server controls that use composition-based 
  39:      /// implementation to create any child controls they contain in preparation for posting back or rendering.
  40:      /// </summary>
  41:      protected override void CreateChildControls()
  42:      {
  43:          // create a panel that will hold all of our controls 
  44:          Panel toolPartPanel = new Panel();
  45:   
  46:          // create the actual control 
  47:          SPContext context = SPContext.Current;
  48:          SPSite site = context.Site;
  49:          TaxonomySession session = new TaxonomySession(site);
  50:          TermStore termStore = session.TermStores[TermStoreName];
  51:          Group group = termStore.Groups[TermGroupName];
  52:          TermSet productsTermSet = group.TermSets[TermSetName];
  53:   
  54:   
  55:          TaxonomyControl = new TaxonomyWebTaggingControl();
  56:          TaxonomyControl.ID = "taxonomyControl";
  57:          TaxonomyControl.SspId.Add(termStore.Id);
  58:          TaxonomyControl.TermSetId.Add(productsTermSet.Id);
  59:          TaxonomyControl.IsAddTerms = false;
  60:          TaxonomyControl.AllowFillIn = true;
  61:          TaxonomyControl.IsMulti = MultiSelect;
  62:   
  63:          TaxonomyControl.Text = GetTextFromWebPart(this.ParentToolPane.SelectedWebPart);
  64:   
  65:          toolPartPanel.Controls.Add(TaxonomyControl);
  66:   
  67:          // finally add the panel to the controls collection of the tool part 
  68:          Controls.Add(toolPartPanel);
  69:   
  70:          base.CreateChildControls();
  71:      }
  72:   
  73:      /// <summary>
  74:      /// Gets the textual representation of the selected terms from the WebPart and sets it on the Taxonomy control.
  75:      /// </summary>
  76:      /// <param name="webPart">The web part.</param>
  77:      /// <returns>a value from the webpart to select in the TaxonomywebTaggingControl</returns>
  78:      /// <remarks>Override this method in your child class to link the webpart property with the taxonomy field.</remarks>
  79:      /// <example>the term string has a value like 'Term 1|db61b704-cf1d-490d-bfc3-4cbcd8d2f453;Term 2|66b5696d-94a2-4299-ae34-63d3072ca357</example>
  80:      protected virtual string GetTextFromWebPart(WebPart webPart) { return string.Empty; }
  81:   
  82:      /// <summary>
  83:      /// Sets the textual representation of the selected terms from the Taxonomy control to the WebPart.
  84:      /// </summary>
  85:      /// <param name="webPart">The parent web part.</param>
  86:      /// <param name="selectedTerms">The selected terms.</param>
  87:      /// <remarks>Override this method in yout child class to link the taxonomy filed with the webpart property</remarks>
  88:      /// <example>the term string has a value like 'Term 1|db61b704-cf1d-490d-bfc3-4cbcd8d2f453;Term 2|66b5696d-94a2-4299-ae34-63d3072ca357</example>
  89:      protected virtual void SetTextToWebPart(WebPart webPart, string selectedTerms) { }
  90:   
  91:      /// <summary>
  92:      /// Called when the user clicks the OK or the Apply button in the tool pane.
  93:      /// </summary>
  94:      public override void ApplyChanges()
  95:      {
  96:          WebPart webPart = this.ParentToolPane.SelectedWebPart;
  97:          SetTextToWebPart(webPart, TaxonomyControl.Text);
  98:      }
  99:  }

This base class can now be used in a new class, where the configuration of the ToolPart and the linking with the WebPart needs to be implemented:

   1:  public class TestToolPart : TaxonomyToolPart
   2:  {
   3:      public TestToolPart()
   4:      {
   5:          this.TermStoreName = "Managed Metadata";
   6:          this.TermGroupName = "NL";
   7:          this.TermSetName = "Brand";
   8:          this.MultiSelect = true;
   9:          this.Title = "Taxonomy Example";
  10:      }
  11:   
  12:     protected override string GetTextFromWebPart(Microsoft.SharePoint.WebPartPages.WebPart webPart)
  13:      {
  14:          return ((TestWebPart)webPart).Text;
  15:      }
  16:   
  17:      protected override void SetTextToWebPart(Microsoft.SharePoint.WebPartPages.WebPart webPart, string selectedTerms)
  18:      {
  19:          ((TestWebPart)webPart).Text = selectedTerms;
  20:      }
  21:  }        

The only thing you need to do is override the GetToolParts() in your WebPart to inject your custom ToolPart in the ToolPart array, and your ToolPart should work.

Sunday, January 23, 2011

Enhanced ASP.NET input sanitation with AntiXSS

Need for input sanitation

The applications you build for the internet can have quite a big audience. It is possible for the whole connected world to visit your website and use the app you built on it. But with these visitors, you will attract dark forces who can misuse your application for their own agenda. It is therefore needed to harden your application, and be sure no-one can send email, inject custom HTML and javascript and hijack user information. It is needed you built secure code and protect yourself.

The main characteristic of an application is that it needs input data from the end user. With this input data, something is done. If this data is sent back to the user, is can be displayed on the screen. In it most simple form, this looks like:


<div>
<asp:TextBox ID="inputBox" runat="server" TextMode="MultiLine" />
<br />
<asp:Button ID="submitButton" runat="server" Text="Submit"
onclick="submitButton_Click" />
<br />
<asp:Label runat="server" EnableViewState="True" AssociatedControlID="resultLiteral" Text="Html output:" />
<asp:Literal ID="resultLiteral" runat="server"></asp:Literal>
</div>



With the following button_click code:


protected void submitButton_Click(object sender, EventArgs e)
{
string input = inputBox.Text;
string output = input;
resultLiteral.Text = output;
}


With this example code, it is possible to inject javascript into the response. Try pasting <script language="javascript">alert('Hello World!');</script> in the input box and see.

Out of the box ASP.NET functionality

With the standard ASP.NET setup, the last script example didn’t worked, but threw an exception with the message ‘A potentially dangerous Request.Form value was detected from the client (inputBox="<script language="ja...").’. This is because out of the box, ASP.NET will scan each input parameter to dangerous characters. But don’t let this filter mislead you. The default characters will be the less than character (<) and some ampersand-hash encoded characters. There are also scenario’s you will be switching off the request validation. Simply because some business scenario (maybe you want some html from your user).

You can switch your validation off for all your pages in ASP.NET in the web.config, or specify ValidateRequest="false" in the page directive for the specific page you want to disable this check (note that in ASP.NET 4, there are some additional steps needed). But don’t rely on request validation to heavily, because there are situations in can’t detect malicious input.

Shortcomings of Request Validation

Think about the following situation. You want the user of your site to specify the background color of an element on your page, and you use the following submit event:

protected void submitButton_Click(object sender, EventArgs e)
{
string color = inputBox.Text;
string output = "<div style=\"width:200px;height:200px;background-color:" + color + ";\">Colored Box</div>";
resultLiteral.Text = output;
}


Because the input is directly pasted into an attribute of the div tag, you don’t need HTML directly to inject javascript. The following line will pass through input validation, and inject the page with some potentially evil javascript:
red;" onclick="alert('Hello World!');" "
/



Filtering input

The first thing to prevent the injection of those unwanted code, is to filter the user input if used for generating output. Standard built-in in ASP.NET is the HttpUtility class with some Encoding methods. They can help with the above two attacks, but it is still possible to inject URL backgrounds in the second example. Because these filters are limited in usage, Microsoft started a new library quite some time ago.

AntiXSS library

The two main features in the AntiXSS library are the Encoder and Sanitizer classes. Like the HttpUtility, the encoder class has several specific Encoding methods. These methods are a lot more specific than HttpUtility though. In the second example, it is possible filter the color input with a call to Encoder.CssEncode. The output will be CSS encoded into ‘red\00003B\000022\000020onclick\00003D\000022alert\000028\000027Hello\000020World\000021\000027\000029\00003B\000022\000020\000022’.

The Sanitizer class is even more powerful. It can strip certain HTML tags out of the input. It can transform <script language="javascript">alert('Hello World!');</script><strong>bla</strong><img src="bla.gif" /><ul><li>one<li>Two<li>Three</ul> into <strong>bla</strong><img src="bla.gif"> <ul> <li>one</li><li>Two</li><li>Three</li></ul>


Install AntiXSS with NuGet

AntiXSS used to be a very hidden gem somewhere deep on Microsoft Download or CodePlex. But with the new NuGet, it is on page one of packages. First you need to install NuGet into your Visual Studio. After that, right click your project and choose ‘Add Library Package Reference’.



imageimage


As of today, AntiXSS is the eighth package in the list. If you click install, all assemblies for AntiXSS will be automatically downloaded and added to your solution. So it won’t be very hard anymore to write really secure code!

Wednesday, December 15, 2010

Conversion of a RTF document to PDF with C#

In my current project, I need to convert in an easy way RTF documents to PDF from managed code. I don't want to rebuild these documents in PDF, because the RTF's still have some need in the application.

After google-ing around for possible solutions, I tried two components: the last version of iTextSharp with RTF support (from version five on, the RTF support is split into a new project and removed from iTextSharp) and Aspose.Words.

After a quick conversion with iTextSharp, I understand why RTF support was dropped. The produced PDF was one piece of garbage. The code I used was:

using (FileStream outstream = File.Create(outFile))
{
Document docText = new Document();
PdfWriter writer = PdfWriter.GetInstance(docText, outstream);
docText.Open();
RtfParser rtf = new RtfParser(null);
using (FileStream rtfStream = File.OpenRead(inFile))
{
rtf.ConvertRtfDocument(rtfStream, docText);
}
docText.Close();
}


Aspose.Words worked like a charm, while using only two lines of code:

Aspose.Words.Document doc = new Aspose.Words.Document(inFile);
doc.Save(outFile, SaveFormat.Pdf);

The only drawback is iTextSharp is OpenSource and Aspose.Words isn't. But I guess there isn't another reliable OS alternative.

Wednesday, August 11, 2010

Migrating Tridion templates from 5.2 to 2009

Upgrading a Tridion environment from Tridion 5.2 SP1 to Tridion 2009 SP1 isn’t a straightforward procedure, especially when you have to cope with a lot of custom functionalities. In this post, I write down some experience whith the upgrade of the old templating framework to a new one.


Tridion 5.2 situation


The templating framework used in 5.2 (pre-compound templating) was we built as a ScriptExtension in C#, and this ScriptExtension was registered one in the Tridion MMC snap-in. All the present VBScript based templates call this ScriptExtension with some templating parameters. This templating setup is very easy to deploy (register one dll and you're ready to go),


The drawback of this solution was the usage of the Tridion COM API, and the managed to native interop issues you have to deal with (like releasing your references to COM objects), but with Tridion 5.2 (and before that, with Tridion 5.1SP4) it worked.


First try, migrating this solution to 2009 SP1


While building our solution with Tridion 5.1SP4 and 5.2SP1, you had to built the Interop assemblies yourself. With version 2009, Tridion delivered these in the bin\client folder of the Tridion installation. Linking the existing solution to these new assemblies, fixing small API changes and recompiling the whole worked like a charm. But testing the code gave some major issues. The internals of the deployment packages changed for binaries and was killing the custom metadata for indexing purposes. But the whole publishing process became a large memory hog. So it was needed to rewrite the solution (or restart the TDSE process once in a short while). That was basically what was done, the legacy rendering and publishing was ditched for the new way of publishing and rendering content.

Wednesday, September 30, 2009

Demo Parallel Extensions .NET 4.0

Yesterday I a gave a presentation/demonstration about the upcoming .NET 4.0 framework release. Unfortunately, there wasn't enough time to show the complete parallel demo. Here I show a couple of ways to display all integers between 0 and 100 that are dividable by 10.


class Program
{
// objects for classic parallel code
static object locker = new object();
static Queue<int> integers;
//with concurrent Queue, we don't need a locker
static ConcurrentQueue<int> concurrentIntegers;

static void Main(string[] args)
{
int steps = 100;
steps.WriteOnConsole(); //extension method to display an integer on the console
Classic(); //classic for loop, no parallel code
ClassicParallel(); //classic parallel invocation

New(steps); //parallel for loop
NewMoreLikeClassic(steps); //parallel the new way, but looks like classic parallel

Linq(steps); //old LINQ way
PLinq(steps); //new Parallel LINQ
}

private static void Classic(int steps = 100)
{
for (int i = 0; i < steps; i++)
{
if (i % 10 == 0)
{
i.WriteOnConsole();
}
}
}

private static void ClassicParallel(int steps = 100)
{
integers = new Queue<int>(steps);
// fill the queue with all integers
for (int i = 0; i < steps; i++)
{
integers.Enqueue(i);
}

int workerCount = 5; //arbitrary number for workercount.
Thread[] workers = new Thread[workerCount];
// Create and start a separate thread for each worker
for (int i = 0; i < workerCount; i++)
{
workers[i] = new Thread(Consume);//.Start();
}
foreach (Thread worker in workers)
{
worker.Start();
}
}

private static void Consume()
{
while (true)
{
int i;
lock (locker)
{
if (integers.Count == 0) return; // run until the queue is empty
i = integers.Dequeue();
}
if (i % 10 == 0)
{
i.WriteOnConsole();
}
}
}

private static void New(int steps)
{
ParallelLoopResult result = Parallel.For(0, steps, (i, loop) =>
{
if (i % 10 == 0)
{
i.WriteOnConsole();
}
//With the LoopState, we can break and terminate the processing of the loop
if (i == 50)
{
loop.Break();
}
}
);
Console.WriteLine("Completed: {0}, Breaked at iteration {1}",
result.IsCompleted,
result.LowestBreakIteration);
}

private static void NewMoreLikeClassic(int steps = 100)
{
concurrentIntegers = new ConcurrentQueue<int>(Enumerable.Range(0, steps));
Parallel.Invoke(() =>
{
ConsumeQueue();
}
);
}

private static void ConsumeQueue()
{
// note: there is no locking used here, because we use a ConcurrentQueue
int i;
bool success = concurrentIntegers.TryDequeue(out i);
if (success && (i % 10 == 0))
{
i.WriteOnConsole();
}
}

private static void Linq(int steps)
{
Enumerable.Range(0,steps).Where(i => i % 10 == 0)
.ToList<int>().ForEach(i=>i.WriteOnConsole());
}

private static void PLinq(int steps)
{
Enumerable.Range(0, steps).Where(i => i % 10 == 0).AsParallel()
.ToList<int>().ForEach(i => i.WriteOnConsole());
}
}

Wednesday, September 16, 2009

ASP.NET favicon.ico routing to deep link

After seeing some errors in my application log complaining about a non existing business object with id favicon.ico, and being sure that I had a <link href="/resources/images/favicon.ico" rel="shortcut icon" /> tag in my header section, I realized that old non-standard-compliant browsers do a request for the hard-coded /favicon.ico url. So I wanted to add a route in my route table to redirect these requests to the proper icon location. Unfortunately, there is no public StaticFileHandler available with a virtual path in its constructor, so I had to built them myself. The following couple of lines do the trick:

Registering the routes in the application startup:

routes.Add(new Route("favicon.ico", new StaticFileRouteHandler("~/Resources/images/favicon.ico")));
// generic, catch-all rule, caused the error for favicon.ico
routes.Add(Routes.BusinessObject, new Route(
string.Format("{{{0}}}", RouteParameters.BusinessObjectIdentifier),
new CustomRouteHandler("~/Pages/BusinessObjectDetails.aspx")));


The StaticFileRouteHandler to serve the the static file from the request.

public class StaticFileRouteHandler : IRouteHandler
{
public string VirtualPath { get; set; }
public StaticFileRouteHandler(string virtualPath)
{
VirtualPath = virtualPath;
}

#region IRouteHandler Members
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
{
HttpContext.Current.RewritePath(VirtualPath);
return new DefaultHttpHandler();
}
#endregion
}

Wednesday, September 2, 2009

New VS2010 / .NET 4.0 features

I already love the new dynamic keyword in VS2010, and missing it in my day to day work with Tridion COM objects. Although the drawback is no IntelliSense in VS on the object, see the following code to get the item title from a Tridion TOM item:

Old code

object obj = tdse.GetObject(tcmUri, EnumOpenMode.OpenModeView, null, XMLReadFilter.XMLReadAll );
string title = null;
if (obj is Component)
{
Component component = (Component) obj;
title = component.Title;
}
if (obj is Folder)
{
Folder folder = (Folder) obj;
title = folder.Title;
}
if (obj is Page)
{
Page page = (Page) obj;
title = page.Title;
}


New code

dynamic tridionItem = tdse.GetObject(tcmUri, EnumOpenMode.OpenModeView);
string title = tridionItem.Title;


Another long-missing-but-finally-added feature is the support of optional COM Interop parameters in C#. Before 4.0, you needed to specify all optional parameters in Interop method calls, even if you wanted to use the default values, leading to extremely long method calls (maybe not in Tridion, but infamous in Office Interop with Type.Missing). These method parameters do now have the block parentheses around them in IntelliSense:

Wednesday, July 15, 2009

Using MySQL Providers with ASP.NET

MySQL Logo
I'm figuring out how to use MySQL with Visual Studio and ASP.NET. The first thing to install (besides MySQL Server) is the MySQL Connector for .NET, currently at version 6.0.4.
After installing this connector, you've all the .NET providers and entity framework stuff to go. One thing I should mention is that the .NET Connectors will install MySql providers which you can use in your website, MySql won't popup in the Express editions of Visual Studio. So you can't connect to a MySQL database with your server explorer with these versions.

So installing the MySQL connector on your server will modify the server's machine.config and add the provider config in it. Not installing the connector on your server means you need to configure the providers in the system.web section of the web.config of the site (and bin deploying the MySql dll's of course):

<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider" />
<add connectionStringName="MySqlServer" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="true"
applicationName="/" requiresUniqueEmail="false" passwordFormat="Clear"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10"
passwordStrengthRegularExpression="" name="MySQLMembershipProvider"
type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.0.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</membership>
<profile>
<providers>
<remove name="MySQLProfileProvider"/>
<add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.0.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="MySqlServer" applicationName="/" />
</providers>
</profile>
<roleManager defaultProvider="MySQLRoleProvider">
<providers>
<remove name="MySQLRoleProvider" />
<add connectionStringName="MySqlServer" applicationName="/" name="MySQLRoleProvider"
type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.0.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</roleManager>


These new providers need a connection string, so add to your connectionString section:

<connectionStrings>
<add name="MySqlServer" providerName="MySql.Data.MySqlClient" connectionString="server=mysql1;user id=webuser;password=xxxxxx;persist security info=True;database=website" />
</connectionStrings>

Next you need the schema. The docs will say they will be created automatically, but I didn't saw a single table created. By looking at the connector source code, I distilled the following script to create the schema in your database:

CREATE TABLE `my_aspnet_applications` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(256) DEFAULT NULL,
`description` varchar(256) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;

CREATE TABLE `my_aspnet_membership` (
`userId` int(11) NOT NULL DEFAULT '0',
`Email` varchar(128) DEFAULT NULL,
`Comment` varchar(255) DEFAULT NULL,
`Password` varchar(128) NOT NULL,
`PasswordKey` char(32) DEFAULT NULL,
`PasswordFormat` tinyint(4) DEFAULT NULL,
`PasswordQuestion` varchar(255) DEFAULT NULL,
`PasswordAnswer` varchar(255) DEFAULT NULL,
`IsApproved` tinyint(1) DEFAULT NULL,
`LastActivityDate` datetime DEFAULT NULL,
`LastLoginDate` datetime DEFAULT NULL,
`LastPasswordChangedDate` datetime DEFAULT NULL,
`CreationDate` datetime DEFAULT NULL,
`IsLockedOut` tinyint(1) DEFAULT NULL,
`LastLockedOutDate` datetime DEFAULT NULL,
`FailedPasswordAttemptCount` int(10) unsigned DEFAULT NULL,
`FailedPasswordAttemptWindowStart` datetime DEFAULT NULL,
`FailedPasswordAnswerAttemptCount` int(10) unsigned DEFAULT NULL,
`FailedPasswordAnswerAttemptWindowStart` datetime DEFAULT NULL,
PRIMARY KEY (`userId`)
) COMMENT='2';

CREATE TABLE `my_aspnet_profiles` (
`userId` int(11) NOT NULL,
`valueindex` longtext,
`stringdata` longtext,
`binarydata` longblob,
`lastUpdatedDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`userId`)
) ;


CREATE TABLE `my_aspnet_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`applicationId` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ROW_FORMAT=DYNAMIC;

CREATE TABLE `my_aspnet_schemaversion` (
`version` int(11) DEFAULT NULL
) ;

CREATE TABLE `my_aspnet_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`applicationId` int(11) NOT NULL,
`name` varchar(256) NOT NULL,
`isAnonymous` tinyint(1) NOT NULL DEFAULT '1',
`lastActivityDate` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ;

CREATE TABLE `my_aspnet_usersinroles` (
`userId` int(11) NOT NULL DEFAULT '0',
`roleId` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`userId`,`roleId`)
) ROW_FORMAT=DYNAMIC;

INSERT my_aspnet_SchemaVersion (version) VALUES (4);


Finally, you can use the ASP.NET Configuration website to configure users. To get only the providers working, it took a whole blog post. The .NET connector for MySQL is still a little bit rough on the edges, but after figuring the above things out, it will work!

Saturday, May 2, 2009

Code generation for a COM wrapper assembly

For my last post, I needed some quick and dirty code generator. Basically, I've a COM Iterop assembly full with interfaces I need to wrap with a specified template.

The following code works, but still needed some handwork (like hand coding the ref parameters). Use it on your own risk ;)


using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;

namespace CodeGeneration
{
class Program
{
static Dictionary<string, string> keywordType;

static void Main(string[] args)
{
FillKeywordType();

Assembly interop = Assembly.Load(@"Tridion.ContentManager.Interop.cm_tom");
foreach (Type t in interop.GetTypes())
{
//Console.WriteLine(t.Name);
if (t.Name.StartsWith("_"))
{
WriteOut(t, t.Name.Replace("_",string.Empty));
}
}
Console.ReadLine();
}

private static void FillKeywordType()
{

keywordType = new Dictionary<string, string>();
keywordType.Add("System.String", "string");
keywordType.Add("System.Void", "void");
keywordType.Add("System.Int32", "int");
keywordType.Add("System.DateTime", "DateTime");
keywordType.Add("System.Boolean", "bool");
keywordType.Add("System.Object", "object");
}

private static void WriteOut(Type t, string className)
{
Console.WriteLine("Info of {0}", t.Name);

using (StreamWriter writer = new StreamWriter(string.Format("D:\\Work\\DisposableOut\\{0}.cs", className) ))
{

WriteHeader(writer, className);


foreach (MethodInfo mi in t.GetMethods())
{
if (!(mi.Name.StartsWith("get_") || mi.Name.StartsWith("set_") || mi.Name.StartsWith("let_")))
{
string methodSig = string.Format("{1} {0}", mi.Name, GetTypeName(mi.ReturnType.Name, mi.ReturnType.Namespace));
bool isVoid = (GetTypeName(mi.ReturnType.Name, mi.ReturnType.Namespace)=="void");
List<string> parameters = new List<string>();
List<string> parameterNames = new List<string>();
foreach (ParameterInfo pi in mi.GetParameters())
{
parameters.Add(string.Format("{1} {0}", pi.Name, GetTypeName(pi.ParameterType.Name, pi.ParameterType.Namespace)));
parameterNames.Add(pi.Name);
}
string parameter = string.Join(", ", parameters.ToArray());

writer.Write(@"public {0} ({2})" + Environment.NewLine +
@" {{" + Environment.NewLine +
@" checkNotDisposed();" + Environment.NewLine +
@" {5}com{1}.{3}({4});" + Environment.NewLine +
@" }}" + Environment.NewLine + Environment.NewLine,
methodSig, className, string.Join(", ", parameters.ToArray()), mi.Name, string.Join(", ", parameterNames.ToArray()),
isVoid?string.Empty:"return ");
}
}

foreach (PropertyInfo pi in t.GetProperties())
{
writer.Write(@"public {0} {1} {{" + Environment.NewLine, GetTypeName(pi.PropertyType.Name, pi.PropertyType.Namespace), pi.Name);
if (pi.CanRead)
{
//get
writer.Write(@" get {{" + Environment.NewLine +
@" checkNotDisposed();" + Environment.NewLine +
@" return com{1}.{0};" + Environment.NewLine +
@" }}" + Environment.NewLine ,
pi.Name, className);
}
if (pi.CanWrite)
{
//set
writer.Write(@" set {{" + Environment.NewLine +
@" checkNotDisposed();" + Environment.NewLine +
@" com{1}.{0} = value;" + Environment.NewLine +
@" }}" + Environment.NewLine,
pi.Name, className);
}
writer.Write("}" + Environment.NewLine + Environment.NewLine);
}

WriteFooter(writer);
writer.Flush();
writer.Close();
}
}

private static string GetTypeName(string name, string nameSpace)
{
string typeName = string.Format("{0}.{1}", nameSpace, name);
if (keywordType.ContainsKey(typeName))
{
return keywordType[typeName];
}
return typeName;
}

private static void WriteFooter(StreamWriter writer)
{
writer.Write(@" #endregion" + Environment.NewLine +
@" }" + Environment.NewLine +
@"}" + Environment.NewLine);
}

private static void WriteHeader(StreamWriter writer, string className)
{
StringBuilder fileHeader = new StringBuilder();
fileHeader.AppendFormat(@"using System;{0}", Environment.NewLine);
fileHeader.AppendFormat(@"using System.Collections.Generic;{0}", Environment.NewLine);
fileHeader.AppendFormat(@"using System.Text;{0}", Environment.NewLine);
fileHeader.AppendFormat(@"using System.Runtime.InteropServices;{0}", Environment.NewLine);
fileHeader.AppendFormat(@"using Tridion.ContentManager.Interop.TDS;{0}", Environment.NewLine);
fileHeader.AppendFormat(@"{0}", Environment.NewLine);
fileHeader.AppendFormat(@"namespace DisposableTridion{0}", Environment.NewLine);
fileHeader.AppendFormat(@"{{{0}", Environment.NewLine);
fileHeader.AppendFormat(@" public class {1} : DisposableBase {0}", Environment.NewLine, className);
fileHeader.AppendFormat(@" {{{0}", Environment.NewLine);
fileHeader.AppendFormat(@" private Tridion.ContentManager.Interop.TDS.{1} com{1};{0}", Environment.NewLine, className);
fileHeader.AppendFormat(@"{0}", Environment.NewLine);
fileHeader.AppendFormat(@" public {1}(Tridion.ContentManager.Interop.TDS.{1} {2}){0}", Environment.NewLine, className, className.ToLower());
fileHeader.AppendFormat(@" {{{0}", Environment.NewLine);
fileHeader.AppendFormat(@" com{1} = {2};{0}", Environment.NewLine, className, className.ToLower());
fileHeader.AppendFormat(@" }}{0}", Environment.NewLine);
fileHeader.AppendFormat(@"{0}", Environment.NewLine);
fileHeader.AppendFormat(@" ~{1}(){0}", Environment.NewLine, className);
fileHeader.AppendFormat(@" {{{0}", Environment.NewLine);
fileHeader.AppendFormat(@" Dispose(false);{0}", Environment.NewLine);
fileHeader.AppendFormat(@" }}{0}", Environment.NewLine);
fileHeader.AppendFormat(@"{0}", Environment.NewLine);
fileHeader.AppendFormat(@" protected override void DisposeMembers(){0}", Environment.NewLine);
fileHeader.AppendFormat(@" {{{0}", Environment.NewLine);
fileHeader.AppendFormat(@" DisposableBase.ReleaseComObject(com{1});{0}", Environment.NewLine, className);
fileHeader.AppendFormat(@" }}{0}", Environment.NewLine);
fileHeader.AppendFormat(@"{0}", Environment.NewLine);
fileHeader.AppendFormat(@" #region _{1} Members{0}", Environment.NewLine, className);

writer.Write(fileHeader.ToString());
}
}
}

Friday, May 1, 2009

Disposing COM objects

The Tridion solutions at my current assignment are working great, but now and then the CM website freezes. After investigating the issue with Tridion customer support, there is a suspicion the Tridion COM objects freeze under memory load.
This load is generated because our custom solutions do not release the COM objects they use. So now the codebase should be recoded with this cleanup operation.

When you don't cleanup this code, the cleanup will be initiated by the .NET Garbage Collector (GC). But the GC isn't working continually, but will only be called under memory pressure.
Because COM objects aren't run under as managed code, the GC doesn't know how much memory is used by them. Therefore, waiting until the GC will cleanup your code can take a long time, especially because COM objects are small objects on the managed memory.

The pattern to use for cleaning up unmanaged resources is the IDisposable interface. So with this pattern, we can release a COM object after you're done with it by calling the Marshal.ReleaseComObject method.

Because the Tridion Object Model (TOM) has a lot of objects, I'm creating a managed wrapper assembly, where on each object I can implement the IDisposable interface. Besides the interface, I need some more plumbing, so the first class to create is an abstract DisposableBase class:

public abstract class DisposableBase : IDisposable
{
private bool disposed = false;

protected void checkNotDisposed()
{
if (this.disposed)
{
string message = "Object of type " + base.GetType().Name + " cannot be accessed because it was disposed.";
throw new ObjectDisposedException(base.GetType().Name, message);
}
}

public void Dispose()
{
if (!this.disposed)
{
this.Dispose(true);
}
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
this.DisposeMembers();
}
this.disposed = true;
}

protected abstract void DisposeMembers();

public static void ReleaseComObject(object interopObject)
{
if (interopObject != null)
{
Marshal.ReleaseComObject(interopObject);
}
interopObject = null;
}
}



So I can use this base class in each wrapper class for TOM classes, like the Component class:

public class Component : DisposableBase
{
private Tridion.ContentManager.Interop.TDS.Component comComponent;

public Component(Tridion.ContentManager.Interop.TDS.Component component)
{
comComponent = component;
}

~Component()
{
Dispose(false);
}

protected override void DisposeMembers()
{
DisposableBase.ReleaseComObject(comComponent);
}

public void CheckIn(bool permanentLock)
{
checkNotDisposed();
comComponent.CheckIn(permanentLock);
}

_Component Members
}


So now it's perfectly safe to use the TOM to check in a component with the following code:

using (Component component = tdse.GetObject("tcm:8-123", EnumOpenMode.OpenModeView))
{
component.CheckIn(true);
}

Tuesday, December 16, 2008

Creating a configuration section

In general, a lot of application are using the appSettings section of a config file for storing application parameters. A major drawback of this practice, is the lack of prior knowledge about the format and default value of these parameters, so you need to program all this functionality yourself.
A better way to provide your application with configuration values, is the use of a configuration section. Instead of using the appSettings node, you can specify your own.
The key to your own configuration section is the System.Configuration namespace.
You write your own class, but should inherit ConfigurationSection.
Now you can spice up your properties in this class with the ConfigurationProperty attribute. Validation can be programmed with the attributes
  • IntegerValidatorAttribute
  • LongValidatorAttribute
  • RegexStringValidatorAttribute
  • StringValidatorAttribute
  • TimeSpanValidatorAttribute


For example:

public class TestConfigurationSection : ConfigurationSection
{
// Empty Construct
public TestConfigurationSection() { }

// default string property
[ConfigurationProperty("deliveryStore", IsRequired = true)]
public string DeliveryStore
{
get
{
return (string)this["deliveryStore"];
}
set
{
this["deliveryStore"] = value;
}
}
//uri types will work too
[ConfigurationProperty("serviceUrl", DefaultValue = "http://192.168.1.10/MessageService", IsRequired = false)]
public Uri ServiceUrl
{
get
{
return (Uri)this["serviceUrl"];
}
set
{
this["serviceUrl"] = value;
}
}

[ConfigurationProperty("timeOut", DefaultValue = "0:00:20")]
[TimeSpanValidator(MinValueString = "0:00:05", MaxValueString = "0:05:00", ExcludeRange = false)]
public TimeSpan TimeOut
{
get
{
return (TimeSpan)this["timeOut"];
}
set
{
this["timeOut"] = value;
}
}
}


To use this configuration section in your config, you need to add it to the configsections node, for instance:

<configSections>
<section name="testConfig" type="NJV.Utils.TestConfigurationSection, NJV.Utils"/>
</configSections>
<testConfig
deliveryStore="D:\Test"
serviceUrl="http://10.0.0.9/MessageService"
timeOut="0:00:20"
/>


Now you've the settings defined and validation setup. To read these values, you can use the following code:

TestConfigSection config = (TestConfigSection)System.Configuration.ConfigurationManager.GetSection("testConfig");
TimeSpan timeout = config.TimeOut;
string deliveryLocation = config.DeliveryStore;
Uri serviceLocation = config.ServiceUrl;


The only drawback here is, you should be sure to have a testConfig section defined in your config, and it should be of the correct type. So maybe there could be some type and null reference checking on line 1:

TestConfigSection config = System.Configuration.ConfigurationManager.GetSection("testConfig") as TestConfigSection;
if (config==null)
{
throw new ApplicationException("No configuration available");
}

Thursday, October 16, 2008

Presentation on .NET 3.5

I did a presentation on .NET 3.5 last evening for my company. The presentation with demo code is posted on my SkyDrive. The presentation went well... I was a little bit nervous, but it went away quickly after I'd started.

I've made use of the demo pptPlex functionality from Office Labs. The version posted here, doesn't have these nice little extra's, but see the pptPlex website for more info about this tool. I didn't used pptPlex during the presentation the whole time... during the presentation I noticed I was presenting the wrong sheets, with old content on it. I changed back to normal presentation mode. Afterwards, I found the 'clear cache' under 'Learn more' to tidy up the cache and got the latest version of the sheets (but such a strange place for such an option).

Downloads

Wednesday, July 2, 2008

Compiling documents the OpenXML way

Today, I've got a RFC about the automatically generation of a document. De document should be a write-out of a thesaurus, which is contained in a SQL database. It should run server-sided, and should produce the document with the ease of a push of the button.
Besides the standard list of words, the document should contain page-numbers. In the past, this was done by writing out html, saving the document with the .doc extension and pushing the file with the right MIME headers. But with this approach, insertion of page numbers on each page is quite a burden (if possible at all)... so enter OpenXML.

The other scenario, using mail-merge functionality, isn't used. I want the merge takes place on the server, not on the client.

The code here is just programming with XML and the System.IO.Packaging namespace, introduced in .NET 3.0. I still haven't tried the OpenXML SDK, so you should know what you're doing with adding XML fragments and their relations into the package.
The solution is quite straightforward, and it won't be difficult to expand this to your own needs.

We start by referencing the System.IO.Packaging namespace. It is delivered in the WindowsBase GAC dll. Add a reference to the WindowsBase and you can build your own Package from scratch:

private void Load(string documentPath)
{
Package pkgOutputDoc = null;
pkgOutputDoc = Package.Open(@"c:\work\test.docx", FileMode.Create, FileAccess.ReadWrite);
Uri uri = new Uri("/word/document.xml", UriKind.Relative);
PackagePart partDocumentXML = pkgOutputDoc.CreatePart(uri,
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");

StreamWriter streamStartPart = new StreamWriter(partDocumentXML.GetStream(FileMode.Create, FileAccess.Write));
XmlDocument xdoc = new XmlDocument();
xdoc.Load(@"C:\work\document.xml");
FillDocument(xdoc);
xdoc.Save(streamStartPart);
streamStartPart.Close();
pkgOutputDoc.Flush();

pkgOutputDoc.CreateRelationship(uri, TargetMode.Internal,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
"rId1");
pkgOutputDoc.Flush();
pkgOutputDoc.Close();
}


I've added all the xml fragments I've used as embedded resources to my dll, so it is quite easy for me to version and deploy this solution. The added document.xml, the main content of my docx file, is expanded by generating custom xml, based on the database content.
I've read my database content into a dictionary, and I'm generating the xml based on each keyword in my database.

<w:p>
<w:r>
<w:t>Term</w:t>
</w:r>
<w:r>
<w:br />
</w:r>
<w:r>
<w:tab />
<w:t>SN</w:t>
</w:r>
<w:r>
<w:tab />
<w:t>scope note for Term</w:t>
</w:r>
<w:r>
<w:br />
</w:r>
<w:r>
<w:tab />
<w:t>UF</w:t>
</w:r>
<w:r>
<w:tab />
<w:t>Term B</w:t>
</w:r>
<w:r>
<w:br />
</w:r>
<w:r>
<w:tab />
<w:t>RT</w:t>
</w:r>
<w:r>
<w:tab />
<w:t>Term C</w:t>
</w:r>
<w:r>
<w:br />
</w:r>
</w:p>

This xml fragment is built by the following code

private void FillDocument(XmlDocument xdoc)
{
XmlNamespaceManager nsMgr = new XmlNamespaceManager(new NameTable());

string wNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
nsMgr.AddNamespace("w", wNamespace);

XmlNode wBody = xdoc.SelectSingleNode("/w:document/w:body", nsMgr);
//begin inserting at the last defined paragraph
XmlNode lastParagraph = xdoc.SelectSingleNode("/w:document/w:body/w:p[last()]", nsMgr);

Dictionary<string, List<RelatedKeyword>> thesaurus = ThesaurusList.GetThesaurus();

foreach (string keyword in thesaurus.Keys)
{
XmlElement thesaurusTerm = xdoc.CreateElement("w", "p", wNamespace);
wBody.InsertAfter(thesaurusTerm, lastParagraph);
lastParagraph = thesaurusTerm;

XmlElement thesaurusRterm = xdoc.CreateElement("w", "r", wNamespace);
XmlElement thesaurusText = xdoc.CreateElement("w", "t", wNamespace);
XmlElement thesaurusRbreak = xdoc.CreateElement("w", "r", wNamespace);
XmlElement thesaurusBreak = xdoc.CreateElement("w", "br", wNamespace);

thesaurusText.InnerText = keyword;

thesaurusTerm.AppendChild(thesaurusRterm);
thesaurusRterm.AppendChild(thesaurusText);

thesaurusTerm.AppendChild(thesaurusRbreak);
thesaurusRbreak.AppendChild(thesaurusBreak);

foreach (RelatedKeyword relatedKeyword in thesaurus[keyword])
{
XmlElement termTypeR = xdoc.CreateElement("w", "r", wNamespace);
XmlElement termDescriptionR = xdoc.CreateElement("w", "r", wNamespace);
XmlElement termBreakR = xdoc.CreateElement("w", "r", wNamespace);
XmlElement termTypeT = xdoc.CreateElement("w", "t", wNamespace);
XmlElement termTypeTab = xdoc.CreateElement("w", "tab", wNamespace);
XmlElement termDescriptionT = xdoc.CreateElement("w", "t", wNamespace);
XmlElement termDescriptionTab = xdoc.CreateElement("w", "tab", wNamespace);
XmlElement termBreak = xdoc.CreateElement("w", "br", wNamespace);



termTypeT.InnerText = relatedKeyword.Relation;
termDescriptionT.InnerText = relatedKeyword.Keyword;

thesaurusTerm.AppendChild(termTypeR);
termTypeR.AppendChild(termTypeTab);
termTypeR.AppendChild(termTypeT);

thesaurusTerm.AppendChild(termDescriptionR);
termDescriptionR.AppendChild(termDescriptionTab);
termDescriptionR.AppendChild(termDescriptionT);

thesaurusTerm.AppendChild(termBreakR);
termBreakR.AppendChild(termBreak);

}
}

}


Now I need to add different xml fragments to the package. The XML fragments for settings, footer and styles are added with this generic function.

AddPart(pkgOutputDoc, uri, partDocumentXML,
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
"rId2",
"/word/settings.xml",
"settings.xml");

/// <summary>
/// Adds the part from an embedded XML to the Package.
/// </summary>
/// <param name="package">The package.</param>
/// <param name="documentUri">The document URI.</param>
/// <param name="partDocumentXML">The part document XML.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="relationshipType">Type of the relationship.</param>
/// <param name="relationId">The relation id.</param>
/// <param name="partPath">The part path.</param>
/// <param name="embeddedFile">The embedded file.</param>
private void AddPart(Package package, Uri documentUri, PackagePart partDocumentXML,
string contentType, string relationshipType, string relationId, string partPath,
string embeddedFile)
{
XmlDocument xdoc = new XmlDocument();
Uri uriPart = new Uri(partPath, UriKind.Relative);
PackagePart part = package.CreatePart(uriPart, contentType);
Uri relativePartUri =
PackUriHelper.GetRelativeUri(documentUri, uriPart);
Stream contentStream = GetEmbeddedXml(embeddedFile);
xdoc.Load(contentStream);
contentStream.Close();
xdoc.Save(part.GetStream());
partDocumentXML.CreateRelationship(relativePartUri, TargetMode.Internal, relationshipType, relationId);
}


The footer can contain the page number by using this xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:p>
<w:pPr>
<w:jc w:val="right"/>
</w:pPr>
<w:fldSimple w:instr=" PAGE \* MERGEFORMAT ">
<w:r>
<w:t>1</w:t>
</w:r>
</w:fldSimple>
</w:p>
</w:ftr>


Tuesday, June 17, 2008

Generics with Actions

An action is pointer to a function with no return value which you can use for working with generic lists. It looks like the Predicate functions, but the referenced method won't return a boolean value.

Still, the only parameter in the function is of the type of the generic. In this example, I extend the DateRange class with an Action.

An example of such an implementation:

/// <summary>
/// DateRange is a helper class to work with dates
/// </summary>
public class DateRange
{
private DateTime _startDate = DateTime.MinValue;
private DateTime _endDate = DateTime.MaxValue;

public DateTime StartDate
{
get { return _startDate; }
}
public DateTime EndDate
{
get { return _endDate; }
}

public DateRange(DateTime startDate, DateTime endDate)
{
_startDate = startDate;
_endDate = endDate;
}

/// <summary>
/// Gets the IsInPeriod method.
/// </summary>
/// <value>The in period.</value>
public Predicate<DateTime> InPeriod
{
get { return IsInPeriod; }
}

/// <summary>
/// Determines whether the specified date is in the period set by startdate and enddate.
/// </summary>
/// <param name="date">The date.</param>
/// <returns>
/// <c>true</c> if the specified date is in the period; otherwise, <c>false</c>.
/// </returns>
private bool IsInPeriod(DateTime date)
{
if ((date >= StartDate) && (date < EndDate))
{
return true;
}
else
{
return false;
}
}

/// <summary>
/// Gets the WriteNumberOfDaysFromStartDate method.
/// </summary>
/// <value>The write number of days till end.</value>
public Action<DateTime> WriteNumberOfDaysFromStart
{
get { return WriteNumberOfDaysFromStartDate; }
}
/// <summary>
/// Writes the number of days from the start date of the period.
/// </summary>
/// <param name="date">The date.</param>
private void WriteNumberOfDaysFromStartDate(DateTime date)
{
Console.WriteLine("{0} days to go", ((TimeSpan)(date - StartDate)).Days);
}
}


You can now use this conditional predicate with different Generic methods.

public class ActionExamples
{
public static void Main()
{
// fill an example list
List events = new List();
events.Add(DateTime.Now.AddDays(-1));
events.Add(DateTime.Now.AddDays(-2));
events.Add(DateTime.Now);
events.Add(DateTime.Now.AddDays(1));
events.Add(DateTime.Now.AddDays(2));
events.Add(DateTime.Now.AddDays(3));
events.Add(DateTime.Now.AddDays(4));

//create a DateRange object for tomorrow
DateRange nextMonth = new DateRange (new DateTime(2008,7,1), new DateTime(2008,7,31) )

//get events for next month
List nextMonthEvents = events.FindAll(nextMonth.InPeriod);

//write days from start of nextMonth to console
events.ForEach(nextMonth.WriteNumberOfDaysFromStart);
}
}

Monday, June 16, 2008

Generics with Predicates

A predicate is pointer to a boolean function which you can use for querying generic lists.
With these methods, coding against generic lists will be much easier. But one problem with these predicates is that the only parameter in the function is of the type of the generic. A solution for this is refactoring the predicate to a class, where you can provide these parameters to properties or the constructor.

An example of such an implementation:

/// <summary>
/// DateRange is a helper class to work with dates
/// </summary>
public class DateRange
{
private DateTime _startDate = DateTime.MinValue;
private DateTime _endDate = DateTime.MaxValue;

public DateTime StartDate
{
get { return _startDate; }
}
public DateTime EndDate
{
get { return _endDate; }
}

public DateRange(DateTime startDate, DateTime endDate)
{
_startDate = startDate;
_endDate = endDate;
}

/// <summary>
/// Gets the IsInPeriod method.
/// </summary>
/// <value>The in period.</value>
public Predicate<DateTime> InPeriod
{
get { return IsInPeriod; }
}

/// <summary>
/// Determines whether the specified date is in the period set by startdate and enddate.
/// </summary>
/// <param name="date">The date.</param>
/// <returns>
/// <c>true</c> if the specified date is in the period; otherwise, <c>false</c>.
/// </returns>
private bool IsInPeriod(DateTime date)
{
if ((date >= StartDate) && (date < EndDate))
{
return true;
}
else
{
return false;
}
}
}


You can now use this conditional predicate with different Generic methods.

public class PredicateExamples
{
public static void Main()
{
// fill an example list
List events = new List();
events.Add(DateTime.Now.AddDays(-1));
events.Add(DateTime.Now.AddDays(-2));
events.Add(DateTime.Now);
events.Add(DateTime.Now.AddDays(1));
events.Add(DateTime.Now.AddDays(2));
events.Add(DateTime.Now.AddDays(3));
events.Add(DateTime.Now.AddDays(4));

//create a DateRange object for tomorrow
DateRange tomorrow = new DateRange (DateTime.Today.AddDays(1), DateTime.Today.AddDays(2))

//get a boolean if there is an event tomorrow
bool tomorrowHasEvents = events.Exists(tomorrow.InPeriod);

//get events for tomorrow
List tomorrowEvents = events.FindAll(tomorrow.InPeriod);

//get first event for tomorrow (first item in list!)
DateTime tomorrowFirstEvent = events.Find(tomorrow.InPeriod);
//get last event for tomorrow
DateTime tomorrowLastEvent = events.FindLast(tomorrow.InPeriod);

//get the index of the first event for tomorrow
int tomorrowFirstEventIndex = events.FindIndex(tomorrow.InPeriod);
//get the index of the last event for tomorrow
int tomorrowLastEventIndex = events.FindLastIndex(tomorrow.InPeriod);

//remove all events for tomorrow
int removedItems = events.RemoveAll(tomorrow.InPeriod);

//are all events in the list tomorrow
bool allEventsTomorrow = events.TrueForAll(tomorrow.InPeriod);

}
}

Friday, June 13, 2008

.NET 2.0 = .NET 3.0 = .NET 3.5

Yesterday I had a discussion on an internal Microsoft Developers meeting about the status of .NET 3.5. We had presented that .NET 3.0 is an extension of .NET 2.0, and not a new version. My statement that the status of .NET 3.5 is the same, it is basically .NET 2.0 with extra features, was received sceptically.
Just to prove I'm right, here my observations.

Build a very simple .NET Console application, using two lines of code:

Console.WriteLine("Hello World");
Console.WriteLine("using version: {0}", System.Environment.Version.ToString());


With Visual Studio 2008, you can build this with all three version of the framework. And all three executables yields the same results: using version: 2.0.50727.1433.

ILDASM one of these assemblies gives the same assembly header:

// Metadata version: v2.0.50727
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 2:0:0:0
}


Proving all three versions are based on the .NET core version 2.0 (and this is the same version you should configure in ASP.NET. There is no v3 there).
Just to be sure if you want to upgrade to 3.5 at your customer to mention that version 3.5 also is basically .NET 2.0, with some extra features added. I won't say that the libraries of .NET 2.0 are the same with 3.5, but runtime versions are equal.

Rick Strahl blogged about this a while ago.

Friday, May 2, 2008

Unexpected SqlException...

On the production servers at the customer I'm currently working for, we had a strange error regarding a new feature in our reporting tools. A strange error, because during the development and test cycle of our release, we hadn't found any issues regarding SQL errors.

The error firing was 'The count aggregate operation cannot take a uniqueidentifier data type as an argument', during the execution of SELECT COUNT(Item.Id) AS ItemCount ... while the datatype of Item.Id was uniqueidentifier.

The only difference between our development, test and production servers is the version of MS SQL Server. While we migrated our dev and test servers to 2005, production was still behind on version 2000. And version 2000 can't run an aggregate operation on a uniqueidentifier, you need to run it with the asterisk instead (like COUNT(*) ).

Fortunately, migration to MS-SQL 2005 is already scheduled to happen soon :)

Wednesday, March 26, 2008

C# test automation with Internet Explorer

As a follow up on my previous post, I had the idea you can do the same in managed code (in your test library, for instance). Although this won't exactly be a unit test (especialy with the example search form, it's more integration testing), it can be usefull in some scenarios.

You need a reference to two COM dll's,
MSHTML
Microsoft HTML Object Library
SHDocVw
Microsoft Internet Controls


After that, you can use the following example code inside your test (I present it here as one block. Some things can be put in test setup and teardown):

SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorerClass();
object missing = new object();
ie.Navigate("http://localhost/Default.aspx", ref missing, ref missing, ref missing, ref missing);
ie.Visible = true;
while (ie.Busy)
{
System.Threading.Thread.Sleep(500);
}
mshtml.HTMLDocumentClass doc = ie.Document as mshtml.HTMLDocumentClass;
doc.getElementById("searchbox").setAttribute("value", "test", 0);
doc.getElementById("searchsubmit").click();
while (ie.Busy)
{
System.Threading.Thread.Sleep(500);
}
string bodytext = doc.body.innerHTML;
Debug.Assert( bodytext.IndexOf("documents found")>0);

ie.Quit();