Wednesday, February 19, 2014
Quickly update WebPart titles by CSOM
Friday, December 20, 2013
Lightweight monitoring solution with PowerShell
As UI bugs will be noticed directly, those more technical features are hardly noticed directly on failure. So there was the need to script and monitor those features.
As I wanted a simple, free and easy to expand solution (I worked with HostMonitor before, it's easy to write small tests there, but it isn't free), I decided to create my own PowerShell framework. Here it is. It is written for PowerShell 2.0, so webrequests are not executed with Invoke-WebRequest but with the C# System.Net variant.
The script is basically executing tests found in one folder, format the results as HTML and sending it by email with a SMTP server. Things to improve are more test outcomes (now it is Success or Failure, but there might be a yellow inbetween warning or so), or possibly using a tool like Selenium to run tests inside a browser session as well.
Tuesday, December 11, 2012
No search results on anonymous SP2010 website
A lot of the suggestions Google came up with weren't applicable in this situation. It turned out the Anonymous policy on one of the zones of the web application was 'Deny all'. This zone wasn't crawled, but the policy was still propagated to the index and used on the other zone. This meant that, as the content had a deny all flag for anonymous users, security trimming didn't allowed the return of any results.
Tuesday, June 5, 2012
Bug in Duet Enterprise NetWeaver configuration wizard
What turns out is that you can specify the user name prefix in the Configuration wizard, but the wizard always turns the characters to uppercase. So the wizard step is quite pointless, as you need to delete the user mapping and recreate it again with the proper casing with SPRO, SAP Reference IMG - SAP NetWeaver - Gateway - Configuration - Connection Settings - SAP NetWeaver Gateway to Consumer - Define Consumer Issuer Certificate & Map SAP User Names to Consumer.
Update: this behavior is addressed in SAP Note 1688843.
Thursday, March 1, 2012
MSOCAF false positives
A couple of examples:
- The tool implements SPDispose check. It is a fantastic tool to detect the right disposal of SharePoint objects, but sometimes it can't determine the context right. These errors are taged with 'could be false positive'
- MSOCAF implements a couple custom FxCop rules, but these are the quite problematic ones. For example, it detects the usage of deprecated classes and members. It uses the list found on MSDN with deprecated members. But in the notes added, there is the source of errors:
Note: Types and methods in the Microsoft.SharePoint.Portal namespace are not included in these lists because, with a few exceptions, the entire namespace has been made obsolete.
What it means, the Microsoft.SharePoint.Portal namespace? If you look at the MSDN documentation, you see that all classes directly in this namespace are deprecated or internal. But the FxCop rule is implemented as (thank you Reflector):if (fullName.Equals(str3) || fullName.Contains("Microsoft.SharePoint.Portal"))
. And here disaster strikes. My code use a new SP2010 class AverageRatingFieldControl. But as this one is in the Microsoft.SharePoint.Portal.WebControls namespace, it is marked as a deprecated class (see FxCop rule). And now I need time to justify the use of a deprecated method.
- MSOCAF does like logging to ULS, no problem with that. It checks a couple of rules:
- detects if Unified Logging Service (ULS) logging is performed in every catch block.
- SPDiagnosticsService should be called at start and end of Timer Jobs, Event Receiver, Feature Receiver, and Web Services functions.
- Any errors happening in the Feature Receiver upon activation and deactivation should be logged to the ULS and the exception must be reported back to SharePoint.
Too bad that the rules used in MSOCAF still need some tweeking.
Sunday, December 4, 2011
Remove BDC Models in PowerShell
$context = "http://sharepoint.local"
$bdc = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType Catalog -ServiceContext $context
foreach ($model in $bdc.GetModels("*") ) {
Remove-SPBusinessDataCatalogModel –Identity $model
}
Thursday, August 11, 2011
SharePoint File Upload
ListsSoapClient client = new ListsSoapClient();
XElement result = client.GetListItems("{642DF480-74CB-4EDC-865C-CA009054998F}", null, null, null, null, null, null);
XNamespace rs = "urn:schemas-microsoft-com:rowset";
XNamespace z = "#RowsetSchema";
var data = result.Descendants(rs + "data").Descendants(z+"row");
CopySoapClient copyClient = new CopySoapClient();
FieldInformation[] fields;
byte[] output;
uint result2 = copyClient.GetItem(Uri.EscapeUriString("http://example.hostname/"+"Documents/Report.xls"), out fields, out output);
string destinationUrl = "http://example.hostname/Documents/Test.xls";
string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) };
List<fieldinformation> fieldsList = new List<fieldinformation>();
CopyResult[] copyResults;
uint result3 = copyClient.CopyIntoItems("+", destinationUrls, fieldsList.ToArray(), output, out copyResults);
WebRequest request = WebRequest.Create(destinationUrl);
request.Method = "PUT";
request.Credentials = CredentialCache.DefaultCredentials;
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
stream.Write(output, 0, output.Length);
}
WebResponse response = request.GetResponse();
response.Close();
Friday, August 5, 2011
Tips while working with SharePoint projects in VS2010
- Install the CSKDev tools
- Use quick deploy on the project to test small changes in markup and code
- Page layouts don't support Intellisense when double clicking the aspx (VS2010 opens the file in textmode). Right-click and use 'View Code' or 'View Markup' will open the file as a webpage, with fill Intellisense support.
- To start with already filled page layouts based on the content type, use the CSKDev 'Create page layout' on the content type in the Server Explorer.

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’.
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#
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.
Thursday, August 19, 2010
VBScript to detect if there is a COM+ application instance running
Here is the quickly written vbscript:
running = False
Dim oCatalog
Set oCatalog = CreateObject("COMAdmin.COMAdminCatalog")
sName = "Tridion Content Manager"
Dim result
set apps = oCatalog.GetCollection("Applications")
apps.Populate
For Each app In apps
If app.Name = sName Then
Set objAppInst = apps.GetCollection("ApplicationInstances",app.Key)
objAppInst.Populate
for each inst in objAppInst
pId = inst.Value("ProcessID")
running = not ( inst.Value("IsPaused") or inst.Value("HasRecycled"))
if running then
Exit For
end if
Set objAppInst = nothing
Next
Exit For
End If
Next
set apps = Nothing
set oCatalog = nothing
MsgBox pid & " " & running
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.
Monday, July 5, 2010
Upgraded Certification
With the new version of the .NET Framework, I needed to upgrade my .NET Certifications to this new version. A couple of months ago, I did the beta versions of these exams, and last week I got the results. I passed all the exams I did. They were not easy, so I was quite surprised to receive all the results positively back.
Monday, January 18, 2010
Updated XSLT for CC.NET in SharePoint
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes" />
<xsl:template match="/">
<table border="0" cellpadding="0" cellspacing="0">
<thead class="ms-viewheadertr">
<th style="text-align:left;" scope="col" class="ms-vh2-nograd" nowrap="nowrap">Project</th>
<th class="ms-vh2-nograd" > </th>
<th style="text-align:left;" scope="col" class="ms-vh2-nograd" nowrap="nowrap">Status</th>
<th class="ms-vh2-nograd" > </th>
<th style="text-align:left;" scope="col" class="ms-vh2-nograd" nowrap="nowrap">Last buildtime</th>
<th class="ms-vh2-nograd" > </th>
<th style="text-align:left;" scope="col" class="ms-vh2-nograd" nowrap="nowrap">Buildlabel</th>
<th class="ms-vh2-nograd" > </th>
<th style="text-align:left;" scope="col" class="ms-vh2-nograd" nowrap="nowrap">Activity</th>
</thead>
<tbody>
<xsl:apply-templates select="/CruiseControl/Projects/Project">
<xsl:sort select="@name"/>
</xsl:apply-templates>
</tbody>
</table>
</xsl:template>
<xsl:template match="Project">
<tr>
<xsl:if test="position() mod 2 != 1">
<xsl:attribute name="class">ms-alternating</xsl:attribute>
</xsl:if>
<td class="ms-vb2" align="top" nowrap="nowrap">
<xsl:element name="a">
<xsl:attribute name="onfocus">OnLink(this)</xsl:attribute>
<xsl:attribute name="href">
<xsl:value-of select="@webUrl"/>
</xsl:attribute>
<xsl:attribute name="onclick">GoToLink(this);return false;</xsl:attribute>
<xsl:attribute name="target">_self</xsl:attribute>
<xsl:value-of select="@name"/>
</xsl:element>
</td>
<td> </td>
<xsl:element name="td">
<xsl:attribute name="class">ms-vb2</xsl:attribute>
<xsl:attribute name="align">top</xsl:attribute>
<xsl:attribute name="style">padding-bottom: 3px;
<xsl:choose>
<xsl:when test="@lastBuildStatus='Failed'">
color:red;
</xsl:when>
<xsl:when test="@lastBuildStatus='Exception'">
color:red;
</xsl:when>
<xsl:when test="@lastBuildStatus='Unknown'">
color:yellow;
</xsl:when>
<xsl:when test="@lastBuildStatus='Failure'">
color:red;
</xsl:when>
<xsl:otherwise>
color:green;
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:value-of select="@lastBuildStatus"/>
</xsl:element>
<td> </td>
<td class="ms-vb2" style="padding-bottom: 3px;" align="top">
<xsl:value-of select="substring-before(@lastBuildTime,'T')"/> 
<xsl:value-of select="substring-before(substring-after(@lastBuildTime,'T'),'.')"/>
</td>
<td> </td>
<td class="ms-vb2" style="padding-bottom: 3px;text-align:right;" align="top">
<xsl:value-of select="@lastBuildLabel"/>
</td>
<td> </td>
<xsl:element name="td">
<xsl:attribute name="class">ms-vb2</xsl:attribute>
<xsl:attribute name="align">top</xsl:attribute>
<xsl:attribute name="style">
padding-bottom: 3px;
<xsl:choose>
<xsl:when test="@activity='Building'">
color:red;
</xsl:when>
<xsl:when test="@activity='CheckingModifications'">
color:yellow;
</xsl:when>
<xsl:otherwise></xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:value-of select="@activity"/>
</xsl:element>
</tr>
</xsl:template>
</xsl:stylesheet>
Saturday, October 24, 2009
Getting Hippo Site Toolkit demo to work
1. Download the wars, drop them in your Tomcat servlet container and start Tomcat (see in_servlet_container, but with different wars).
2. Checkout the HST2 project, start the cms and the site of the demosuite in the buildin Jetty servlet container.
So I use Tomcat, and its saying in another page to rename the cms war to cms.war, there is no mention of renaming the site war to site.war. But in the rest of the documentation the assumption is made to use the /site URL. I'm no Tomcat guru, so how should I know that the webapp wars are used as URI shortcuts ;).
But that's the main pain in the ass with OSS documentation, it's mostly incomplete. How hard should it be to test your HOWTO for a plain and simple demo. Adding a simple step 1.5: "rename the cms war to cms.war and the site war to site.war" isn't a big deal, but makes a difference of about 1 hour for a Hippo n00b figuring out what's going on!
Wednesday, September 30, 2009
Demo Parallel Extensions .NET 4.0
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
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
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
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!