Monday, June 16, 2008 #

Signed up to work for the software empire

That’s right, I recently took a job offer from Microsoft as a Software Engineer and will be starting there in July. After few months of grueling interview process and tough decision on my part, I decided that it was an opportunity that I couldn’t miss.

So why Microsoft? Well, there are few things. First ‘aspiration’, I have always wanted to work for the software giant, the fact that you have opportunity to impact millions of people by your work is impassable.  Second, working with smarter people and chance to learn new things every day is appealing. And rest like benefits, location etc.. are definitely added bonus.

Why NOT Microsoft?  Looking from outside in, I have had doubts if I should take the opportunity. Particularly, the way big corporation works and the “red tape” around the processes. And of course there is a big difference between aspiration and reality. Also, I have heard horror stories of people who came out of there. Someone even asked me if “I sold my soul to the evil empire”. And finally, the rainy weather and expensive real estate in Seattle. But in long term, these were trivial compared to the opportunity. And I should not even complain about the rain compared to snowy winters and humid summers here in Des Moines. And being near to Vancouver is a big bonus for my wife and our family.

My job? It’s still .Net development. I’ll be working for Relationship Experience Division at Issaquah location near Seattle. Currently, I only know the high levels of the projects I might be working on; I guess I’ll find out more once I actually start there. Will I still be blogging? Definitely! I have heard MS is encouraging its employees to blog more. Though I probably won’t be able to blog everything, I’ll try to keep it as up to date as possible.

When’s the big move? It’s probably going to be July 1st and its coming up pretty fast. Though it’s nice that they will be taking care of everything for the move, I still need to kind of plan for it on my side. And moving from one place to another is definitely not easy. Still need to tie all loose ends at my current work, move and settle in Seattle area in 1 week, enjoy a vacation the following week and then start the grind on Monday!

posted @ Monday, June 16, 2008 10:02 AM | Feedback (1)

Monday, March 24, 2008 #

Is V1 of LINQ to SQL only suitable for RAD?

In my previous couple posts, I have been religiously trying to solve the problem or should I say 'find a best pattern' to use with linq to sql. In past few projects, I ventured into Linq to sql world abandoning ORM tools (OR mapper, NHibernate…) that I had been using; however, I have been greatly disappointed by the fact that Linq to sql doesn't support few fundamental concepts/patterns (LINQ to SQL takes a little different approach than traditional ORM tools). I am starting to have serious doubts if V1 of Linq2SQl is even cut out for any n-tier application (I am not even thinking enterprise application). Don't get me wrong, LINQ is a great framework and LINQ to SQL is an awesome extension. But in the real world business application the implementation of LINQ to SQL out of the box is not practical. How did I arrive to this conclusion? Here's how:

The two fundamental problems it fails to support out of the box are:

1. Working with objects in LINQ to SQL in disconnected context is painful. i.e. Most mid-large size applications are designed as n-tier architecture, thus entities within LINQ act more as a container (DTO or Business objects) for carrying data from one tier to another. The problem with LINQ to SQL is that disconnecting from one datacontext and reattaching to another is not trivial. This is a serious drawback given the fact that almost all the applications needs to use this model other than "quick demos".


I have seen lots of posts/articles from developers questioning the same problem. Various people have taken a stab at solving this, if you are seriously considering LINQ to SQL read these.

  • Benjamin's ULinqGen project in codeplex allows change tracking in pure POCO models
  • Post by Rick Strahl, explaining problem in Linq to SQL in a disconnected environment.
  • Matt's Linq2SqlEB project in codeplex which implements synchronization.

     

2. If you somehow implement an architecture to have live datacontext, one serious issue that you need to focus on is the lifetime management of DataContext. Please be aware, that poorly managed datacontext will bloat eventually and will hamper performance.

  • See my previous post on managing lifetime of datacontext
  • Rick Strahl discusses datacontext lifetime management here
  • Dino Esposito, suggest that you should use atomic context, but I don't see how it would solve the problem if you can't work in a disconnected environment.

Conclusion:
Am I ready to make jump to LinqToSql in my next project from my previous ORM tools? I don't know about others but, I will be holding back until I figure out a best way to work in a disconnected environment, which might be the next project. But the point is disconnected context support will be required. Dinesh Kulkarni, a senior dev for Linq to SQL team advises not use Active Record Pattern, but the problem is I don't see any pattern that I can use effectively in a n-tier architecture, not only the Active Record. LINQ to SQL itself uses great patterns within, but the way datacontext is managed and Entities/child entities are persisted it presents a different problem. It makes for a great presentation or RAD applications so far, but fails to support n-tier applications easily. I am considering concepts of offline datacontext and will follow up with more posts on this.

Is ADO.Net Entity Framework an answer?
Not really. The framework uses same concept of active context as Linq to SQL and quickly runs into the problem in a disconnected environment. I haven't done an in-depth implementation of it but the problem seems to be the same.

 

Let me know what you guys think of LINQ to SQL.

 

posted @ Monday, March 24, 2008 10:31 PM | Feedback (2)

Thursday, March 20, 2008 #

(Follow Up) Best practice and effective use of DataContext in LINQ

NOTE: 3/24/2008 - The problem of working with LINQ to sql extends beyond lifetime management of DataContext, thus I am scrapping the second part of my blog. Only thing useful in this post is the performance comparision. Here's new post on LINQ to SQL

In my previous post, I had probed a question on how to effectively incorporate DataContext in ones pattern so the ease of use and unit of work is well represented. Thanks to everyone who provided feedback, it definitely was a good read and provided lots of insight. Few reasons we got into asking this question instead of using simple create/dispose model, in the first place was

  • We wanted to make it so that it was easy to use
  • We heavily use Repository Pattern for business logic/transaction scoping and Entity model for CRUD operations, so wanted to make sure datacontext we used was as efficient as possible.
  • Concerns regarding efficiency of creating/disposing datacontext and not being able to use caching of datacontext effectively.

 

However, after reading several posts and looking deeper into datacontext, it seems that creating/disposing it as required is the best way to go. In order, to get rid of any suspicion I even created a little test to compare Ambient Context and Instantiation as required model, results are below. In the image below, first method GetByID(int32) actually instantiates datacontext everytime, where as the second one takes in a datacontext instantiated once by the caller (code is included at the bottom of the post). The results are impressive for dynamic instantiation. 23.7 secs vs. 20.9 secs for 6200 iterations. I think 3 secs is a reasonable margin not taking into account impact in memory with ambient datacontext or the efficiency of caching.

 

 

Either way, I believe for our purpose and in general a repository pattern incorporated with entity model should work pretty well. One thing Jeff did point out to me however was, once you have disposed your datacontext, any attempt to load/access child objects that is marked for lazy load will throw disposed object error as below. So make sure you load your objects while the context is alive, once that is done subsequent access is successful.

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Diagnostics;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
//Create & dispose Context everytime
            Test1();
            
        //Ambient Context Concept
Test2();
        }

//Create datacontext everytime
        private static void Test1()
        {
            List<EcardOrder> orders;
            using (MercyDataContext dbContext = new MercyDataContext())
            {
                for (int i = 0; i < 100; i++)
                {
                    orders = dbContext.EcardOrders.ToList();
                    foreach (EcardOrder order in orders)
                    {
                        //Datacontext will be created everytime 
// in this function
                        Ecard card = Ecard.GetByID(order.EcardID);
                    }
                }
            }
        }

        
//Create datacontext only once
        private static void Test2()
        {
            List<EcardOrder> orders;
            using (MercyDataContext dbContext = new MercyDataContext())
            {
                for (int i = 0; i < 100; i++)
                {
                    orders = dbContext.EcardOrders.ToList();
                    foreach (EcardOrder order in orders)
                    {
                        //Pass datacontext to the function as well
                        Ecard card = Ecard.GetByID(order.EcardID, dbContext);
                    }
                }
            }
        }


    }

    /// <summary>
    /// Partial Ecard class extended from database
    /// </summary>
    public partial class Ecard
    {
        //new datacontext is created and disposed everytime.
        public static Ecard GetByID(int ID)
        {
            using (MercyDataContext _context = new MercyDataContext())
            {
                return _context.Ecards.SingleOrDefault(e => e.EcardID == ID);
            }
        }

        //Puesdo concept of ambient datacontext
        //NOTE: once the Ecard is loaded it is cached in the context, 
        //thus items will be returned from cache
        public static Ecard GetByID(int ID, MercyDataContext _context)
        {
            return _context.Ecards.SingleOrDefault(e => e.EcardID == ID);
        }
    }


}

posted @ Thursday, March 20, 2008 4:46 PM | Feedback (1)

Tuesday, March 18, 2008 #

Best practice and effective way of using DataContext in Linq to SQL?

NOTE: See my follow up post here for more info.

At work, Jeff and I have been throwing around ideas to find a best way to implement DataContext in Linq so that we can integrate it into the base class in our framework while achieving following goals.

  • Implementation should be easy and non-redundant, so that we do not need to do new DataContext(), every time we have to use one.
  • Portability of the DataContext should be such that we do not need to pass it around as parameters from one tier to another.
  • "Unit of work" pattern should be well represented and "very" transparent.
  • Context should not be persisted without intent, or be open to manipulation from other methods, such that "unit of work" is compromised or a transaction is ill-represented

These seem like simple goals given the features and flexibility of LINQ, however, in reality this has become much more difficult and annoying to achieve than we previously thought. Here are several ideas we have been kicking around, and problem it presents. I would like to hear from people who have effectively used LINQ Datacontext in these scenarios or in a pattern that's most effective.

 

1. Creating and disposing LINQ as required.

DbDataContext myContext = new DbDataContext();

//your code goes here

myContext.SubmitChanges();

Problems with this pattern:

  • Creating datacontext everytime we need to use is cumbersome and in my opinion just verbose.
  • If you have to use datacontext in any of the method this code calls, you'll have to pass the datacontext with it. This is one- too many parameters to pass around

     

2. Creating a static DataContext and using it throughout the application.

DataLayer.DataContext.Current

Problems with this pattern:

  • Creating static object isn't always a good thing. In this case, the context is available for manipulation at any level. And unit of work quickly becomes very hard to maintain
  • If manipulated by other threads or methods context isn't clean anymore and cannot be trusted

3. Ambient DataContext (Currently using this)

The idea behind ambient datacontext is that context is created for a particular thread or a httpcontext(in asp.net) as soon as there is a first call for the DataContext. Then the same context is used for that thread or request unless it is disposed manually. This is done by storing the context in the request/thread data store. The approach to this pattern is similar to static DataContext, however, separation is provided for each thread and requests. This works really well in Asp.Net, however, is again plagued by some of the problems of static context.

Problems with this pattern:

  • The context is available for manipulation at any level. And quickly becomes very hard to maintain unit of work
  • Portability across thread is very hard
  • Unit of work pattern is not transparent enough

4.  Finally, the last idea we've been trying to come up with is concept similar to TransactionScope.

In this pattern, you would used using{ } block to initialize your context and represent a "Datacontext Scope". Any method below that will automatically be able to figure out the proper context, through thread/request datastore. Then just before the dispose happens, you manually call the SubmitChanges() method. This is the one I like so far, however, has few practical problems.

Problems with this pattern:

  • If sub method needs to implement a new context, we need to figure out how to exclude it from the parent context's using block. If allowing multiple contexts in multiple using blocks, how do you determine which context to use in sub-sub methods?

 

Please do comment on what you think is the best approach to solving this problem.

posted @ Tuesday, March 18, 2008 8:51 PM | Feedback (7)

Thursday, February 07, 2008 #

Is VB.Net better or C#.net? Or is .Net a .Net either way?

As a .net programmer at some point in your life, you probably have gotten into a discussion or at least faced a choice between VB.net and C#.net. Though the argument is never ending on both sides, how do programmer that are bilingual or someone who is just learning feel? What long term productivity impact does this have in development shop or team in general?

Well for me, I clearly have choice in mind, but instead of presenting my views today, I will publish the following list our good friend Jeff Lanning compiled from various sources few years back. Though some of the points have changed with new version of .Net, I hope it provides a good reference for anyone dealing with such a choice. Here it goes; don't forget to put in your two cents:

Reasons to Choose C# over VB.NET:

C# was designed expressly for the .NET platform and Microsoft is standardizing their company on it, which means they have a much deeper investment in C# technologies (language features, compilers, dev tools, etc) than they do in VB.NET. In fact, both Visual Studio and the .NET Framework where written in C# (using C++ as a backend). Furthermore, C# was submitted to, and standardized by, the ECMA group as an open standard while VB remains proprietary.

The C# language is very similar to the other major languages (like Java, JavaScript, C/C++, PHP, and Perl) and shares many of the same concepts, keywords, and syntactical elements. These similarities means a C# programmer will be more able to read, write, and borrow code from those other languages. Most programming books not specific to any one programming language (e.g., books on UML, data structures, OOP concepts, etc.) are likely to include examples in Java.

Outside of the endless language features debate, C# has become the defacto standard for .NET development. A majority of third-party and open source components are written in C#. A majority of advanced programming articles are written in C#. Microsoft's application blocks and other development resources are also provided first in C#, and later converted to VB.NET. If anything, .NET developers owe it to themselves to learn C# for that reason alone (even if they think VB is still the greatest thing since the Apple IIe). As long as they never have to modify or inspect anyone else's .NET code, it may be fine to ignore C# for the time being, but chances are that isn't going to be the case for very long if they want to take advantage of the rapidly growing .NET community's resources.

Most students coming out of college have experience with Java and/or C++, making the transaction to C# quite natural. In addition, these young professionals will likely see VB.NET in the same light as COBOL with its legacy-ridden, verbose BASIC syntax, and be drawn to C# as the best long-term choice for professional grown.

The learning curve going from VB6 to either VB.NET or C# is about the same given that 95% of the effort will be spent learning the object model of the .NET Framework, the new development tools, new OOP concepts, and all the new techniques involved in developing Windows or Web applications in .NET. While VB.NET might seem to be just an improved version of VB6, they are really two languages that are eerily similar, but perversely different. In fact, many experienced VB developers may find C# easier to learn (although a bit more uncomfortable at first) because it helps draw a clean distinction between the two development platforms and avoids many pitfalls associated with bringing a VB6 mindset into the .NET world (like using "On Error GoTo"). There is much to be said for starting with a clean slate.

VB.NET does not have native support for XML embedded documentation, which is used by IntelliSense and to auto-generate class reference documentation directly from the code (with tools like NDoc, DocGen, and many others). The absence of this feature alone is a strong reason to avoid VB.NET on large development projects. This limitation will be fixed in the VS2005 release.

Over the next few years, Microsoft will be differentiating the VB.NET and C# product lines. VB.NET will diverge to provide a better RAD (Rapid Application Development) experience, while C# will diverge to provide a better experience building complicated business frameworks, backend services, application architecture, and reusable object-oriented components. For smaller projects, either language will be a fine choice, but as the size and complexity of applications increase, the productivity gain from C# will likely outweigh that of VB.NET.

Language-specific reasons C# is a better choice…

- less verbosity (e.g., easier to find the "important" words in the code)

- assignment operator is not the same as the comparison operator

- Native XML code documentation (which drives IntelliSense notes)

- does not hide "Advanced Members" of classes

- simplified type casting syntax (instead of directcast(), ctype(), cbool(), etc...)

- case-sensitivity (allowing for better variable names in many cases)

- 'OnError GoTo' is impossible

- option explicit by default (enforces correct type usage)

- cleaner null test expressions ("obj != null" rather than "not obj is nothing")

- better variable scope containment in loops and code blocks

- automatic logic short circuiting (streamlining common test/use logic)

- 'using' blocks for clean/safe resource management

- continue / break statements supported in loops

- embed special string characters ('\n', '\r', '\t', etc…)

- string escaping ('@')

- comment support is just better (multiline comments, XML comments, single-line comments, etc…)

- as operator (string s = obj as string)

- native increment/decrement supported ('--' and '++' )

- intellisense is much less interfering

- arrays are defined with number of elements, not the upper bounded index

- hierarchical constructor calling (ctor() : ctor("defaultValue"))

- array/collection indexer is not the same as a function call ('[0]' vs '(0)')

- 'ByVal' is very misleading (it passes a pointer (ie reference), not a value; whereas 'ByRef' passes a pointer to a pointer)

- unsigned values (uint, ulong)

- P/Invoke makes much more sense, and is uberly easier to figure out

- doesn't hide delegate usage (AddressOf)

- more optimized MSIL generation

- operator overloading

- pointers

- event syntax

- delegate syntax

- unmanaged/unsafe code supported

- 'Default Namespace' doesn't just prefix your classes namespace

- EntryPoint isn't hidden ([STATThread] static void Main(string[] args))

 

From a discussion thread:

Actually I'm little concerned about VB's future with the graduating generation of programmers. Most of today's universities are teaching Java as a primary learning tool. And usually the academics view VB as a clumsy language for lazy programmers. Decades ago the most supreme business language was COBOL. Those who had a chance working with it know it is an outstanding language that is dead meat, not because it is not used anymore (70% of World's applications remain bounded by it) but because the new generations learned from their teachers that computer science is science, COBOL is for business and C is for math (math is science). Some may argue that there is COBOL.Net, however, seniors can't stand OO way of thinking, juniors can't stand OLD language stigma so it is also dead before it is born. Having C language culture and nowadays Java transferred from teachers to students, what do you think IT managers will prefer for their departments growing potentials if they choose to acquire .NET?

 

If I was a manager I would surely choose C# for several reasons:

1) So I can get the brightest of new (low paid) grads up and running in no time.

2) So I can get to that C++ like language fame surrounding my projects and yet get it RAD.

3) So I can leave infamous VB lazy clumsy programmers gossips roam as they wish without feeling their sting.

 

But I am a developer so I choose C# for:

1- No job is secure, so I'd better get used to curly brackets and once I learn most of XML, web services, SOAP, etc., then I am empowered to switch easily to that other half of corporate world that is using J2EE.

2- It's more stylish and attractive (yes it does matter if you are going to spend most of your day on something then better love it).

3- Because VB's parents Bill and Mic seem to undermarket it in favor of C# (could it be they are trying to abandon the ship?).

 

From a discussion thread:

We chose VB.NET a year ago and we regret it. We have 25 very bright developers and a substantial ecommerce web site with plenty of traffic. One year ago we kicked off our port to .NET and we chose VB6 because our existing code base was VB6 and ASP. A few of us here had significant C# expertise from previous jobs and warned the bosses that the "advantages" of VB.NET were a mirage and that there were some clear disadvantages. They actually thought the "automatic conversion" tools were going to buy us some time. The pointy-haired contingent won out and not a day goes by that we don't curse them for forcing VB.NET on us.

As other's have said, you take a big hit moving to .NET at all. The tiny additional hit of moving talented VB6 developers to C# is more than offset (IMHO) by the increased developer productivity achieved over the medium to long term in C#. (If your team is not very talented -- or not talented in that way -- YMMV.)

Why do I think I am more productive in C# than in VB.NET? Here are a few reasons:

1. VB.NET has abysmal static code analysis: functions that don't return values, uninitialized variables, unused variable declarations, etc... This is what a compiler is *for*. I wish VB.NET had an "Option ReallyStrict On" so it would check things as thoroughly as the C# compiler does. You can spend hours trying to track down which uninitialized variable or non-returning pathway in a function is the source of a bug, when the compiler could just tell you.

2. VB.NET has more aggressive background compilation that you can't turn off or control in any way and which is buggy! We have solutions for our web site with 30 projects and some projects with hundreds of files. You can't add a method to a class without taking a coffee break while intellisense chews up a CPU. We're reduced to having to buy double cpu machines for developers so that they can just type at full speed. And even then all that CPU is wasted because the background compilation just can't keep up. I wish there were an option for intellisense so that you could *tell* VB.NET when to recompile and when to just chill out because I'm typing a raft of code.

3. VB.NET (still) has lurking intellisense bugs whether you use project dependencies or file dependencies. Whichever you choose, you're stuck with a different set of problems ("can't copy dll X [v1.1.3000.1] over dll X [v1.1.3000.2]" or "dll A requires a reference to dll B" or "can't copy dll Y to c:\foo\bar\y.dll because it is locked")

4. VB.NET has no "using" directive. I know it's just syntactic sugar... but I want more sugar. The truth is that interacting with non-managed resources (ie. the OS or the database) in .NET sucks even in C#. But having to write "Dim x ... Try ... Finally .... x.dispose EndTry" all the time is just pouring salt in the wound.

5. VB.NET has no multiline comment syntax

6. VB.NET has no within-the-line comment syntax

7. VB.NET has no multiline string syntax

8. VB.NET has a limit on line continuations (what is it, like 10 lines)?

9. VB.NET projects cannot have pre-build or post-build steps (large, real-world projects inevitably need them)

10. VB.NET has no built-in comment->documentation generator

 

And in case anyone is still reading... it's hard to think of any advantage we've seen in using VB.NET. Maybe one: it made some COM coding easier because we could use late binding. I'd say if you are doing lots of COM interop especially if you need late binding, VB.NET is necessary. But I don't recommend doing any more COM interop than you absolutely have to and late binding is worse than evil.

 

I think that pointy-haired types think that VB.NET will make it "faster". That the learning curve will be less steep or that fewer changes will need to be made to the code. It just doesn't work that way. Your project will take 2 or 3 times as long as you anticipated, even if you pick VB.NET. And when you choose VB.NET you may get started faster but you'll be paying a tax forever, because the language and tools just aren't as good as C#. I'm crossing my fingers for VB improvements in 2005, but I'm not holding my breath. Doubtless something else will be "missed" (like multi-language projects were this time) and we'll still be stuck in a VB.NET ghetto.

posted @ Thursday, February 07, 2008 10:45 PM | Feedback (12)

Saturday, January 19, 2008 #

Little Known Feature of RDP 6.0 – Multi-monitor Support

Remote Desktop/VNC is undoubtedly one of the coolest and a most convenient tool for working remotely. However, the lack of multi-monitor support and slow response was always inconvenient. RDP client 6.0 released by Microsoft last year, however, solved that issue by supporting RDP resolution of up to 4096 x 2048 pixels. That means now you can have multiple monitors up to 4096 x 2048 pixel cumulative resolution. All you have to do is, launch mstsc with /span argument.

i.e. on the run window type: mstsc /span

To download or for more information go to http://support.microsoft.com/kb/925876

Please note that along with the above download, you'll also need new version of RDP support on the server/computer you are connecting to. Other features include 32bit color support and support for plug & play devices.

posted @ Saturday, January 19, 2008 11:23 AM | Feedback (0)

Sunday, December 02, 2007 #

“Add” extension method in Linq deprecated in VS 2008 RTM

Well, one of the "perks" of working in beta and switching to rtm is definitely the few surprises that come along. In VS 2008 Beta2 Linq entities had 'Add' method that allowed you to add an object to the current datacontext. Surprisingly, it is removed and renamed to 'InsertOnSubmit' on the RTM. It took me a while to figure that out, cause most of the stuff I had written previously was working fine. And I was so confident that my extention method had gone missing, that I started scouring through Reflector, instead of googling. Anyway, this info should help anyone, who's trying to hunt the add method. For disconnected updates however, attach method still exists.

posted @ Sunday, December 02, 2007 8:19 PM | Feedback (2)

Tuesday, November 13, 2007 #

Got MCPD ed!

Finally passed my Microsoft 70-551 test and got the MCPD certification. To Tell you the truth the new generation of tests are really rigorous than before, esp. 70-549, took few tries to get pass it. Also, this was an upgrade test and had 88 questions for 4 hours, was kinda tiring. Anyway, studying for it provided some insightful knowledge.

posted @ Tuesday, November 13, 2007 8:08 PM | Feedback (4)

Thursday, October 18, 2007 #

Most secure online banking system

I thought it was only me who thought my Credit Union's online banking system was so great! Turns out there are tons of other patrons who share the same feeling. Well, if it makes it to Daily WTF, then it must be something. I couldn't resist not sending few emails to the customer service praising the system. I am sure no-hacker or identity thief has ever gotten through my bank's online security, how could they if I myself have a hard time getting in? To tell you the truth, it's faster for me to run to the ATM/bank to check my account than to try logging into the system. The multi-authentication factor implemented is just unbeatable. Alex does a better job of explaining what it is, check it out here.

Check out the visual keyboard, who needs a physical one??? (BTW: the thieves have to be fast mouse users, otherwise it times out.J)

Unfortunate for the hackers, the system is implemented by various credit unions and banks all over United States. Does your bank have this advance system?

posted @ Thursday, October 18, 2007 6:54 PM | Feedback (0)

Wednesday, October 17, 2007 #

Useful Utility functions in .Net a.k.a ‘Hidden Treasures’

It's no secret that Microsoft's is releasing the source for some of its core .Net classes in upcoming visual studio 2008. Before that arrives, the option to look at some of core classes is probably the .Net Reflector. Every now and then, when I want to find out how Microsoft implemented some of the functionalities in core classes, or if I want to learn better way to program, I use the reflector to dig through the core components. During these adventures, I have bumped into various classes and functions, that I thought were just too cool, and also unfortunate that most were internal only. One of my favorites is the VirtualPath class. However, during this quest I have also found that in some way or other the framework team did expose some great utility functions. Most developers aren't aware of this, including myself and make the mistake of rewriting it. Thus, here's a shot at exposing some of the cool Utility Classes and Functions (I have been using) that every .Net developer should know. (I hope to keep adding to this list, if anyone has other suggestions please feel free to add.)

 

ASP.NET

 

System.Web.HttpUtility
System.Web.HttpServerUtility

Provides helper methods for processing web requests like HTMLEncode, UrlEncode, HTMLDecode
Accessible through 'Server' object in asp.net

System.Web.VirtualPathUtility

Provides utility methods for common virtual path operations.
Members: GetDirectory(), GetExtension()

System.Web.Compilation.BuildManager
.CreateInstanceFromVirtualPath()

One of my favorites, allows you to create instance of pages/controls just by passing a virtual path.

System.Web.Security.UrlAuthorizationModule
.CheckUrlAccessForPrincipal()

Another great utility in asp.net that allows you to check permission on the file even before you use it. Usage? ex: loading sitemap based on the permission set on each file rather than specifying roles in the node.

System.Web.Hosting.HostingEnvironment

Various methods/properties related to hostingenvironment

System.Web.Hosting.HostingEnvironment
.VirtualPathProvider

Retrieves virtual path provider for the application

   

.NET

 

System.IO.Path

Provides helper methods for file/directory strings

Members: ChangeExtension(), GetFileName, Combine…

Int? DateTime?

These are nullable classes of primitive types.

Int.TryParse

Equivalent to IsNumeric() function in VB.

 

NOTE: There are tons of other classes & static functions in .NET, it's a best practice to use those. If you can't find one exposed but is internal/private, I would suggest creating one similar to it.

posted @ Wednesday, October 17, 2007 6:03 PM | Feedback (2)

Copyright © Bigyan Rajbhandari