tag:blogger.com,1999:blog-100531612024-03-13T00:39:01.465+00:00Geekly ever after"Developer-Speak" about developer subjects! Mainly focused on C# and .NETAnonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.comBlogger41125tag:blogger.com,1999:blog-10053161.post-1698047305385847282014-04-21T18:51:00.001+01:002014-04-21T18:52:35.671+01:00Being a "DevOp"I've read an interesting post today about a current trend in the software development industry: <a href="http://jeffknupp.com/blog/2014/04/15/how-devops-is-killing-the-developer/">http://jeffknupp.com/blog/2014/04/15/how-devops-is-killing-the-developer/</a>.
<br/>
The post rants about the "full-stack" developer. The "one-man band" that is basically responsible for pretty much everything from writing code, managing databases and even being a system administrator.
<br/>
Raise your hand if you ever felt like a "DevOp" :) I know I have!Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-69261117793343511092013-02-08T22:47:00.001+00:002013-02-08T22:47:49.756+00:00Transforming web.config in TFS builds<span lang="EN-US" style="mso-ansi-language: EN-US;"><span style="font-family: Calibri;">XDT transforms
(mostly known as web.config transformations) are most useful to perform transformations on
your web.config at deploy time (for more details about web.config transformations you can take a peek at <a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx">http://msdn.microsoft.com/en-us/library/dd465326.aspx</a>). Say that you’re publishing a web application in
the project configuration “Release”. If you have a “web.Release.config” file in
your application, that file contains the transformation to be applied over the
web.config. However, if you are using TFS builds to create the deployable
outputs, you might find yourself in unexplored territory, because your XDT’s
will not be ran as when you explicitly publish from within Visual Studio.</span></span><br />
<span lang="EN-US" style="mso-ansi-language: EN-US;"><span style="font-family: Calibri;">Microsoft might have inadvertedly shed some light on this subject, as they have recently made available a prerelease of an API to perform these XDT transformations
which is available through NuGet here: <span style="mso-spacerun: yes;"> </span></span><a href="https://nuget.org/packages/Microsoft.Web.Xdt"><span style="color: blue; font-family: Calibri;">https://nuget.org/packages/Microsoft.Web.Xdt</span></a><span style="font-family: Calibri;">.
<o:p></o:p></span></span><br />
<span lang="EN-US" style="mso-ansi-language: EN-US;"><span style="font-family: Calibri;">Knowing
this, I’ve decided to explore this new API and put it to good use. I've created a CodeActivity to use this API and integrate the
XDT transformations in my build process. Another alternative (I was previously
using) is to rely on an external tool to do the transformations for you and
invoke that tool from within your build process (see the Config Transformation
Tool here: </span><a href="http://ctt.codeplex.com/"><span style="color: blue; font-family: Calibri;">http://ctt.codeplex.com</span></a><span style="font-family: Calibri;"> ).<o:p></o:p></span></span><br />
<br />
<div class="MsoNormal" style="margin: 0cm 0cm 10pt;">
<span lang="EN-US" style="mso-ansi-language: EN-US;"><span style="font-family: Calibri;">So here’s a
code activity to do just that: run XDT on your web.config depending on the
project configuration being built:</span></span></div>
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
[BuildActivity(HostEnvironmentOption.All)]
public class ApplyWebConfigTransformationsActivity : CodeActivity
{
[RequiredArgument]
public InArgument<BuildSettings> BuildSettings { get; set; }
protected override void Execute(CodeActivityContext context)
{
IBuildDetail buildDetail = context.GetExtension<IBuildDetail>();
string publishWebSitesFolder = Path.Combine(buildDetail.DropLocation, "_PublishedWebsites");
var webConfigFiles = BuildUtils.SearchFiles(publishWebSitesFolder, "web.config");
BuildSettings buildSettings = context.GetValue<BuildSettings>(this.BuildSettings);
if (buildSettings==null)
return;
var currentConfiguration = buildSettings.PlatformConfigurations[0].Configuration;
foreach (var webConfig in webConfigFiles)
{
BuildLog.Info(context, string.Format("Found {0} to transform in build configuration {1}", webConfig, currentConfiguration));
var webConfigDirectory = Path.GetDirectoryName(webConfig);
var targetTranformationPath = Path.Combine(webConfigDirectory, string.Concat("web.", currentConfiguration, ".config"));
if (!File.Exists(targetTranformationPath))
{
BuildLog.Info(context, string.Format("Unable to find target transformation: {0}", targetTranformationPath));
continue;
}
// create xml document
var doc = new XmlDocument();
doc.Load(webConfig);
// apply xml transformation
var transf = new XmlTransformation(targetTranformationPath);
transf.Apply(doc);
try
{
doc.Save(webConfig);
BuildLog.Info(context, "Web.config succesfully transformated");
}
catch (UnauthorizedAccessException)
{
BuildLog.Info(context, "Web.config is currently in read-only mode and cannot be transformed");
}
}
}
}
]]>
</script>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-50279560670597363672013-01-01T15:14:00.003+00:002013-01-01T15:21:08.977+00:00Premature optimizationFirst of all, happy New Year!<br />
Now, on the first post of the year, I would like to quote the great <a href="http://en.wikipedia.org/wiki/Donald_Knuth">Donald Knuth</a>: "We should forget about small efficiencies, say, about 97% of the time: <b>Premature optimization is the root of all evil</b>. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; <b>but only after that code has been identified</b>."<br />
<br />
I've been defending this for a long time, but I keep stumbling upon developers that disregard this rule of thumb. When faced with performance issues most tend to use an empirical approach: read the source code and attempt to make informed guesses on what may be the critical code. Most forget about code profilers that can accurately identify the critical code. I believe this is not only their fault, but also a fault of the education system, that failed to instruct and emphasize on the relevance of such tools.<br />
<br />
Here's another quote (from <a href="http://www.amazon.co.uk/Continuous-Delivery-Deployment-Automation-Addison-Wesley">Continuous Delivery</a>): "Don't guess; measure". My experience tells me, that, most of the times, our informed guesses are not the main culprit of our performance issues. So, the best approach is to clearly identify the culprits and deal with them. What's the point in spending time solving an issue when there's another issued that on itself may represent a 50% improvement? We rarely have the time to perfect our code until we deem it as good and fast as we'ld like, so in such situations a programmer should be pragmatic (which I believe to be one of the most relevant qualities in programmers. By the way, if you haven't read <a href="http://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X">The Pragmatic Programmer</a> yet, it's time to start thinking about it).<br />
<br />
Happy coding in 2013!Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-33976214099094734892012-11-10T17:54:00.001+00:002012-11-10T17:56:09.296+00:00Webinar on Software Best Practices and ROII've recently seen a webinar that I would like to share with you. It concerns software best practices and their impact on companies, mainly focusing on these practices ROI. If you're trying to understand if best practices really work, or struggling to convince anyone of this, than this presentation just might be what you're looking for. I would like to highlight not only the content of the presentation, but also the Q&A session at the end of the talk.<br />
The presenter is Steve McConnell, author for several renowned books. I've recently read his "<a href="http://www.amazon.co.uk/Software-Estimation-Demystifying-Black-Art/dp/0735605351">Software Estimation: Demystifying the Black Art</a>" and strongly recommend it!<br />
<br />
I've asked for permission to publish the link for this webinar and Steve has given his blessing, so here's the link to a <a href="https://event.on24.com/eventRegistration/EventLobbyServlet?target=registration.jsp&eventid=516803&sessionid=1&key=B4DF1D1DDC6C72747C05D5C6EF1C872C&sourcepage=register">recording of Steve's talk</a>.<br />
<br />
<br />
<br />Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-88003028589934066772012-08-26T20:22:00.002+01:002012-08-26T20:22:49.334+01:00Customizing your application resourcesPicture this: You have an asp.net application in which you support multiple languages through the use of resources (global and local resources) and depend on the .NET framework to do all the hard work of loading the correct resources depending on the current UI culture. All is well until you have a requirement of customizing a handful of resources (either per user, per customer, or any other criteria you may think of). <br />
Anyone who has enough knowledge of the .NET framework, tells you right away that you can create your own resource provider and take control of all the aforementioned mechanism. You can find several articles online, including MSDN articles with a detailed explanation of how to provide your own resource provider (<a href="http://msdn.microsoft.com/en-us/library/aa905797.aspx">here's an interesting article about it</a>). <br />
There are several online resources supplying examples of resource providers that load resources from the database and other similar approaches. However in this specific situation we would like to preserve the default provider behaviour and override only when the target resource has been customized. It seems pretty easy, right? We override the default provider, find if the target resource has been customized, if so, return the new value, otherwise, call the base class implementation, right?<br />
Wrong! You can't extend it because the GlobalResXResourceProvider class (default provider responsible for resolving global resources) is internal, the LocalResXResourceProvider class (default provider responsible for resolving local resources) is internal and the ResXResourceProviderFactory class (provider factory responsible for creating instances of the global and local resource providers) is... guess what... internal! So, it seems Microsoft did not want us to extend this classes...<br />
Right now we could opt to rewrite this providers ourselves OR we could avoid that hard work and opt to create our resource providers as proxies/surrogates (see the design pattern <a href="http://sourcemaking.com/design_patterns/proxy">here</a>) that end up invoking the default providers. The only question is how do we initialize these default providers if they are internal... It's not pretty, but I can only think of reflection. In this case, instead of accessing both default providers through reflection I chose to minimize the points of failure by creating only the default resource provider factory through reflection and calling it's public interface to retrieve the default provider instances.<br />
So here's the how our brand new resource provider factory looks like:<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
public class CustomizableResourceProviderFactory : ResourceProviderFactory
{
private ResourceProviderFactory GetDefaultResourceProviderFactory()
{
string typeName = "System.Web.Compilation.ResXResourceProviderFactory, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
ResourceProviderFactory factory = (ResourceProviderFactory)Activator.CreateInstance(Type.GetType(typeName));
return factory;
}
public override IResourceProvider CreateGlobalResourceProvider(string classKey)
{
var defaultFactory = GetDefaultResourceProviderFactory();
var fallbackProvider = defaultFactory.CreateGlobalResourceProvider(classKey);
return new CustomizableLocalResourceProvider(classKey, fallbackProvider);
}
public override IResourceProvider CreateLocalResourceProvider(string virtualPath)
{
var defaultFactory = GetDefaultResourceProviderFactory();
var fallbackProvider = defaultFactory.CreateLocalResourceProvider(virtualPath);
string classKey = virtualPath;
if (!string.IsNullOrEmpty(virtualPath))
{
virtualPath = virtualPath.Remove(0, 1);
classKey = virtualPath.Remove(0, virtualPath.IndexOf('/') + 1);
}
return new CustomizableLocalResourceProvider(classKey, fallbackProvider);
}
}
]]>
</script><br />
Plain simple, just create our brand new customizable resource providers and pass them a "fallback" provider, which will be used to resolve any resource that hasn't been customized. Our new resource providers just have to determine if they should resolve the resource or if they should use the "fallback" provider (which will be the default provider). Something like this:<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
public override object GetObject(string resourceKey, CultureInfo culture)
{
var customResource = "TODO"; // do your stuff to obtain a custom resource here
if (!string.IsNullOrEmpty(customResource))
return customResource;
return FallbackProvider.GetObject(resourceKey, culture);
}
]]>
</script><br />
<br />
Nice and easy! Accessing internal stuff in the framework is obviously something to be avoided, but I think we're pretty safe here. Resource providers have been around for a while and I don't expect Microsoft to remove this class sooner.Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-49436960989068675992012-07-07T19:50:00.000+01:002012-07-07T19:51:37.718+01:00Bug Hunting with NDepend<br />
Here's another post about NDepend (one of my favorite tools of the trade)! I've recently installed the new NDepend v4 and here's how I've used it for the first time.<br />
I was going through the logs of the asp.net application I'm developing and found reasons to believe that somewhere in the application an object was being written on the viewstate that wouldn't serialize as supposed and throw an exception.<br />
Now, how do we find and fix this bug easily? Surely we could attempt to find in the solution for all uses of the Viewstate and reading that code, but that would be too much code to read, so I've decided to use NDepend to aid me.<br />
So here's what I've though:<br />
- most of the times we use the viewstate in this application is through a property on a page or user control;<br />
- if it's a serialization error, we can ignore properties whose type is a primitive type as we're likely dealing with a class defined in our application;<br />
<br />
Here's how I've done it:<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-2lgoP3rkL1I/T_iEyaibIOI/AAAAAAAABQo/e8BzWJWgXN8/s1600/image002.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-2lgoP3rkL1I/T_iEyaibIOI/AAAAAAAABQo/e8BzWJWgXN8/s1600/image002.png" /></a></div>
<br />
From here I only had 3 source code locations to investigate! Much easier than going through the entire application, isn't it?<br />
<br />
The ability to query your code (and now in a syntax much alike the linq queries I write day after day) is something very powerful, and every once in a while we might find a new way of use this power!Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-91199588909597278592012-02-08T00:00:00.001+00:002012-07-07T19:52:34.773+01:00NCrunchI think I can say that I know most of the relevant development tools related with the .NET world, so it's obviously not every day that I stumble upon a new tool worth of notice. But today (or rather tonight) was one of those days (or nights). Even more relevant is the fact that this one is free (at least for know, while its considered a beta version).<br />
I'm talking about NCrunch (http://www.ncrunch.net/). It's a tool targeted for developers using Visual Studio and doing TDD. It aims to decrease the amount of time we loose compiling and runing our unit tests, by not requiring us to do it at all! That is, it compiles and runs our tests in background automatically. Even before we save the file with the unit tests source code!<br />
I'm not going to write a full review, but I dare you to use a handful of minutes looking at the video presented in the NCrunch homepage to see the awesome features available.<br />
<br />
Happy coding and testing!Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-20085731285682750722012-02-05T19:06:00.003+00:002012-02-05T19:09:28.970+00:00Reviewing uCertify 70-515-CSharp MCTS exam prepkit (Part 2)Hi again!<br />
<br />
As I wrote in the last post, I'm reviewing a preparation kit for the 70-515-CSharp MCTS exam from uCertify.<br />
Today, I'm here to write about what I've found to be the strengths and weaknesses of this product.<br />
<br />
This is a full-featured product that pretty much covers everything this kind of tools should cover. I would highlight the following strengths of the product:<br />
<ul>
<li>Easy and intuitive user-interface;</li>
<li>Rather complete explanations of why an answer is either correct or incorrect. Some other products I've seen before are only concerned about wrong questions, and dismiss explanations about the correct which may be as relevant as the explanation for wrong questions;</li>
<li>Extensive study materials covering most topics targeted by the exam. I didn't use them much myself, because I would rather take a peek at documentation supplied in msdn (links to these online resources are also supplied in a section of this product) and try the old "learn by doing" method. However there are people that would rather read the study materials and retake the tests, so I believe this is a useful feature.</li>
<li>Several kinds of test "layouts", from the traditional format, into adptative tests (which dynamically adapt the question complexity to your answers. That is, if you're getting your answers right, the complexity will gradually increase, otherwise they will decrease, thus showing you questions accordingly to your kownledge level).</li>
</ul>
and my favorite feature:<br />
<ul>
<li>The hability to take quick tests. Say that you only have a handful of minutes and you want to study a bit. Just open the application, and start a fixed time test, specifying how many minutes you wish to spend. Lacking enough free time to take complete tests, I found myself using this kind of tests a lot.</li>
</ul>
<br />
I would like to point out that despite the target of this application is to prepare yourself to take the 70-515 exam, you can also use it as a way of enriching and testing your knowledge. For instance, I find out that I have some serious gaps in ASP.NET MVC (which doesn't surprise me, knowing that I haven't developed any serious application in MVC). I just might be targeting MVC as one of the next things to investigate deeper.<br />
Bottom line: if you've decided to take this exam, this kind of tools are definitely a good way of testing and evaluating your knowledge and I would recommend the uCertify product. But always remember that you might find different questions and topics in the real exam, so real-world experience is a must-have. Don't take your exam for granted just because you have good results in the preparation tool.<br />
<br />
By the way, any readers of my blog are entitled to <span style="background-image: initial; background-repeat: initial initial;">a 10% <wbr></wbr>discount (in addition to
any existing sale) on any test preparation software from uCertify
(just use the discount code '<b>UCPREP</b>' in the uCertify <wbr></wbr>shopping cart)</span><span style="background: white; color: #500050; font-size: 10.0pt;">.</span>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-14947584335552097312012-01-02T23:25:00.000+00:002012-01-03T11:23:21.924+00:00Reviewing uCertify 70-515-CSharp MCTS exam prepkitHi! Long time since my last post, right? Let's hope I can make a few more posts in this brand new year than I did in 2011.<br />
<br />
I'll start the year by reviewing a preparation kit for the 70-515-CSharp MCTS exam from uCertify.<br />
I have got a offer from them to review their PrepKit (which you can find <a href="http://www.ucertify.com/exams/Microsoft/70-515-CSHARP.html">here</a>) and I have accepted that challenge. Initially it looks fully-featured and with a nice UI, I haven't had the time to make a few tests and that's what counts most, so I'll leave any further review opinions for later. As soon as I am done with the full review I will post it for you all.<br />
<br />
Best regards and a Happy New YearAnonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-59146362797528465752011-08-04T09:13:00.003+01:002011-08-07T11:09:56.434+01:00Redistributing user controlsEver needed a recipe to build a user control library to use across several web applications? Here's one!<br />
First of all, we should realise that this isn't something you can get out-of-the-box and as such, there are several half-solutions out there, and as far as I know there isn't a perfect one. The one I'm presenting here suits best for what I'm trying to achieve, and it doesn't mean it is the best for other people's situation.<br />
<br />
My main motivation, other than user control reusability was to create a project structure that allowed me to migrate a webapplication developed in VB.NET to C#. This has to be done over a long-period and I don't want to keep adding code in VB.NET any time a new feature is needed. Hence I decided to build user controls in C# that I could use in VB.NET pages, thus avoiding any code-behind code in VB.NET.<br />
<br />
There is however a big problem with creating user controls outside web applications: We're not supposed to do it! When you build a page (aspx) or a user control (ascx) in a regular web application, the compiler creates an assembly where each of this files produces a class that inherits from our "code-behind" class. This class is where some of the magic happens. When we create a user control outside the web application where the user control is being used the afore-mentioned classes don't exist. So how do we cope with this? We'll create a base class for all our user controls and we inject some magic in it as well! This base class will be responsible for:<br />
- manually loading the ascx file and parse it to dynamically create the elements/controls present in the ascx.<br />
- "binding" these elements/controls to the members that represent them in the code-behind class (this members are usually present in the designer file)<br />
Here's the code to such a base class: <br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
/// <summary>
/// Base class to all user controls in this assembly. Knows how to load the ascx files and how to bootstrap user controls
/// </summary>
public abstract class BaseUserControl : UserControl
{
/// <summary>
/// Initializes the control that is derived from the <see cref="T:System.Web.UI.TemplateControl"/> class.
/// </summary>
protected override void FrameworkInitialize()
{
base.FrameworkInitialize();
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetType(), GetType().Name + ".ascx");
if (stream == null) return;
string content;
using (var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
var userControl = Page.ParseControl(content);
if (userControl != null)
{
this.Controls.Add(userControl);
FindControls(this.GetType(), this.Controls);
}
}
/// <summary>
/// Finds controls defined in the ascx and binds them to the control definitions in the code behind.
/// </summary>
/// <param name="userControlType">
Type of the user control.</param>
/// <param name="controlCollection">
The control collection.</param>
private void FindControls(Type userControlType, ControlCollection controlCollection)
{
foreach (Control childCtrl in controlCollection)
{
var controlId = childCtrl.ID;
var controlType = childCtrl.GetType();
if (!string.IsNullOrEmpty(controlId))
{
var controlField = userControlType.GetField(controlId, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (controlField != null && controlField.FieldType.Equals(controlType))
controlField.SetValue(this, FindControl(controlId));
}
if (childCtrl.HasControls())
FindControls(userControlType, childCtrl.Controls);
}
}
}
]]>
</script><br />
<br />
And here's the rest of my recipe:<br />
<br />
1- Create new asp.net web application project. This makes sure we can create new user controls directly through the "new item" dialog, which would not be possible if we were to create a regular class library project.<br />
1.1- Clear all the files that visual studio placed inside the new project (leave only the AssemblyInfo.cs)<br />
<br />
2- Creating user controls in your new project<br />
2.1 - Add a new "Web User Control" item to your project<br />
2.2 - Design your control as you always do<br />
2.3 - Open the designer files and copy the declaration of controls you'll want to access later on to the code-behind class. (You can also keep the designer files as partial classes to your code-behind class, but there's not much point in it as visual studio won't be able to update it later on)<br />
2.4 - Delete the designer files (unless you've decided to keep it as a partial class)<br />
2.5 - The control header (in the ascx file) should be cleaned to keep only the Language attribute, thus leaving only the following header:<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
<%@ Control Language="C#"%>
]]>
</script><br />
2.6 - Change the ascx file build action from "Content" to "Embedded Resource"<br />
2.7 - Change the control base class from "UserControl" to our own "BaseUserControl"<br />
<br />
3- Using the user controls in your web application<br />
3.1 - Reference the new project in our old web application<br />
3.2 - Change the web.config to avoid registering the control in every page you'll use it:<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
<system.web>
<pages>
<controls>
<add assembly="AssemblyNameGoesHere" namespace="ControlNamespaceGoesHere" tagprefix="uc"></add>
</controls>
</pages>
</system.web>
]]>
</script><br />
<br />
Alternatively you could register the control in in the pages you want to use it by adding the following line:<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
<%@ Register Assembly="AssemblyNameGoesHere" Namespace="ControlNamespaceGoesHere" TagPrefix="uc" %>
]]>
</script><br />
<br />
And we're done! Here's a list of the issues found with this solution (so far):<br />
- Couldn't get the control skins to work with my user controls<br />
- Local and Global Resources are currently in the web application (instead of being properly encapsulated in the user controls that uses them), as asp.net loads them from the page, not the user control. There are at least two workarounds for this. We could create a resource provider and resolve the resources manually or we could use resources like we do in a regular winforms application, instead of using the local/global resources asp.net approach.<br />
<br />
That's all folks!Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-82615034950483654702011-06-23T15:44:00.001+01:002011-06-23T15:45:57.639+01:00Testing emails with neptuneMost of us have already developed some feature that sends emails, and when we finish the development phase we need to test it, but how? Surely we can force the application to send a mail to ourselves, but sometimes we don’t even have an available smtp server to use, or it requires further development steps to enable it with some authentication mechanism.<br />
An alternative is to use a lightweight local smtp server focused on this development needs. So today I’ll show you how to use Neptune (There is another product with similar features, which I’ve never used, so feel free to explore it as an alternative to Neptune. It’s called SMTP4Dev and you can find it at smtp4dev.codeplex.com).<br />
The latest Neptune version (downloadable at http://donovanbrown.com/post/Neptune-with-POP3.aspx) even supplies a POP port so that you can easily check the emails you sent, instead of only acknowledging that an email was successfully sent.<br />
Neptune runs in the windows tray. With a right click on it’s icon you access a context menu which allows you to stop the smtp server and access a window showing further details as the smtp/pop ports and the number of email messages processed.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/-vEfckjeUJ9g/TgNQviu2-BI/AAAAAAAABDs/Gry_wrrZ_a4/s1600/tray1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-vEfckjeUJ9g/TgNQviu2-BI/AAAAAAAABDs/Gry_wrrZ_a4/s1600/tray1.png" /></a><a href="http://4.bp.blogspot.com/-3kP_RJJAL_E/TgNQvgQ8jPI/AAAAAAAABD0/twK2fLYcgGM/s1600/tray2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-3kP_RJJAL_E/TgNQvgQ8jPI/AAAAAAAABD0/twK2fLYcgGM/s1600/tray2.png" /></a></div><br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-sC9o6BdVy0o/TgNQv0KUOnI/AAAAAAAABD8/1m5KSR8PCpw/s1600/statusWindow.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-sC9o6BdVy0o/TgNQv0KUOnI/AAAAAAAABD8/1m5KSR8PCpw/s1600/statusWindow.png" /></a></div><br />
<br />
As mentioned earlier, you can easily set up an email account on your outlook (or another email client) to use the pop server supplied by neptune to take a look at the emails sent from your application. Most of the account details (as the username, password and email address) are dummy and make no difference for the pop server. You just have to specify that the mail server is 127.0.0.1.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/-TQD5qZWhuzY/TgNQwcTvdxI/AAAAAAAABEE/pp2rtu2cEZ4/s1600/accountSettingsWindow.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="445" src="http://2.bp.blogspot.com/-TQD5qZWhuzY/TgNQwcTvdxI/AAAAAAAABEE/pp2rtu2cEZ4/s640/accountSettingsWindow.png" width="640" /></a></div><br />
If you’re interested in unit testing your emails, Neptune also supplies some extensibility mechanisms for that purpose.Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-36984868828373101712011-02-25T15:51:00.001+00:002011-02-25T15:53:00.938+00:00Using Keyboard Hooks in .NETHere's another code snippet. This one shows you how to use keyboard hooks in .NET.<br />
I took hints from a few online articles about this subject and stumbled upon an issue that arises when you try to use hooks in .NET 4.0. Typically when you invoke the SetWindowsHookEx, you supply it with the instance of the current module. In most articles you'll find that this can be done with the following line:<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
]]>
</script><br />
However this does not work in .NET 4. For further information see <a href="http://social.msdn.microsoft.com/Forums/en/clr/thread/046dd828-2920-4bec-aaa9-e24aef48c761">this discussion</a> and <a href="http://social.msdn.microsoft.com/Forums/en/vbgeneral/thread/9bb5e76d-e9a3-4264-a9e9-842e6ff5ac32">this one as well</a>. As stated in the later, an alternative way of doing this so that it works in .NET 4 (as well as in the older framework versions) is:<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
Process.GetCurrentProcess().MainModule.BaseAddress;
]]>
</script><br />
<br />
<span class="Apple-style-span" style="color: #333333; font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 16px;"><br />
</span><br />
<span class="Apple-style-span" style="color: #333333; font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 16px;">Here's the code snippet for my HookManager class:</span><br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
internal static class HookManager
{
/// <summary>
/// Info about a low-level keyboard input event.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/en-us/library/ms644967(v=VS.85).aspx
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private struct KeyboardHookStruct
{
/// <summary>
/// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public byte VirtualKeyCode;
/// <summary>
/// Specifies a hardware scan code for the key.
/// </summary>
public int ScanCode;
/// <summary>
/// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
/// </summary>
public int Flags;
/// <summary>
/// Specifies the Time stamp for this message.
/// </summary>
public int Time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int ExtraInfo;
}
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events.
/// </summary>
private const int WH_KEYBOARD_LL = 13;
/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
/// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
/// </summary>
private const int WM_KEYDOWN = 0x100;
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
/// presses another key. It also occurs when no window currently has the keyboard focus;
/// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYDOWN = 0x104;
/// <summary>
/// Stores the handle to the Keyboard hook procedure.
/// </summary>
private static int keyboardHookHandle;
/// <summary>
/// This field is not objectively needed but we need to keep a reference on a delegate which will be
/// passed to unmanaged code. To avoid GC to clean it up.
/// When passing delegates to unmanaged code, they must be kept alive by the managed application
/// until it is guaranteed that they will never be called.
/// </summary>
private static HookProc keyboardDelegate;
/// <summary>
/// Custom action that allows customization of the hook behavior
/// </summary>
private static Action<string, Keys> customAction;
/// <summary>
/// Delegate that represents the Hook
/// </summary>
public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
#region P/Invokes
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
#endregion
/// <summary>
/// Stops the monitoring by removing the hook
/// </summary>
/// <returns></returns>
public static bool StopMonitoring()
{
bool result = UnhookWindowsHookEx(keyboardHookHandle);
keyboardHookHandle = 0;
keyboardDelegate = null;
if (!result)
return false;
return true;
}
/// <summary>
/// Starts monitoring the keyboard keys. Sets the hook
/// </summary>
/// <param name="keyboardCustomAction">
The action that will act upon a pressed key.</param>/// <returns>
/// <c>true</c>if the hook was successfuly set, <c>false</c> otherwise
/// </returns>
public static bool StartMonitoring(Action<string, Keys> keyboardCustomAction)
{
if (keyboardCustomAction == null)
throw new ArgumentNullException();
keyboardDelegate = KeyboardHookProc;
// using the current process mainmodule address resolves issues with .NET 4
IntPtr instance = Process.GetCurrentProcess().MainModule.BaseAddress;
keyboardHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, keyboardDelegate, instance, 0);
customAction = keyboardCustomAction;
if (keyboardHookHandle == 0)
return false;
return true;
}
/// <summary>
/// Hook implemenation
/// </summary>
private static int KeyboardHookProc(int nCode, int wParam, IntPtr lParam)
{
if (nCode >= 0)
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct keyboardHookData = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
{
string text = Encoding.Default.GetString(new byte[] { keyboardHookData.VirtualKeyCode });
// invoke custom action that acts upon the gathered keys
if (customAction != null)
customAction(text, (Keys)keyboardHookData.VirtualKeyCode);
}
}
else
return CallNextHookEx(keyboardHookHandle, nCode, wParam, lParam);
//if event handled in application do not handoff to other listeners
return -1;
}
}
]]>
</script><br />
<span class="Apple-style-span" style="color: #333333; font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 16px;"><br />
</span><br />
<span class="Apple-style-span" style="color: #333333; font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 16px;">And an usage example:</span><br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
var keyHandler = new Action<string, Keys>( (text, keyInfo) => {
//backspace
if (keyInfo == Keys.Back)
ProcessBackspace();
else if (keyInfo == Keys.Enter || keyInfo == Keys.Return)
ProcessEnter();
else if (!string.IsNullOrEmpty(text)) // regular text key
ProcessText(text);
});
HookManager.StartMonitoring(keyHandler);
// do something while you're monitoring the keyboard events
HookManager.StopMonitoring();
]]>
</script>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-65537861775772374652011-02-18T09:33:00.002+00:002011-02-24T09:23:37.708+00:00Brand new Reflector alternativesSo, now that our loved free .NET Reflector is about to run out of juice, what alternatives do we have. I've said before that I'm willing to pay for it, but there are many of you out there who are just too much pissed off at Redgate to buy anything from them! <br />
Whose about to step in and take away some of Redgate's future clients? Jetbrains! Yes, the same ones that develop another much loved tool: ReSharper. They're introducing decompiling capabilities in their tool and also promising to release the decompiler as a free standalone tool by the end of the year! Check it out here: http://blogs.jetbrains.com/dotnet/<br />
That got me thinking if it's finally time to buy ReSharper! What about you?<br />
<br />
Also, there's another free tool on the horizon: <a href="http://wiki.sharpdevelop.net/ilspy.ashx">ILSpy</a><br />
<br />
<b>Edit (24/02/2011)</b>: It seems another alternative is about to rise on the horizon! If you look at the <a href="http://blogs.telerik.com/blogs/posts/11-02-21/q1_11_pre-release_series_decompiling_code-cleaner_and_code_style-sharing_coming_to_justcode.aspx">Telerik's JustCode pre-release blog post</a> (where they provide a special preview of the release highlights for their Q1'2011 release) you can read the following paragraph:<br />
<blockquote>The new decompiling functionality will enable you to recover lost source code and allow you to explore and analyze compiled .NET assemblies. We know a lot of you will welcome this addition as it comes in response to your feedback and recent developments in the industry.</blockquote>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-13817866049824726532011-02-16T11:46:00.000+00:002011-02-16T11:46:40.331+00:00Test INotifyPropertyChanged Pattern implementations<div style="font-family: arial; font-size: small;">Today, I'll cover a well known topic: different implementations of the INotifyPropertyChanged interface (henceforth referred to as INPC). Its most common use is when you're implementing the MVVM pattern. This interface makes sure that your viewmodel properties update the binded interface components when you change the property value. So, with so many WPF and silverlight applications out there, it's a well known interface and you probably also know that it's regular implementation is somewhat boring and extensively verbose! That's why there are so many different alternatives out there. I decided to collect a few and test them for performance.</div><div style="font-family: arial; font-size: small;">The main motivation was to validate the suspected performance penalty of implementations based on expression trees. So I'm pitting this kind of implementation against the most common and basic implementation, two AOP (see <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">http://en.wikipedia.org/wiki/Aspect-oriented_programming</a>) implementations (one using IL weaving and another using a dynamic proxy) and the usage of dependency properties. Dependency properties may seem a little out of place, but they are one of the common alternatives to using the INotifyPropertyChanged.</div><div style="font-family: arial; font-size: small;"><br />
</div><div style="font-family: arial; font-size: small;">The main reasons to research for different INPC implementations (the aforementioned boringness and verbosity) should obviously be taken into account. Most developers don't like that they can't use the simpler syntax of automatic properties if the want to use INPC.</div><div style="font-family: arial; font-size: small;">It's not my objective to discuss the advantages and disadvantages of each, as you can find easily find several articles that delve deep into that subject. However, there are a few points we should keep in mind when choosing the kind of implementation to use. </div><div style="font-family: arial; font-size: small;">A perfectly good example are the disadvantages of using dependency properties: the need of inheriting from DependencyObject and the fact that these properties can't be changed from non-UI dispatcher threads. These may be two show-stoppers depending on your situation. The first also applies to the usage of expression trees. If your viewmodels are depending on some kind of ViewModelBase class then, that's not much of a fuss, but if you wish to achieve some kind of Naked MVVM implementation (see <a href="http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx">http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx</a>) than you can't rely on a base class. Anyway, if you can avoid it, there's no need to burn your base class (see http://www.artima.com/intv/dotnet.html). </div><br />
<div style="font-family: arial; font-size: small;">On the other hand, most AOP approaches only make sense if you're using an IOC container to resolve your viewmodels. This is due to the fact that you can't instantiate your viewmodel class directly, you'll need to call a method that creates a proxy (where the INPC is injected) for your viewmodel. One of the AOP approaches (the one using PostSharp) we're using here avoids this by injecting the INPC in your class in a post-build action through IL weaving (see <a href="http://www.sharpcrafters.com/aop.net/msil-injection">http://www.sharpcrafters.com/aop.net/msil-injection</a>).</div><br />
<b><u>The Test</u></b><br />
<br />
<div style="font-family: arial; font-size: small;">The test is pretty simple. Each of the implementations resides in a separate class which has the integer property (conveniently named "Property") we'll be using in the test. This property will be assigned 200.000 times in a cycle and we'll be controlling the time it takes for this cycle to complete. We'll also make sure that the PropertyChanged event is handled by an event handler that does absolutely nothing (we just want to measure the event handler invocation time, not the time the event handler takes to execute, so we're making it as simple as possible).</div><br />
<div style="font-family: arial; font-size: small;">Example source for a specific test:</div><script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
var postsharpTest = new PostSharpAOPTest();
EventInfo postSharpPropertyChangedEvent = typeof(PostSharpAOPTest).GetEvent("PropertyChanged");
MethodInfo postSharpNopHandlerMethod = typeof(MainPageViewModel).GetMethod("NopPropertyChangedEventHandler");
Delegate postSharpHandler = Delegate.CreateDelegate(typeof(PropertyChangedEventHandler), null, postSharpNopHandlerMethod);
postSharpPropertyChangedEvent.AddEventHandler(postsharpTest, postSharpHandler);
timeStart = Environment.TickCount;
for (int i = 0; i < iterations; i++)
postsharpTest.Property = i;
timeEnd = Environment.TickCount;
int postsharpPropTimeDiff = timeEnd - timeStart;
PostSharpTime = postsharpPropTimeDiff;
postSharpPropertyChangedEvent.RemoveEventHandler(postsharpTest, postSharpHandler);
]]>
</script><br />
<br />
<div style="font-family: arial; font-size: small;">I've shown the example of the PostSharp implementation because the AOP test implementations require you to add the event handler through reflection, as the event doesn't exist at compile time. That's the only difference from the non-AOP implementations. Notice that you won't need to do this in real-life applications because you won't be registering explicitly the PropertyChanged event, that's the job of the framework's binding mechanism.<br />
Also note that in the Castle Dynamic Proxy implementation, the instantiation of the test class would be replaced by a call to create the proxy (which, as stated above, would not be visible if we were using an IOC container to resolve the class)<br />
Example:</div><script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
var castleTest = DataBindingFactory.Create<CastleDynamicProxyTest>();
]]>
</script><br />
<br />
<b><u>Test Results</u></b><br />
<br />
<div class="separator" style="clear: both; font-family: arial; font-size: small; text-align: center;"><a href="http://3.bp.blogspot.com/-bmS67DSTS9A/TVupzZfKn5I/AAAAAAAABC0/c5LLDz5RQZ4/s1600/graph.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="378" src="http://3.bp.blogspot.com/-bmS67DSTS9A/TVupzZfKn5I/AAAAAAAABC0/c5LLDz5RQZ4/s640/graph.png" width="640" /></a></div><br />
<b><u>Implementations</u></b><br />
<div style="font-family: arial; font-size: small;">Here's the code to the implementations used in the test, which by the way, I'm not claiming ownership for, I've just gathered and altered them slightly where needed.</div><div style="font-family: arial; font-size: small;">Common INPC implementation (which I'm calling the "Plain old" way)</div><br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
public class PlainOldTest : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _propValue = 0;
public int Property
{
get { return _propValue; }
set
{
if (_propValue != value)
{
_propValue = value;
NotifyPropertyChanged("Property");
}
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
]]>
</script><br />
<br />
<div style="font-family: arial; font-size: small;">Expression Trees implementation</div><script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
public class ExpressionTreeTest : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _propertyValue;
public int Property
{
get { return _propertyValue; }
set {
if (_propertyValue != value)
{
_propertyValue = value;
NotifyPropertyChanged(() => Property);
}
}
}
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyExpression">
The property expression.</param>private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
protected void NotifyPropertyChanged<t>(Expression<Func<t>> property)
{
if (PropertyChanged != null)
{
var memberExpression = property.Body as MemberExpression;
PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
}
}
}
]]>
</script><br />
<div style="font-family: arial; font-size: small;">Dependency Properties implementation</div><script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
public class DependencyPropTest : DependencyObject
{
public int Property
{
get { return (int)GetValue(DependencyPropProperty); }
set { SetValue(DependencyPropProperty, value); }
}
public static readonly DependencyProperty DependencyPropProperty =
DependencyProperty.Register("Property", typeof(int), typeof(DependencyPropTest), new PropertyMetadata(0, PropertyChanged));
private static void PropertyChanged(object sender, DependencyPropertyChangedEventArgs args)
{
;
}
}]]>
</script><br />
<div style="font-family: arial; font-size: small;">PostSharp AOP implementation</div><script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
[PostSharpNotifyPropertyChangedAttribute]
public class PostSharpAOPTest
{
public int Property { get; set; }
}
[IntroduceInterface( typeof(INotifyPropertyChanged), OverrideAction = InterfaceOverrideAction.Ignore )]
[MulticastAttributeUsage( MulticastTargets.Class, Inheritance = MulticastInheritance.Strict )]
public sealed class PostSharpNotifyPropertyChangedAttribute : InstanceLevelAspect, INotifyPropertyChanged
{
[ImportMember( "OnPropertyChanged", IsRequired = false, Order = ImportMemberOrder.AfterIntroductions)]
public Action<string> OnPropertyChangedMethod;
[IntroduceMember( Visibility = Visibility.Family, IsVirtual = true, OverrideAction = MemberOverrideAction.Ignore )]
public void OnPropertyChanged( string propertyName )
{
if ( this.PropertyChanged != null )
{
this.PropertyChanged( this.Instance, new PropertyChangedEventArgs( propertyName ) );
}
}
[IntroduceMember( OverrideAction = MemberOverrideAction.Ignore )]
public event PropertyChangedEventHandler PropertyChanged;
[OnLocationSetValueAdvice, MulticastPointcut( Targets = MulticastTargets.Property, Attributes = MulticastAttributes.Instance | MulticastAttributes.NonAbstract)]
public void OnPropertySet( LocationInterceptionArgs args )
{
// Don't go further if the new value is equal to the old one.
// (Possibly use object.Equals here).
if ( args.Value == args.GetCurrentValue() ) return;
// Actually sets the value.
args.ProceedSetValue();
this.OnPropertyChangedMethod.Invoke( args.Location.Name );
}
}
]]>
</script><br />
<div style="font-family: arial; font-size: small;">Castle Dynamic Proxy AOP implementation</div><br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
public class CastleDynamicProxyTest
{
public virtual int Property { get; set; }
}
public static class DataBindingFactory
{
private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator();
public static T Create<t>()
{
return (T)Create(typeof(T));
}
public static object Create(Type type)
{
return ProxyGenerator.CreateClassProxy(type,
new[] { typeof (INotifyPropertyChanged), typeof (IMarkerInterface) },
new NotifyPropertyChangedInterceptor(type.FullName));
}
public interface IMarkerInterface
{
string TypeName { get; }
}
public class NotifyPropertyChangedInterceptor : IInterceptor
{
private readonly string typeName;
private PropertyChangedEventHandler subscribers = delegate { };
public NotifyPropertyChangedInterceptor(string typeName)
{
this.typeName = typeName;
}
public void Intercept(IInvocation invocation)
{
if (invocation.Method.DeclaringType == typeof(IMarkerInterface))
{
invocation.ReturnValue = typeName;
return;
}
if (invocation.Method.DeclaringType == typeof(INotifyPropertyChanged))
{
var propertyChangedEventHandler = (PropertyChangedEventHandler)invocation.Arguments[0];
if (invocation.Method.Name.StartsWith("add_"))
{
subscribers += propertyChangedEventHandler;
}
else
{
subscribers -= propertyChangedEventHandler;
}
return;
}
invocation.Proceed();
if (invocation.Method.Name.StartsWith("set_"))
{
var propertyName = invocation.Method.Name.Substring(4);
subscribers(invocation.InvocationTarget, new PropertyChangedEventArgs(propertyName));
}
}
}
}
]]>
</script><br />
<br />
<b><u>Conclusions</u></b><br />
<div style="font-family: arial; font-size: small;">After this, I think it's safe to conclude that the Expression trees implementation implies a severe performance penalty and although it's far simpler than the "Plain old" way of doing it, it still loses in simplicity when compared to the AOP implementations. That said, I should say that I've always been a fan of PostSharp and I currently consider it to be the best way of implementing INPC, although it is a payed tool.</div>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com1tag:blogger.com,1999:blog-10053161.post-78459009107083926362011-02-04T00:09:00.003+00:002011-02-04T00:13:53.407+00:00RIP .NET Reflector (as a free version)If you still haven't heard about it, here's a bad news: Redgate is about to put an end on the .NET reflector's free version as soon as they release the new version (which will be .NET Reflector 7). This new version seems to be scheduled for late february/early march. Knowing that the free version will only work until May 30, you'll soon have to make a decision: either buy it or stop using it. <span class="Apple-style-span" style="font-size: xx-small;">Well, I guess you could maintain a virtual machine with a freezed date and no internet conectivity at all to avoid connections with redgate servers, but where's the praticality in that?</span><br />
<span class="Apple-style-span" style="font-size: xx-small;"><br />
</span><br />
I've made my decision, it's an easy decision, 35$ is not that much for one of the most important tools I use on a daily basis! Otherwise, I would have to make ildasm my new best friend!<br />
As a developer I understand the importance of getting payed for what you develop and that the comporate side demands return on investment upon the new features being developed. Don't get me wrong, I do like the idea of open source, I just don't think we can apply it everywhere. The fact that the .NET community isn't taking this decision very well isn't much of a surprise for me. We all had the expectation that we'ld never have to pay for it, you may even state that we Redgate led us to believe that, that's what's the fuss is all about!<br />
At the end of the day, what really matters is that we're talking about a fanstastic product that deserves the investment. Also, Redgate states that "Version 7 will be sold as a perpetual license, with no time bomb or forced updates", so that's definitely worth the value. I may even consider buying the pro edition...<br />
<br />
What worries me is knowing that there a few companies that will not buy it for their developers! Let's just hope my company buys the necessary licenses asap, so I'm not forced to use my personal license at work!Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com3tag:blogger.com,1999:blog-10053161.post-90951514041017137832011-01-19T00:41:00.000+00:002011-01-19T00:41:00.229+00:00Stack WalkingHave you ever needed to determine who's calling your methods or merely needed to inspect the call stack?<br />
<br />
There's a fairly simple way of doing it by using the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx">StackTrace</a> class. I'll show you an usage example.<br />
First, let's start by creating a small class that creates a stack of 3 method calls just so that we have some to call stack to look into.<br />
This should do it:<br />
<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
public class Class1
{
public void Method1()
{
Method2();
}
private void Method2()
{
Method3();
}
private void Method3()
{
if (ReachedDeepestStackLevel != null)
ReachedDeepestStackLevel(this, new EventArgs());
}
public event EventHandler ReachedDeepestStackLevel;
}
]]>
</script><br />
<br />
Now, let's call Method1 and hook up an event handler that will gather the stack trace and print some information about each stack frame.<br />
<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
static void Main(string[] args)
{
var testInstance = new ClassLibrary1.Class1();
testInstance.ReachedDeepestStackLevel += new EventHandler(ShowStackTrace);
testInstance.Method1();
}
static void ShowStackTrace(object sender, EventArgs e)
{
// wheter to gather information about the file, line and column
bool gatherFileInfo = true;
var stackTrace = new StackTrace(gatherFileInfo);
for (int i = 0; i < stackTrace.FrameCount; i++)
{
var frame = stackTrace.GetFrame(i);
var method = frame.GetMethod();
var module = method.Module;
var assembly = module.Assembly;
Console.WriteLine("Stack Frame {0}", i);
Console.WriteLine("Method: {0}", method.Name);
Console.WriteLine("Type: {0}", method.DeclaringType.FullName);
Console.WriteLine("Assembly: {0}", assembly.GetName().Name);
Console.WriteLine(string.Empty);
}
}
]]>
</script><br />
You should pay special attention to the boolean parameter of the StackTrace constructor. It defines if file information should be gathered (the file, line and column of the method being called). As we'll see below, gathering this information incurs in a performance penalty! Also, these values will likely be absent from a release build, as it is built without debug symbols.<br />
<br />
You may be wondering about the performance of such a feature. I've made some testing and got back the values below. Note that these tests are merely indicative. My laptop had dozens of applications running that could interfere with the processor availability. Anyway, each value from the results below is the best out of three attempts and the average values for a single execution are consistent. Also, for the testing purposes, the Console.WriteLine instructions were removed.<br />
These tests were made using a Debug version of the application.<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TTYw7jtfmCI/AAAAAAAABCg/lemjN4Ni0Yc/s1600/graph1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TTYw7jtfmCI/AAAAAAAABCg/lemjN4Ni0Yc/s1600/graph1.jpg" /></a></div>The graph above shows the time it takes to run several executions of the ShowStackTrace method. The same tests were made with and without gathering file information. As you can see, there is a substantial difference.<br />
The graph below shows the average time of a single execution.<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TTYw8UyU9LI/AAAAAAAABCo/0iBTiYrCqbA/s1600/graph2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TTYw8UyU9LI/AAAAAAAABCo/0iBTiYrCqbA/s1600/graph2.jpg" /></a></div>As you can see, a single run, without file information takes in average 0.05 milliseconds! On a debug build! That seems pretty darn fast. It might be interesting to point out that this is the same way that exceptions gather their stack trace.<br />
<br />
I wonder how this times stack up against the times achieved in a stack walk using the dbghelp.dll library. Maybe on a future blog post...Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-33163126922633344062010-12-10T10:58:00.002+00:002010-12-10T11:01:10.462+00:00.NET Encryption - Part 3Now, for the third and last part of this series (first and second parts can be found <a href="http://geeklyeverafter.blogspot.com/2010/11/net-encryption-part-1.html">here</a> and <a href="http://geeklyeverafter.blogspot.com/2010/12/net-encryption-part-2.html">here</a>) about encryption. I've promised before that I would supply example source code for previously mentioned encryption operations. That's what this post is all about. The source below shows how to perform each of these operations with a handful of source code lines. The only thing covered here that I haven't mentioned before is how to derive algorithm keys (which are arrays of bytes) from a string, typically a password or a pass-phrase. That's covered in the first few lines and you should pay special attention to it, because it is something you'll need plenty of times.<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
var password = "sample password";
var salt = "sample salt";
var dataToEncrypt = "my sample data";
#region Algorithms setup / Derive key and IV from a password and a salt
var deriveBytes = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt));
SymmetricAlgorithm symAlgorithm = new RijndaelManaged(); // pick your favorite symmetric algorithm implementation
symAlgorithm = new RijndaelManaged();
symAlgorithm.Key = deriveBytes.GetBytes(symAlgorithm.KeySize / 8);
symAlgorithm.IV = deriveBytes.GetBytes(symAlgorithm.BlockSize / 8);
var persistentCspParams = new CspParameters() { KeyContainerName = "MyApplicationKeyContainer" };
var asymAlgorithm = new RSACryptoServiceProvider(persistentCspParams);
asymAlgorithm.PersistKeyInCsp = true;
// instead of using a persistent key container, you could load the rsa keys from an xml
// asymAlgorithm.FromXmlString(rsaXmlLoadedFromFile);
// remember that if you don't persist the RSA keys you'll never be
// able to decrypt a message created with it's public key
#endregion
#region Symmetric encryption
MemoryStream msEncrypt = new MemoryStream();
string encryptedData;
using (var cryptoStream = new CryptoStream(msEncrypt, symAlgorithm.CreateEncryptor(), CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cryptoStream))
writer.Write(dataToEncrypt);
encryptedData = Convert.ToBase64String(msEncrypt.ToArray());
}
Console.WriteLine("Encrypted data: {0}", encryptedData);
#endregion
#region Symmetric Decryption
string dataToDecrypt = encryptedData;
MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(dataToDecrypt));
string decryptedData;
using (var cryptoStream = new CryptoStream(msDecrypt, symAlgorithm.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cryptoStream))
decryptedData = reader.ReadToEnd();
}
Console.WriteLine("Decrypted data: {0}", decryptedData);
#endregion
#region Asymmetric encryption
var dataByteArray = Encoding.UTF8.GetBytes(dataToEncrypt);
var encryptedDataByteArray = asymAlgorithm.Encrypt(dataByteArray, true);
encryptedData = Convert.ToBase64String(encryptedDataByteArray);
Console.WriteLine("Asymmetric encrypted data: {0}", encryptedData);
#endregion
#region Asymmetric decryption
var dataToDecryptByteArray = Convert.FromBase64String(encryptedData);
var decryptedDataByteArray = asymAlgorithm.Decrypt(dataToDecryptByteArray, true);
decryptedData = Encoding.UTF8.GetString(decryptedDataByteArray);
Console.WriteLine("Asymmetric decrypted data: {0}", decryptedData);
#endregion
#region Non-Keyed Hashing of the encrypted data
HashAlgorithm hashAlgorithm = new SHA512CryptoServiceProvider();
//HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
//HashAlgorithm hashAlgorithm = new SHA1Managed();
//HashAlgorithm hashAlgorithm = new SHA1Cng();
hashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(encryptedData));
var encryptedDataHash = Convert.ToBase64String(hashAlgorithm.Hash);
Console.WriteLine("Encrypted data non-keyed Hash: {0}", encryptedDataHash);
#endregion
#region Keyed Hashing of the encrypted data
KeyedHashAlgorithm keyedHashAlgorithm = new HMACSHA512();
// using the same key as the one used for the symmetric algorithm. A different one should/could be used
keyedHashAlgorithm.Key = symAlgorithm.Key;
keyedHashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(encryptedData));
encryptedDataHash = Convert.ToBase64String(keyedHashAlgorithm.Hash);
Console.WriteLine("Encrypted data keyed Hash: {0}", encryptedDataHash);
#endregion
]]>
</script><br />
<br />
Hope you've enjoyed this cryptography sessions.Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-34780519207814917702010-12-08T22:01:00.000+00:002010-12-08T22:01:19.884+00:00Software Building vs Software Maintenance<table><tbody>
<tr> <td><br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=geeeveaft-20&o=1&p=8&l=bpl&asins=0201835959&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe></td> <td><br />
I've been reading "The Mythical Man-Month" in the last few days and I'ld like to highlight here a particular paragraph:<br />
<blockquote>Systems program building is an entropy-decreasing process, hence inherently metastable. Program maintenance is an entroypy-increasing process, and even its most skillful execution only delays the subsidence of the system into unfixable obsolescence. </blockquote>So, for all of us working on program maintenance this means that even if from times to times we introduce new features into the system, we should keep in mind that someday (maybe not so far into the future as we would like to believe) the system we're working on will be deamed obsolete and eventually replaced! Isn't it so much better to design and implement brand new systems? Maybe that's why we're so eager to refactor existing sub-systems and sometimes even throw them way and build them from scratch...<br />
<br />
By the way, this is one of those books that should be regarded as a "must-read" for all software engineers/architects!</td> </tr>
</tbody></table>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-60861632462810176802010-12-01T21:59:00.001+00:002010-12-02T07:37:02.710+00:00.NET Encryption - Part 2<div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div>In the <a href="http://geeklyeverafter.blogspot.com/2010/11/net-encryption-part-1.html">first article of this series</a> I’ve briefly covered some topics about .NET encryption. Now that we’ve all remembered how encryption works, let’s move onwards to the real deal.<br />
Let’s start by seeing what .NET provides us with. In the table below I’ve grouped every algorithm (please let me know if I’ve missing any!) and categorized them by purpose (symmetric encryption, asymmetric encryption, non-keyed hashing and keyed hashing) and implementation. <br />
There are three kinds of implementations: <br />
<ul><li>Managed: pure .NET implementations</li>
</ul><ul><li>CryptoServiceProvider: managed wrappers to the Microsoft Crypto API native code implementations </li>
</ul><ul><li>CNG: managed wrappers to the Next Generation Cryptography API designed to replace the previously mentioned CryptoAPI (also known as CAPI)</li>
</ul><br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/_d0-GJfBcpv0/TPbDnIRjggI/AAAAAAAABCU/VLrTltaPXqg/s1600/encryptionTable.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/_d0-GJfBcpv0/TPbDnIRjggI/AAAAAAAABCU/VLrTltaPXqg/s1600/encryptionTable.png" /></a></div><br />
In the table above, I’ve highlighted in red a few classes which were only introduced in .NET 3.5. However these new classes (except AesManaged) can only be used on Windows Vista and later operating systems. This is due to the fact that the CNG API was first released along with Windows Vista. <br />
Please note that .NET framework supports only a few of the CNG features. If you wish to use CNG more extensively in .NET you may be interested in delving into the <a href="http://clrsecurity.codeplex.com/">CLR Security Library</a>.<br />
<br />
So, the first big question is: with so many flavors what should we choose? Of course there’s no absolute and definitive response, there are too many factors involved, but we can start by pointing some of the pros and cons of each kind of implementation.<br />
<b>CNG</b>: It has the downside of only running on the latest Operating Systems; On the upside it is the newer API (you should face CAPI as the deprecated API), it’s FIPS-Certified and it’s native code (hence likely to be faster than the Managed implementation).<br />
<b>Managed</b>: It has the downside of not being FIPS-Certified and likely to be slower than the native implementations; On the upside this approach has increased portability has it works across all platforms (and apart from AesManaged you don’t even need the latest .NET version) <br />
<b>CSP</b>: CryptoServiceProviders supply you a bunch of FIPS-Certified algorithms and even allows you to use cryptography hardware devices. Note that .NET support for Crypto Service Providers is a wrapper for the CAPI features and doesn’t all of CAPI features.<br />
<br />
You may ask “What’s FIPS-Certified?”. FIPS (Federal Information Processing Standards) are a set of security guidelines which are demanded by several federal institutions and governments. Your system<a href="http://blogs.msdn.com/b/shawnfa/archive/2005/05/16/417975.aspx?PageIndex=2"> can be configured to allow only the use of FIPS-Certified algorithms</a>. When faced with such a requirement, using a non FIPS-Certified algorithm is considered the same as using no encryption at all!<br />
<br />
So, now that you know how to choose among the different kinds of implementations, another (perhaps more relevant and important) question, is how to choose the algorithm to use. It mostly depends upon the encryption strategy you are using. <br />
<ul><li>For a symmetric algorithm, Rijndael is mostly recommended. AES is no more than a Rijndael implementation with fixed block and key sizes.</li>
</ul><ul><li>For asymmetric algorithms, RSA is the common option.</li>
</ul><ul><li>For hashing purposes, SHA2 algorithms (SHA256, SHA384, SHA512) are recommended. MD5 is considered to have several flaws and is considered insecure. SHA1 has also been recently considered insecure.</li>
</ul>That's all for these blog post. In the next part of the series I'll show you source code examples and maybe delve into a few common scenarios and necessities.Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-11885006388699369402010-11-16T01:17:00.001+00:002010-11-16T01:19:11.474+00:00.NET Encryption - Part 1<div style="font-family: Arial,Helvetica,sans-serif;">In this series, I’ll target .NET encryption. These will be a series of articles to avoid extensive blog posts.</div><div style="font-family: Arial,Helvetica,sans-serif;">I want to make a kind of a personal bookmark for whenever I need to use it. Heck, that’s one of the reasons most of us keep technical blogs, right?</div><div style="font-family: Arial,Helvetica,sans-serif;">Encryption is one of those things we don’t tend to use on a daily basis, so it’s nice to have this kind of info stored somewhere to help our memory!</div><div style="font-family: Arial,Helvetica,sans-serif;"><br />
</div><div style="font-family: Arial,Helvetica,sans-serif;">In this Part 1, let’s start by remembering a few concepts:</div><div style="font-family: Arial,Helvetica,sans-serif;"><br />
</div><div style="font-family: Arial,Helvetica,sans-serif;"><b>Symmetric encryption</b></div><div style="font-family: Arial,Helvetica,sans-serif;">In this method, a single key is used to encrypt and decrypt data, hence, both the sender and the receiver need to use the exact same key.</div><div class="separator" style="clear: both; font-family: Arial,Helvetica,sans-serif; text-align: center;"></div><div class="separator" style="clear: both; font-family: Arial,Helvetica,sans-serif; text-align: center;"></div><div class="separator" style="clear: both; font-family: Arial,Helvetica,sans-serif; text-align: center;"><a href="http://1.bp.blogspot.com/_d0-GJfBcpv0/TOHSHn2TBtI/AAAAAAAABCQ/oqbXo2RiACg/s1600/symmetric.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="132" src="http://1.bp.blogspot.com/_d0-GJfBcpv0/TOHSHn2TBtI/AAAAAAAABCQ/oqbXo2RiACg/s400/symmetric.png" width="400" /></a></div><div style="font-family: Arial,Helvetica,sans-serif;">Pros:</div><ul><li style="font-family: Arial,Helvetica,sans-serif;">Faster than asymmetric encryption</li>
<li style="font-family: Arial,Helvetica,sans-serif;">Consumes less computer resources </li>
<li><span style="font-family: Arial,Helvetica,sans-serif;">Simpler to implement</span></li>
</ul><div style="font-family: Arial,Helvetica,sans-serif;">Cons:<b></b></div><ul><li><span style="font-family: Arial,Helvetica,sans-serif;">The shared key must be exchanged between both parties, that itself poses a security risk. If the <u>key exchange must not be compromised</u>!</span></li>
</ul><div style="font-family: Arial,Helvetica,sans-serif;"><br />
<b>Asymmetric encryption</b></div><div style="font-family: Arial,Helvetica,sans-serif;">This method uses two keys: the private key and the public key. The public key is publicly available for everyone who wishes to send encrypted messages. These encrypted messages can only be decrypted by the private key. This provides a scenario where everyone can send encrypted messages, but only the receiver bearing the private key is able to decrypt the received message. </div><div class="separator" style="clear: both; font-family: Arial,Helvetica,sans-serif; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TOHSGomL2wI/AAAAAAAABCI/mBkufDytwns/s1600/assymmetric.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="133" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TOHSGomL2wI/AAAAAAAABCI/mBkufDytwns/s400/assymmetric.png" width="400" /></a></div><div style="font-family: Arial,Helvetica,sans-serif;">Pros:</div><ul><li><span style="font-family: Arial,Helvetica,sans-serif;">Safer, because there’s <u>no need to exchange any secret key</u> between the parties involved in the communication</span></li>
</ul><div style="font-family: Arial,Helvetica,sans-serif;">Cons:<br />
<ul><li>Slower than symmetric encryption</li>
<li>Bad performance for large sets of data</li>
<li>Requires a Key management system to handle all saved keys</li>
</ul></div><div style="font-family: Arial,Helvetica,sans-serif;"><br />
<b>Hashing</b><br />
Safer, because Hashing isn’t encryption<i> per-se</i>, but it’s typically associated with it. Hashing is a mechanism that given an input data generates a hash value from which the origin data cannot be deduced. Typically a small change in the origin message can produce a completely different hash value. Hash values are typically used to validate that some data hasn’t been tampered with. Also when sensitive data (like a password) needs to be saved but its value is never to be read (only validated against), the hash can be saved instead of the data. <b></b><br />
<b><br />
</b></div><div style="font-family: Arial,Helvetica,sans-serif;"><div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/_d0-GJfBcpv0/TOHSHHHybHI/AAAAAAAABCM/Kdsbia4JmIo/s1600/hash.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="93" src="http://4.bp.blogspot.com/_d0-GJfBcpv0/TOHSHHHybHI/AAAAAAAABCM/Kdsbia4JmIo/s320/hash.png" width="320" /></a></div><b><br />
</b></div><div style="font-family: Arial,Helvetica,sans-serif;">That's all folks! In the next part(s) I'll cover the encryption algorithms available in .NET, how to choose among them, some real-life scenarios and source code examples.</div>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-41382827373012801022010-11-04T01:51:00.000+00:002010-11-04T01:51:51.173+00:00Silverlight Strategy Tweaked to handle HTML5Recently, there has been quite some buzz about Silverlight and HTML5. Microsoft has stated over and over they are supporting and investing a lot in HTML5. Have you heard the PDC keynote? If you heard it, then you’ve surely noticed the emphasis Ballmer placed on HTML5! Where was Silverlight in that keynote? Yes, I know PDC’s SilverLight focus was all about WP7, but what about all the other platforms?<br />
<br />
So where does that leave Silverlight? <br />
- Are they dropping the investment in SL?<br />
- Does it still make sense to support both platforms knowing that their targets and objectives are slightly different? <br />
- Will SL make sense only for smaller devices as WP7? <br />
- Is SL going to be the future WPF Client Profile (as we have nowadays lighter .NET versions called “Client Profile”) and the gap between WPF and SL continuously reduced until only WPF exists? Will it be named “WPFLight”? <br />
- Can HTML5 completely replace SL? Does it make sense to build complex UI applications in plain HTML5? Can/Should I build something like CRM Dynamics in HTML5?<br />
- Is it the best alternative if you want to invest in developing cloud applications?<br />
<br />
Much has been written about this subject, there are many opinions and mostly many unanswered questions. These are just a few of the questions I’ve heard and read in the last few weeks/months. These are hardly questions that just popped out of my mind… Let’s call them cloud questions, they are all over the web!<br />
What I would like to point out is that Microsoft is aware of this and in response they’ve published in the Silverlight team blog (<a href="http://team.silverlight.net">http://team.silverlight.net</a>), they’ve published an announcement talking about changes in the Silverlight strategy (<a href="http://team.silverlight.net/announcement/pdc-and-silverlight">http://team.silverlight.net/announcement/pdc-and-silverlight</a>). And I would like to quote the last part of it:<br />
<blockquote>We think HTML will provide the broadest, cross-platform reach across all these devices. At Microsoft, we’re committed to building the world’s best implementation of HTML 5 for devices running Windows, and at the PDC, we showed the great progress we’re making on this with IE 9. <br />
The purpose of Silverlight has never been to replace HTML, but rather to do the things that HTML (and other technologies) can’t, and to do so in a way that’s easy for developers to use. Silverlight enables great client app and media experiences. It’s now installed on two-thirds of the world’s computers, and more than 600,000 developers currently build software using it. Make no mistake; we’ll continue to invest in Silverlight and enable developers to build great apps and experiences with it in the future</blockquote><br />
So, what they are saying here is:<br />
- We acknowledge that HTML5 is the best cross-platform technology for the web<br />
- We think there’s still some room for SilverLight, namely complex user interface client apps<br />
<br />
And finally: “we’ll continuing investing in it!”. The question that might pop in your mind is “will they? Really? A long-term investment? Or a rather short one?”<br />
<br />
What do I think? I think there’s still room for SL applications and I’m looking forward to see the developments and how SL will continue to reduce the gap to the full WPF framework.Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-19669473912737446562010-09-20T14:43:00.001+01:002010-09-20T15:07:09.129+01:00Memory Dump to the Rescue<div style="text-align: justify;">Surely you’ve been through those situations where a user or a tester reports a situation that you can’t reproduce in your development environment. Even if your environment is properly set up, some bugs (such as a <a href="http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug">Heisenbug</a>) can be very difficult to reproduce. Sometimes you even have to diagnose the program in the testing/production environment! Those are the times you wish you had a dump of the process state when the bug occurred. Heck, you’ve even read recently that <a href="http://msdn.microsoft.com/en-us/library/fk551230.aspx">Visual Studio 2010 allows you to open memory dumps</a>, so you don’t even have to deal with tools like windbg, cdb or ntsd!</div><div style="text-align: justify;">Wouldn’t it be great if you could instruct your program to generate a minidump when it stumbles upon a catastrophic failure? </div><div style="text-align: justify;">Microsoft supplies a <a href="http://msdn.microsoft.com/en-us/library/ms679309(v=VS.85).aspx">Debug Help Library</a> which among other features, allows you to write these memory dumps. The code below is a .NET wrapper to this particular feature, which allows you to easily create a memory dump. </div><div style="text-align: justify;">Note however that the target assembly must be compiled against .NET 4.0, otherwise visual studio will only be able to do native debugging.</div><br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
namespace DumpLib
{
public class NativeMethods
{
DllImport("dbghelp.dll", EntryPoint = "MiniDumpWriteDump", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, IntPtr hFile, uint dumpType, ref MiniDumpExceptionInformation expParam, IntPtr userStreamParam, IntPtr callbackParam);
[DllImport("kernel32.dll", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern uint GetCurrentThreadId();
[DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess", ExactSpelling = true)]
public static extern IntPtr GetCurrentProcess();
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct MiniDumpExceptionInformation
{
public uint ThreadId;
public IntPtr ExceptionPointers;
[MarshalAs(UnmanagedType.Bool)]
public bool ClientPointers;
}
[Flags]
public enum DumpType : uint
{
MiniDumpNormal = 0x00000000,
MiniDumpWithDataSegs = 0x00000001,
MiniDumpWithFullMemory = 0x00000002,
MiniDumpWithHandleData = 0x00000004,
MiniDumpFilterMemory = 0x00000008,
MiniDumpScanMemory = 0x00000010,
MiniDumpWithUnloadedModules = 0x00000020,
MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
MiniDumpFilterModulePaths = 0x00000080,
MiniDumpWithProcessThreadData = 0x00000100,
MiniDumpWithPrivateReadWriteMemory = 0x00000200,
MiniDumpWithoutOptionalData = 0x00000400,
MiniDumpWithFullMemoryInfo = 0x00000800,
MiniDumpWithThreadInfo = 0x00001000,
MiniDumpWithCodeSegs = 0x00002000,
MiniDumpWithoutAuxiliaryState = 0x00004000,
MiniDumpWithFullAuxiliaryState = 0x00008000,
MiniDumpWithPrivateWriteCopyMemory = 0x00010000,
MiniDumpIgnoreInaccessibleMemory = 0x00020000,
MiniDumpValidTypeFlags = 0x0003ffff,
};
public sealed class MiniDump
{
public static void WriteDump(string fileName)
{
MiniDumpExceptionInformation info;
info.ThreadId = NativeMethods.GetCurrentThreadId();
info.ClientPointers = false;
info.ExceptionPointers = Marshal.GetExceptionPointers();
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
uint processId = (uint)Process.GetCurrentProcess().Id;
IntPtr processHandle = NativeMethods.GetCurrentProcess();
IntPtr processHandle2 = Process.GetCurrentProcess().Handle;
// Feel free to specify different dump types
//uint dumpType = (uint) (DumpType.MiniDumpNormal | DumpType.MiniDumpWithDataSegs);
uint dumpType = (uint)DumpType.MiniDumpWithFullMemory;
NativeMethods.MiniDumpWriteDump(processHandle2,
processId,
fs.SafeFileHandle.DangerousGetHandle(),
dumpType,
ref info,
IntPtr.Zero,
IntPtr.Zero);
}
}
}
}
]]>
</script><br />
<br />
<div style="text-align: justify;"><br />
</div><div style="text-align: justify;">Having the code to write a dump, let’s create an error situation, to trigger the memory dump creation. Let’s just create a small program that try to make a division by zero.</div><script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
static void Main(string[] args)
{
try {
// compiler doesn't allow division by a zero constant,
// so we have to use an auxiliary variable
int zero = 0;
int value = 123456789 / zero;
}
catch {
string fileName = string.Concat("C:\\", Process.GetCurrentProcess().ProcessName, ".dmp");
DumpLib.MiniDump.WriteDump(fileName);
}
}
]]>
</script><br />
<div style="text-align: justify;">Running this program will throw an obvious DivideByZeroException, which will be caught by the try catch block and will be handled by generating a memory dump.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">Let’s go through the process of opening this memory dump and opening it inside Visual Studio 2010. When you open a dump file in VS, it will present a Summary page with some data about the system where the dump was generated, the loaded modules and the exception information.</div><div style="text-align: justify;">Note that this summary has a panel on the right that allows you to start debugging. We’ll press the “Debug with Mixed” action to start debugging.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/_d0-GJfBcpv0/TJdhm4vT79I/AAAAAAAABAI/5LYxCxZ72i4/s1600/dumpLibSummary.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="454" qx="true" src="http://3.bp.blogspot.com/_d0-GJfBcpv0/TJdhm4vT79I/AAAAAAAABAI/5LYxCxZ72i4/s640/dumpLibSummary.png" width="640" /></a></div></div><div style="text-align: justify;"><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;"><br />
Starting the debug of a memory dump will start debugger with the exception that triggered the dump, thus you’ll get the following exception dialog:</div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;"><br />
</div></div><div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/_d0-GJfBcpv0/TJdhkNSfiyI/AAAAAAAABAE/adjx5TAwkBY/s1600/break.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="176" qx="true" src="http://4.bp.blogspot.com/_d0-GJfBcpv0/TJdhkNSfiyI/AAAAAAAABAE/adjx5TAwkBY/s400/break.png" width="400" /></a></div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; text-align: justify;"><br />
</div><div style="text-align: justify;">After you press the “Break” button, you’ll be shown the source code as shown below. Note the tooltip with the watch expression “$exception” (you can use this expression in the immediate or the watch window whenever you want to check the value of the thrown exception, assuming somewhere up in the stack you are running code inside a catch block) where you can see the divide by zero exception that triggered the memory dump.</div><div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/_d0-GJfBcpv0/TJdhgjUkugI/AAAAAAAAA_8/C6t0TSNpS2Y/s1600/dumpLibBreak.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="620" qx="true" src="http://3.bp.blogspot.com/_d0-GJfBcpv0/TJdhgjUkugI/AAAAAAAAA_8/C6t0TSNpS2Y/s640/dumpLibBreak.png" width="640" /></a></div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; text-align: justify;"><br />
</div><div style="text-align: justify;"><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;">You can also see the call stack navigate through it to the Main method where the exception was caught. All the local and global variables are available for inspection in the “Locals” and “Watch” tool windows. You can use this to help in your bug diagnosis.</div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;"><br />
</div></div><div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdhilAtl1I/AAAAAAAABAA/B8fGfFRcaHI/s1600/dumpLibBreak2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="265" qx="true" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdhilAtl1I/AAAAAAAABAA/B8fGfFRcaHI/s640/dumpLibBreak2.png" width="640" /></a></div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; text-align: justify;"><br />
</div><div style="text-align: justify;">The approach explained above automatically writes a memory dump when such an error occurs, however there are times when you are required to do post-mortem debugging in applications that don’t automatically do this memory dumping for you. In such situations you have to resort to other approaches of generating memory dumps. </div><div style="text-align: justify;"><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;">One of the most common approaches is using the debugger <a href="http://en.wikipedia.org/wiki/WinDbg">windbg</a> to achieve this. Let’s see how we could have generated a similar memory dump for this application. If we comment the try catch block and leave only the division by zero code in our application, it will throw the exception and immediately close the application. Using windbg to capture such an exception and create a memory dump of it is as simple as opening windbg, selecting the executable we’ll be running:</div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;"><br />
</div></div><div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdhopUsqOI/AAAAAAAABAM/d77iMLGGjEg/s1600/winDbg.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" qx="true" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdhopUsqOI/AAAAAAAABAM/d77iMLGGjEg/s400/winDbg.png" width="266" /></a></div><div style="text-align: justify;"><br />
This will start the application and break immediately (this behaviour is useful if we want to set any breakpoints in our code). We’ll order the application to continue by entering the command “g” (you could also select “Go” from the “Debug” menu). </div><div style="text-align: justify;"><br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdhqth6s4I/AAAAAAAABAQ/RbBkNufmQZU/s1600/winDbg2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="364" qx="true" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdhqth6s4I/AAAAAAAABAQ/RbBkNufmQZU/s640/winDbg2.png" width="640" /></a></div><br />
This will execute until the division by zero throws the exception below. When this happens, we’ll order windbg to produce our memory dump with the command ‘.dump /mf “C:\dump.dmp”’.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;"><div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdheJl5fDI/AAAAAAAAA_4/5_nj85prCxM/s1600/winDbg3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="363" qx="true" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TJdheJl5fDI/AAAAAAAAA_4/5_nj85prCxM/s640/winDbg3.png" width="640" /></a></div></div><div style="text-align: justify;"><br />
After this your memory dump is produced in the indicated path and you can open it in visual studio as we’ve previously done.</div><div style="text-align: justify;">Post-mortem is a valuable resource to debug some complex situations. This kind of debugging is now supported by Visual Studio, making it a lot easier, even though for some trickier situations you’ll still need to resort to the power of native debuggers and extensions like <a href="http://msdn.microsoft.com/en-us/library/yy6d2sxs.aspx">SOS</a>.</div>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com4tag:blogger.com,1999:blog-10053161.post-56053040989557063142010-09-16T17:27:00.001+01:002010-09-16T17:28:51.747+01:00Code Access Security Cheat Sheet<div class="MsoNormal"><span lang="EN-GB" style="font-family: Arial;">Here’s one thing most developers like: Cheat Sheets!<o:p></o:p></span></div><div class="MsoNormal"><span lang="EN-GB" style="font-family: Arial;">I’ve made a simple cheat sheet about .NET Code Access Security, more specifically about the declarative and imperative way of dealing with permissions.<o:p></o:p></span></div><div class="MsoNormal"><span lang="EN-GB" style="font-family: Arial;">Bear in mind that this cheat sheet <u>doesn’t</u> cover any of the new features brought by <a href="http://msdn.microsoft.com/en-us/magazine/ee677170.aspx">.NET 4.0 security model</a>.<o:p></o:p></span></div><div class="MsoNormal"><span lang="EN-GB" style="font-family: Arial;">This cheat sheet may be handy for someone who doesn’t use these features often and tend to forget how to use it or for someone studying for the <a href="http://www.microsoft.com/learning/en/us/exam.aspx?ID=70-536&locale=en-us">70-536 exam</a>.<o:p></o:p></span></div><div class="MsoNormal"><span lang="EN-GB" style="font-family: Arial;"><br />
</span></div><div class="MsoNormal"><span lang="EN-GB" style="font-family: Arial;"><b><a href="http://www.box.net/shared/3v44asyt7d">Download it here</a>.</b></span></div>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-89168427621195214982010-09-07T14:50:00.001+01:002010-09-07T14:55:20.683+01:00Viewing __ComObject with a Dynamic ViewIf you ever had to debug a .NET application that uses COM objects, you've probably added such an object to the Watch window or tryied to inspect it in the Immediate window, just to find out it was a __COMObject type which wouldn't give you any hint about it's members.<br />
Visual Studio 2010 gives you a solution for this problem. They've introduced a feature called <a href="http://msdn.microsoft.com/en-us/library/dd998308.aspx">Dynamic View</a>. As long as your project is using the .NET 4.0 framework you can now inspect these elements.<br />
<br />
Let's take a look at this code:<br />
<br />
<script class="brush: csharp" type="syntaxhighlighter">
<![CDATA[
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace DummyProj
{
class Program
{
static void Main(string[] args)
{
Type vsType = Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
object vsObj = System.Activator.CreateInstance(vsType, true);
EnvDTE.DTE dteObject = (EnvDTE.DTE)vsObj;
Debugger.Break();
}
}
}
]>
</script><br />
<div><br />
</div><div>This code is creating a Visual Studio instance and instructing the debugger to break execution right after the creation so that we can inspect the __ComObject.</div><div><br />
</div><div>There are two ways of doing this:</div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;"><ul><li>adding "vsObj" to the watch window and expanding "Dynamic View" node <span id="goog_1101428851"></span><span id="goog_1101428852"></span></li>
<li style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;">adding "vsObj, dynamic" to the watch window</li>
</ul><div class="separator" style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/_d0-GJfBcpv0/TIZBeU8H5gI/AAAAAAAAA-4/73tgkKAT_nc/s1600/dynamicView1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="626" ox="true" src="http://3.bp.blogspot.com/_d0-GJfBcpv0/TIZBeU8H5gI/AAAAAAAAA-4/73tgkKAT_nc/s640/dynamicView1.png" width="640" /></a></div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;"><br />
</div><div><br />
</div><div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;">Also note that if your object contains other __COMObjects you can inspect them in the same way as show here in the "AddIns" property.</div><div style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none;"><br />
</div></div></div><div class="separator" style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_d0-GJfBcpv0/TIZA-Ku-NRI/AAAAAAAAA-0/cT4RUN9jo8c/s1600/dynamicView2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="270" ox="true" src="http://2.bp.blogspot.com/_d0-GJfBcpv0/TIZA-Ku-NRI/AAAAAAAAA-0/cT4RUN9jo8c/s640/dynamicView2.png" width="640" /></a></div><div class="separator" style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; clear: both; text-align: center;"><br />
</div><div class="separator" style="border-bottom-color: initial; border-bottom-style: none; border-bottom-width: medium; border-left-color: initial; border-left-style: none; border-left-width: medium; border-right-color: initial; border-right-style: none; border-right-width: medium; border-top-color: initial; border-top-style: none; border-top-width: medium; clear: both; text-align: justify;">This "Dynamic View" feature was developed mainly to inspect dynamic objects (another new feature from .NET 4.0). That's where its name comes from.</div>Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0tag:blogger.com,1999:blog-10053161.post-16391798793112389092010-09-06T17:53:00.000+01:002010-09-06T17:53:00.917+01:00RIP : Object Test BenchAfter spending some time looking for Object Test Bench in VS2010 menus, I've decided to do a quick search and found this <a href="http://blogs.msdn.com/b/habibh/archive/2009/07/27/visual-studio-2010-rip-list-partial.aspx">VS2010 RIP list</a> where Habib supplies a partial list of the features removed in VS2010. I was surprised to find out they have removed Object Test Bench!<br />
It's not as if I really needed it, there's nothing I would do with it that I can't do with <a href="http://msdn.microsoft.com/en-us/library/f177hahy(VS.80).aspx">Immediate window</a>, but I did use it from time to time for some lightweight testing. I guess I won't be using it anymore, will I?<br />
But maybe you'll be more surprised to find out they also removed intellisense for C++/CLI!!!Anonymoushttp://www.blogger.com/profile/17321056367038938684noreply@blogger.com0