Tag Archive for .net

Utility to make important windows remain always on top

AlwaysOnTop

Do you sometimes fail to notice Outlook reminder window? Do you wish a chat window would remain always on top of other windows so that you never miss a message? Do you want to have a notepad always on top so that you can take quick notes anytime, while working on other apps?

We have an app for that.

It runs quietly on system tray and monitors open windows. Whenever it finds a window that you want to make always on top, it does that:

You can use this AlwaysOnTop utility to make any window remain always on top of other windows.

Get the tool and details here:

http://www.codeproject.com/Articles/794407/Utility-to-make-important-windows-remain-always-on

 

Sit back and relax, let Sharepoint remind and chase your team

EmailExample

Sharepoint Task List is a great place to record tasks for your team members. However, once you have recorded and assigned the tasks, then the fun begins. You have to remind your team members repeatedly about what they need to do today, what tasks are overdue, what’s coming this week and so on. Here’s an app that takes that chore away, and you can sit back and relax, while it will reminds your team members as many times as you want. Your team members will get an email like this, reminding them of their assigned tasks:

The email templates are fully customizable. You can define exactly how the email should look like. You can also include custom fields from sharepoint taks items to appear on the email.

Read the CodeProject article here for details:

http://www.codeproject.com/Articles/789418/Sit-back-and-relax-let-Sharepoint-remind-and-chase

10 IT Admin skills every .NET developer should have before going live

ITAdminSkillTalk

My talk at London .NET User Group on couple of essential skills every .NET developer should have under their belt before going live. If you are a startup or a developer who has to code, deploy and maintain .NET apps on production, you will find these techniques very handy.

Omar Skillsmater

http://skillsmatter.com/podcast/design-architecture/10-it-admin-skills-every-dot-net-developer-should-have-before-going-live/mh-6871

Watch the video at Skills Matters website.

Here are the slides from the talk.

SlidePreview

Memory Stream Multiplexer–write and read from many threads simultaneously

MultiplexerImage

Here’s an implementation of MemoryStream like buffer manager where one thread can write and many threads can read simultaneously. Each reading thread gets its own reader and can read from the shared stream on its own without blocking write operation or other parallel read operations. It supports blocking Read call so that reader threads can call Read(…) and wait until some data is available, exactly the same way you would expect a Stream to behave. You can use this to read content from network or file in one thread and then get it read by one or more threads simultaneously. Readers do not block writing. As a result, both read and write happens concurrently. Handy for building http proxy where you are downloading a certain file and you have multiple clients asking for the same file at the same time. You can download it in one thread and let one or more client threads read from the same buffer exactly at the same time. You can also use this to read same file on disk from multiple clients at the same time. You can also use this to implement a server side cache where the same buffer is read by multiple clients at the same time.

image

See the detail implementation here:

Memory Stream Multiplexer–write and read from many threads simultaneously

Don’t forget to vote.

Finally! Entity Framework working in fully disconnected N-tier web app

Entity Framework was supposed to solve the problem of Linq to SQL, which requires endless hacks to make it work in n-tier world. Not only did Entity Framework solve none of the L2S problems, but also it made it even more difficult to use and hack it for n-tier scenarios. It’s somehow half way between a fully disconnected ORM and a fully connected ORM like Linq to SQL. Some useful features of Linq to SQL are gone – like automatic deferred loading. If you try to do simple select with join, insert, update, delete in a disconnected architecture, you will realize not only you need to make fundamental changes from the top layer to the very bottom layer, but also endless hacks in basic CRUD operations. I will show you in this article how I have  added custom CRUD functions on top of EF’s ObjectContext to make it finally work well in a fully disconnected N-tier web application (my open source Web 2.0 AJAX portal – Dropthings) and how I have produced a 100% unit testable fully n-tier compliant data access layerfollowing the repository pattern.

http://www.codeproject.com/KB/linq/ef.aspx

In .NET 4.0, most of the problems are solved, but not all. So, you should read this article even if you are coding in .NET 4.0. Moreover, there’s enough insight here to help you troubleshoot EF related problems.

You might think “Why bother using EF when Linq to SQL is doing good enough for me.” Linq to SQL is not going to get any innovation from Microsoft anymore. Entity Framework is the future of persistence layer in .NET framework. All the innovations are happening in EF world only, which is frustrating. There’s a big jump on EF 4.0. So, you should plan to migrate your L2S projects to EF soon.

Do not use “using” in WCF Client

You know that any IDisposable object must be disposed using using. So, you have been using using to wrap WCF service’s ChannelFactory and Clients like this:

using(var client = new SomeClient()) {

.

.

.

}

Or, if you are doing it the hard and slow way (without really knowing why), then:

using(var factory = new ChannelFactory<ISomeService>()) {

var channel= factory.CreateChannel();

.

.

.

}

That’s what we have all learnt in school right? We have learnt it wrong!

When there’s a network related error or the connection is broken, or the call is timed out before Dispose is called by the using keyword, then it results in the following exception when the using keyword tries to dispose the channel:

failed: System.ServiceModel.CommunicationObjectFaultedException : 
The communication object, System.ServiceModel.Channels.ServiceChannel,
cannot be used for communication because it is in the Faulted state.

Server stack trace:
at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
at System.ServiceModel.ClientBase`1.Close()
at System.ServiceModel.ClientBase`1.System.IDisposable.Dispose()

There are various reasons for which the underlying connection can be at broken state before the using block is completed and the .Dispose() is called. Common problems like network connection dropping, IIS doing an app pool recycle at that moment, some proxy sitting between you and the service dropping the connection for various reasons and so on. The point is, it might seem like a corner case, but it’s a likely corner case. If you are building a highly available client, you need to treat this properly before you go-live.

So, do NOT use using on WCF Channel/Client/ChannelFactory. Instead you need to use an alternative. Here’s what you can do:

First create an extension method.

public static class WcfExtensions
{
public static void Using<T>(this T client, Action<T> work)
where T : ICommunicationObject
{
try
{
work(client);
client.Close();
}
catch (CommunicationException e)
{
client.Abort();
}
catch (TimeoutException e)
{
client.Abort();
}
catch (Exception e)
{
client.Abort();
throw;
}
}
}


Then use this instead of the using keyword:

new SomeClient().Using(channel => {
channel.Login(username, password);
});

Or if you are using ChannelFactory then:

new ChannelFactory<ISomeService>().Using(channel => {    
channel.Login(username, password);
});

Enjoy!

New and Improved Dropthings – the Open Source Web 2.0 AJAX portal

I have made some significant improvements and bug fixes on the latest 2.5.4 release of Dropthings, my open source Web 2.0-style AJAX Portal built on ASP.NET 3.5, Linq to SQL, Linq to Xml, Silverlight, Enterprise Library, Unity, Velocity, and what not. All the cool production quality techs you want to see in action are there in Dropthings – in a production quality open source project that powers critical portals around the world.

You can get the latest code from here:

http://code.google.com/p/dropthings/

I have uploaded some how to video tutorials to help you get started with Dropthings easily and troubleshoot common problems.

Here’s a list of new stuffs that were added and stabilized in this new release:

  • Run Dropthings under a virtual directory.
  • Widget drag & drop, add/remove improvements and many bug fixes on some not-so-common use cases.
  • Velocity Caching support. Dropthings can now be run in web farm and/or web garden mode and use Velocity for the distributed cache. This gives you more scalability and you can deploy on a large web farm and run a heavy traffic website. I have done enough load test to prove Velocity does make Dropthings scale. You can turn on/off Velocity from web.config. Just create a cache store named “Dropthings”, turn on the config and you are good to go.
  • AspectF implementation to put sensitive operations under transaction, retry, logging and error handling. Error logging is more streamlined. There are two log files where one log contains information and the other contains exceptions. They are both in App_Data folder.
  • Rich set of xUnit tests in Behavior Driven Development style. Important operations like First Visit, Revisit are now covered under automated tests.
  • Addition of “admin” role and “admin” user in database, who can Manage widgets and assign/revoke roles to widgets. You can setup admin user and admin role in your existing database using the ASP.NET Configuration tool.
  • A new page /Admin/ManageWidgets.aspx which is a one stop shop for managing widgets and permissions. Add widgets very conveniently. See the video tutorials on how to get a new widget coded and deployed in less than 5 mins.
  • More web.config settings to allow customization of key behaviors of the project.

Enjoy the new version. Those who have purchased the old version, I strongly recommend you take the time to upgrade. There’s no DB schema change. But there’s some good amount of code change. Check out the code commit history and the details of the changes are there.

C# with keyword equivalent

There’s no with keyword in C#, like Visual Basic.
So you end up writing code like this:

this.StatusProgressBar.IsIndeterminate = false;
this.StatusProgressBar.Visibility = Visibility.Visible;
this.StatusProgressBar.Minimum = 0;
this.StatusProgressBar.Maximum = 100;
this.StatusProgressBar.Value = percentage;

Here’s a work around to this:

this.StatusProgressBar.Use(p =>
{
  p.IsIndeterminate = false;
  p.Visibility = Visibility.Visible;
  p.Minimum = 0;
  p.Maximum = 100;
  p.Value = percentage;
});

Saves you repeatedly typing the same class instance or control
name over and over again. It also makes code more readable since it
clearly says that you are working with a progress bar control
within the block. It you are setting properties of several controls
one after another, it’s easier to read such code this way
since you will have dedicated block for each control.

It’s a very simple one line function that does it:

public static void Use<T>(this T item, Action<T> work)
{
    work(item);
}

You could argue that you can just do this:

var p = this.StatusProgressBar;
p.IsIndeterminate = false;
p.Visibility = Visibility.Visible;
p.Minimum = 0;
p.Maximum = 100;
p.Value = percentage;

But it’s
not elegant. You are introducing a variable “p” in the
local scope of the whole function. This goes against naming
conventions. Morever, you can’t limit the scope of
“p” within a certain place in the function.

Update: Previously I proposed a way to do it without generic
extention method which was not so clean. Andy T posted this cleaner
solution in comments.

Do Unit Test and Integration Test from same test code using Conditional Compilation

You usually write unit test and integration test code separately
using different technologies. For example, for unit test, you use
some mocking framework like Moq to
do the mocking. For integration test, you do not use any mocking,
just some test classes that hits some service or facade to do
end-to-end integration test. However, sometimes you see that the
integration and unit test are more or less same, they test the same
class using its interface and perform the same tests against the
same expectation. For example, if you think about a WCF service,
you write unit test to test the ServiceContract using the
interface where you use some mocking framework to mock the
interface of the WCF Service. If you look at the following example,
I am using Moq to test IPortalService interface which is a
ServiceContract for a WCF service. I am using xUnit and
SubSpec to do BDD style tests.

[Specification]
public void GetAllWidgetDefinitions_should_return_all_widget_in_widget_gallery()
{
    var portalServiceMock = new Mock<IPortalService>();
    var portalService = portalServiceMock.Object;

    "Given a already populated widget gallery".Context(() =>
    {
        portalServiceMock.Setup(p => p.GetAllWidgetDefinitions())
            .Returns(new Widget[] { new Widget { ID = 1 }, new Widget { ID = 2 }})
            .Verifiable();
    });

    Widget[] widgets = default(Widget[]);
    "When a widget is added to one of the page".Do(() =>
    {
        widgets = portalService.GetAllWidgetDefinitions();
    });

    "It should create the widget on the first row and first 
column on the same page"
.Assert(() => { portalServiceMock.VerifyAll(); Assert.NotEqual(0, widgets.Length); Assert.NotEqual(0, widgets[0].ID); }); }

Now when I want to do an end-to-end test to see if the service
really works by connecting all the wires, then I write a test like
this:

[Specification]
public void GetAllWidgetDefinitions_should_return_all_widget_in_widget_gallery()
{
    var portalService = new ManageCustomerPortalClient();

    "Given a already populated widget gallery".Context(() =>
    {
    });

    Widget[] widgets = default(Widget[]);
    "When a widget is added to one of the page".Do(() =>
    {
        widgets = portalService.GetAllWidgetDefinitions();
    });

    "It should create the widget on the first row and 
first column on the same page"
.Assert(() => { Assert.NotEqual(0, widgets.Length); Assert.NotEqual(0, widgets[0].ID); }); }

If you look at the difference, it’s very little. The
mockings are gone. The same operation is called using the same
parameters. The same Asserts are done to test against the
same expectation. It’s an awful duplication of code.

Conditional compilation saves the day. You could write the unit
test using some conditional compilation directive so that in real
environment, those mockings are gone and the real stuff gets run.
For example, the following code does both unit test and integration
test for me. All I do is turn on/off some conditional
compilation.

[Specification]
public void GetAllWidgetDefinitions_should_return_all_widget_in_widget_gallery()
{
#if MOCK
    var portalServiceMock = new Mock<IPortalService>();
    var portalService = portalServiceMock.Object;
#else
    var portalService = new ManageCustomerPortalClient();
#endif

    "Given a already populated widget gallery".Context(() =>
    {
#if MOCK
        portalServiceMock.Setup(p => p.GetAllWidgetDefinitions())
            .Returns(new Widget[] { new Widget { ID = 1 }, new Widget { ID = 2 }})
            .Verifiable();
#endif
    });

    Widget[] widgets = default(Widget[]);
    "When a widget is added to one of the page".Do(() =>
    {
        widgets = portalService.GetAllWidgetDefinitions();
    });

    "It should create the widget on the first row and 
first column on the same page"
.Assert(() => { #if MOCK portalServiceMock.VerifyAll(); #endif Assert.NotEqual(0, widgets.Length); Assert.NotEqual(0, widgets[0].ID); }); }

The code is now in unit test mode. When I run this, it performs
unit test using Moq. When I want to switch to integration test
mode, all I do is take out the “MOCK” word from Project
Properties->Build->Conditional Compilation.


image

Hope this gives you ideas to save unit test and integration test
coding time.