Showing posts with label .NET. Show all posts
Showing posts with label .NET. Show all posts

Wednesday 27 April 2011

ASP.NET and HTML5 Local Storage

 

HTML5 Local Storage and consuming it through ASP.NET. A great read.

With this entry on my blog, I’m making a comeback into my writing world. I had remained silent for quite a while now. Sometimes life just takes over.  Reasons can be innumerable. Right!, After battling it out with life, i’m glad, i’ve finally made time to post things on my blog again.

Thursday 23 September 2010

Tip of the day – A good use of auto implemented properties.

A very practical use of auto implemented properties could be to create a immutable lightweight class. An auto implemented property is a ‘property’ in C# without fields. The C# JIT Compiler generates the IL with a field for the auto implemented properties. (hence the name). The IL also replaces the Get and Set accessor stubs in the Properties to return and set the automatically generated field.

Take a look at the below code ( class ‘Books’). There are Title, Author and PublshedYear auto implemented properties. Notice the set is private, This makes the ‘Books’ class immutable.

autoprop

The tip is to use this kind of construct to replace structs when ever a reference type is required. Also notice that the constructor is made ‘private’. Simply because i find the factory method ‘CreateBook’  semantically appealing to call the private constructor rather than having to use the auto implemented property directly in the constructor for initializing the Books object.

Take a look at the IL for Books.,  Notice the ‘k__BackingField’ feild generated by the C# Compiler.

image

//////////////get_Author: string() IL////////////////////

.method public hidebysig specialname instance string
        get_Author() cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // Code size       11 (0xb)
  .maxstack  1
  .locals init (string V_0)
  IL_0000:  ldarg.0
  IL_0001:  ldfld      string ConsoleApplication1.Books::'<Author>k__BackingField'
  IL_0006:  stloc.0
  IL_0007:  br.s       IL_0009
  IL_0009:  ldloc.0
  IL_000a:  ret
} // end of method Books::get_Author

 

//////////////////set_Author:void(string) IL////////////////

.method private hidebysig specialname instance void
        set_Author(string 'value') cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  stfld      string ConsoleApplication1.Books::'<Author>k__BackingField'
  IL_0007:  ret
} // end of method Books::set_Author

Now, a demo of using the above immutable lightweight class

democode

Happy patterns discovery..

I’ve used the MSDN example here to illustrate.

Tuesday 7 September 2010

Entity Framework 4.0 and ASP.Net 4.0

This is a very good example of real world EF and ASP.Net .
Published with Blogger-droid v1.5.8

Wednesday 4 August 2010

Mono Tools for Visual Studio - 2.0

Mono Tools for Visual Studio is a commercial add-in for Microsoft™ Visual Studio™ that enables developers to write .NET applications for non-Windows platforms within their preferred development environment.
It allows developers to build, debug and deploy .NET applications on Linux, while continuing to leverage the extensive ecosystem of code, libraries, and tools available for .NET. – Courtesy http://mono-tools.com/

More Here:
http://mono-tools.com/FAQ/

Thursday 11 February 2010

Visual Studio 2010 and .Net 4 RC

WhooHoo!!
Download everything from here
Catch the action here
I’m having a play on the following, till the RC expires!
1] VS 2010
2] TFS
3] Lab Management 
4] Test Professional
5] Agents -Visual Studio Agents 2010 enables scale-out load generation, distributed data collection, and distributed test execution.

Sunday 15 November 2009

PDC 2009 Next Week!!

 

I am eagerly looking forward to the presentation ‘Future Directions for C# and Visual Basic’.

http://blogs.msdn.com/lucabol/archive/2009/11/13/luca-at-pdc-2009-next-week.aspx

Wednesday 26 November 2008

Tools for everyday development


1. Process Explorer
processexplorer
Process Explorer shows you information about which handles and DLLs processes have opened or loaded.
The Process Explorer display consists of two sub-windows. The top window always shows a list of the currently active processes, including the names of their owning accounts, whereas the information displayed in the bottom window depends on the mode that Process Explorer is in: if it is in handle mode you'll see the handles that the process selected in the top window has opened; if Process Explorer is in DLL mode you'll see the DLLs and memory-mapped files that the process has loaded. Process Explorer also has a powerful search capability that will quickly show you which processes have particular handles opened or DLLs loaded.

2. Debug View
debugview
DebugView is an application that lets you monitor debug output on your local system, or any computer on the network that you can reach via TCP/IP. It is capable of displaying both kernel-mode and Win32 debug output, so you don't need a debugger to catch the debug output your applications or device drivers generate, nor do you need to modify your applications or drivers to use non-standard debug output APIs.
Cool Features
  • Win32 OutputDebugString
  • Kernel-mode DbgPrint
  • All kernel-mode variants of DbgPrint implemented in Windows XP and Server 2003
DebugView also extracts kernel-mode debug output generated before a crash from Window's 2000/XP crash dump files if DebugView was capturing at the time of the crash.
3. PsKill
Windows NT/2000 does not come with a command-line 'kill' utility. You can get one in the Windows NT or Win2K Resource Kit, but the kit's utility can only terminate processes on the local computer. PsKill is a kill utility that not only does what the Resource Kit's version does, but can also kill processes on remote systems. You don't even have to install a client on the target computer to use PsKill to terminate a remote process.
P.S: Filemon and Regmon have been replaced by Process Monitor on versions of Windows starting with Windows 2000 SP4, Windows XP SP2, Windows Server 2003 SP1, and Windows Vista. Filemon and Regmon remain for legacy operating system support, including Windows 9x.
4. Resource Refactor
RefactoringTool-Menu
Features for Resource Refactoring Tool
  • Works with C#, VB.Net languages. Supports all project types that ships with Visual Studio 2005 including web sites and web application projects.
  • A preview window to show changes.
  • Finds other instances of the text being replaced in the project automatically.
  • Lists existing resources by their similarity level to the text being replaced.
  • Automatically replaces hard coded string with a reference to resource entry.
5. Ghost Doc
Automatically generates documentation for constructors,methods,properties and class. Integrates will with visual studio and style cop and is a must have to get rid of those style cop warnings.
6. Microsoft StyleCop
StyleCop analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. This is a definite must have. It enforces consistent looking code across the whole project with multiple developers with varied tastes and preferences.
7. Microsoft FxCop
FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. Many of the issues concern violations of the programming and design rules set forth in the Design Guidelines for Class Library Developers, which are the Microsoft guidelines for writing robust and easily maintainable code by using the .NET Framework.
FxCop is intended for class library developers. However, anyone creating applications that should comply with the .NET Framework best practices will benefit. FxCop is also useful as an educational tool for people who are new to the .NET Framework or who are unfamiliar with the .NET Framework Design Guidelines.
FxCop is designed to be fully integrated into the software development cycle and is distributed as both a fully featured application that has a graphical user interface (FxCop.exe) for interactive work, and a command-line tool (FxCopCmd.exe) suited for use as part of automated build processes or integrated with Microsoft Visual Studio® .NET as an external tool.

Links
Sysinternals Suite
FxCop
The Visual Studio Code Analysis Team Blog
StyleCop
Introducing StyleCop on legacy projects
Ghost Doc
Resource Refactor

Thursday 20 November 2008

Unit Testing Silverlight Apps

Inarguably SL2 applications are  a whole new experience of developing cross platform applications from managed code environments.

Unit Testing becomes very vital while developing for cross browser enterprise class applications. Visual Studio's tight integration of the Unit Testing framework is such an invaluable tool in the code production pipeline. Now, with the release of a unit testing framework for SL2 applications, the same experience can be leveraged.  SL2 applications can be developed in a test driven fashion now. It perfectly suits an agile team. A team which is constantly driven by change and is delivering on a constant basis, almost every day in some cases. Much like a team which does not have a release model. (Check out Jeff Wilcox's blog). I guess the Silverlight test framework was itself developed using an agile methodology.

The SL Unit testing framework has  proved to be an invaluable tool personally for me. It allows me to test SL applications on 3 different browsers (cheap guess if you are thinking which browsers ) even though i target IE mainly. :P.  I'll write about it with a test application soon in my next blog. Till then, check out these links..

Some Links:

Silverlight Toolkit - You can find components like dockpanel, treeview etc for SL 2, themes and of course the source code for controls with unit tests and the unit test framework itself.

Jeff Wilcox - The guy who develops actively on the SL unit test framework at MS.

Scott Gu's small demo program on SL unit testing - (If you don't know this man, you are not worth living, jump off a building NOW!)

MS Silverlight Unit Test Framework - MS unit test framework for SL 2.

Wednesday 19 November 2008

A Simple Multi-threaded Logger

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace SudhirMurthy.Logger {

public interface ILog {

void LogToDisk(string msg);

}

interface ILoggerService {
ILog ILog {
get;
}
}

public class LogFile : ILog {

static List<string> messages;

//WriteToDisk delegate
private delegate void WriteToDisk(object sender, string fileName);

//WriteToDisk event
private static event WriteToDisk writeToDisk;

public static void WriteLog(string fileName) {
//Raise the event
writeToDisk(new object(), (fileName));
}

public void SendToDisk(object sender, string fileName) {

StreamWriter sw = File.CreateText(fileName);
foreach (string s in messages) {
sw.WriteLine(s);
}
sw.Close();
}

public LogFile() {
messages = new List<string>();
WriteToDisk mydelegate = new WriteToDisk(SendToDisk);
writeToDisk = new WriteToDisk(SendToDisk);
}

public List<string> Messages {
get {
return messages;
}
}

#region ILog Members

public void LogToDisk(string msg) {
Monitor.Enter(this);
messages.Add(msg);
Monitor.Exit(this);
}

#endregion
}

public class LoggerService : ILoggerService {

//TODO: Need to make it threadsafe..
private static ILog logInstance = null;

public LoggerService() {
logInstance = new LogFile();
}

#region ILoggerService Members

public ILog ILog {
get {
return logInstance;
}
}

#endregion
}

public class LoggerClient1 {

LoggerService logService;

public LoggerClient1() {
logService = new LoggerService();
}

public void Log() {
logService.ILog.LogToDisk(string.Format(
"I am Logging: {0}", this.ToString()));
}
}

public class LoggerClient2 {
LoggerService logService;
public LoggerClient2() {
logService = new LoggerService();

}
public void Log() {
logService.ILog.LogToDisk(string.Format(
"I am Logging: {0}", this.ToString()));
}
}

public class TestApp {

LoggerClient1 a;
LoggerClient2 b;

public TestApp() {

a = new LoggerClient1();
b = new LoggerClient2();
}

public void logClient1() {
for (int i = 0; i < 1000000; i++) {
a.Log();
}
}

public void logClient2() {
for (int i = 0; i < 1000000; i++) {
b.Log();
}
}
}

class Program {

static void Main(string[] args) {

TestApp app = new TestApp();
Thread t1 = new Thread(new ThreadStart(app.logClient1));
Thread t2 = new Thread(new ThreadStart(app.logClient2));


try {
t1.Start();
t2.Start();
} catch (Exception) {
throw;
}
t1.Join();
t2.Join();

//The main thread should technically wait until
//t1 and t2 should have finished and then execute
//the following
LogFile.WriteLog("log.txt");
}

}

}



I have demonstrated a simple multi-threaded logging mechanism here. The threads t1 and t2 share the static instance variable 'List<string> messages' while logging. The LoggerClient classes LoggerClient1 and LoggerClient2 each use the LoggerService to log messages. The log is finally written to disk by the the main thread. The LogFile class uses the Monitor.Enter(this) and Monitor.Exit(this) methods to allow locking while shared access to writing the log. This synchronizes the threads t1 and t2 to perform shared access writes without corrupting or overlapping the write operations. Another important thing to notice here is the methods t1.Join() and t2.Join() which is used to make the main thread wait until the threads t1 and t2 have finished executing.


If you try removing the Monitor.Enter(this) and Monitor.Exit(this) lines from the above code, you end up getting weird line numbers in your log.txt file. (enable line no's in visual studio and see log.txt). i.e the count of the log will never be as expected (2 million in the above case). By putting the above lines back, you get the expected value which is 2million lines of log. :). It takes about 5-6 seconds on my dual core for threads t1 and t2 to finish logging and the main thread to write to disk. :).  A bloated 93.4 MB file!!



My thread on MSDN Forums.



C0de

Wednesday 13 August 2008

VS 08 SP1 and .Net FX 3.5 SP1

Woohoo!! Time to get excited..VS 08 SP1 seems to me like more of a bug fixing upgrade over features. However, .Net FX 3.5 SP1 is exciting with the following

1] ASP.Net Dynamic Data :

ASP.NET Dynamic Data, which provides a rich scaffolding framework that enables rapid data driven development without writing code, and a new addition to ASP.NET AJAX that provides support for managing browser history (back button support). For more information

2] Entity Framework

http://msdn.microsoft.com/en-us/data/aa937723.aspx

3] ADO.NET Data Services Framework

The ADO.NET Data Services Framework consists of a combination of patterns and libraries, which enable data to be exposed as a flexible REST (Representational State Transfer)-based data service that can be consumed by Web clients in a corporate network or across the Internet. The ADO.NET Data Services Framework makes data service creation over any data source. A conceptual view model of the underlying storage schema can easily be exposed through rich integration with the ADO.NET Entity Framework. Services created by using the ADO.NET Data Services Framework, and also compatible Windows Live (dev.live.com) services, can be easily accessed from any platform. For client applications that are running on Microsoft platforms, a set of client libraries are provided to make interaction with data services simple. For example, .NET Framework-based clients can use LINQ to query data services and a simple .NET Framework object layer to update data in the service

Downloads

> .NET FX 3.5 SP1

> VS 08 SP1

Thursday 31 July 2008

A Concurrent Programming Primer on Code Project

 

I found a good read on PLINQ (Parallel LINQ) and TPL (Task Parallel Library) on code project. It doesn’t cover everything though but gives you good examples and common pitfalls using them.

The examples cover,

  • Parallel Class - Parallel.For, Parallel.Do, AsParallel  constructs
  • Exception Handling for Parallel programming constructs
  • Handling of compiler side-effects.

You need the TPL CTP download and of course VS 2008 for trying out the samples.

Converting a LINQ query from sequential to parallel execution is as simple and straightforward as below :

   1: Enumerable<T> data = ...;



   2: var q = from x in data.AsParallel() where p(x) orderby k(x) select f(x);




Here’s the link

Wednesday 2 July 2008

Running Queries on Multi-Core Processors


Multi-core processors are here. Once pervasive mainly in servers and desktop PCs, now multi-core processors are being used in mobile phones and PDAs, resulting in great benefits in power consumption. Responding to the increased availability of multi-processor platforms, Parallel Language Integrated Query (PLINQ) offers an easy way to take advantage of parallel hardware, including traditional multi-processor computers and the newer wave of multi-core processors.
PLINQ is a query execution engine that accepts any LINQ-to-Objects or LINQ-to-XML query and automatically utilizes multiple processors or cores for execution when they are available. The change in programming model is tiny, meaning you don't need to be a concurrency guru to use it. In fact, threads and locks won't even come up unless you really want to dive under the hood to understand how it all works. PLINQ is a key component of Parallel FX, the next generation of concurrency support in the Microsoft® .NET Framework.
Using technologies like PLINQ will become increasingly crucial to ensuring the scalability of software on future parallel microprocessor architectures. By utilizing LINQ at choice places throughout your applications today—such as where you have data- or compute-intensive operations that can be expressed as queries—you will ensure that those fragments of your programs continue to perform better when PLINQ becomes available and the machines running your application grow from 2 to 4 to 32 processors and beyond. And even if you only run that code on a single-processor machine, the overhead of PLINQ is typically so small that you won't notice a difference. In addition, the data parallel nature of PLINQ ensures your programs will continue to scale as the size of your data sets increases.
More here