AmbiguousMatchException Error on Silverlight 4 RC

On March 17, 2010, in Programming, by Akash Kava

Here is quick update for the following error,

System.Windows.Markup.XamlParseException occurred
  Message=System.Reflection.AmbiguousMatchException: Ambiguous match found.

That may start popping up after you install Silverlight 4 RC or later version and its quite annoying when Silverlight does not offer any detail about the error. One of the most annoying factor in silverlight is, for every parse exception Line Number and Line Position are always zero.

I started analyzing my code and try to understand what went wrong, it took half an hour to figure out the root cause. And following is the result,

I had a derived TextBox class of silverlight and had a property named “Watermark”, however I did compile everything against Silverlight 3 only, but over curiosity I had installed Silverlight 4 RC, which has TextBox with a property named “Watermark” with type as object.

No Side by Side in Silverlight

That is bad news, because if tomorrow there is one update by Microsoft, and you are away from your desk, all of sudden support calls will start piling up. Because the new update will have few things that will raise all unexpected errors without warnings. So if you have Silverlight 3 app, if you dont plan to upgrade to 4, Silverlight will not run side by side and it will cause problems. So you will always have to keep on upgrading Silverlight apps!!

AmbigiousMatchException

This occurs when you have a property in your class as well as in the base class (usually we always will be careful to avoid this) with different type. However I dont know what exactly will happen if you have property with same type and name in base as well as child class, but it looks to me as if this is just a parse exception. Silverlight may load values correctly.

Solution

I know this is what you are looking for, but it isnt easy, what you have to find out is, if any of your class has any property whose name exactly matches with name of property defined in its base class and higher in inheritance chain. If you have same name but different type, this error will occur, it may also occur if you have property written with new keyword. It will not occur on inherited property.

Please also have a look at upcoming, rapid business form development on  WPF as well as Silverlight. Please click here to check the preview.

  • Share/Bookmark

Looking at the innovation driving inside Silverlight, it is getting more attention then the former WPF. However having very similar syntax and .NET as base platform, both WPF and Silverlight are very different in approach, design and use. Today lot of developers live in dilemma of WPF vs Silverlight and it has now become a great trade off as similar to speed vs size.

Lets compare the need and features of both and make the trade off very easy to understand.

History of Microsoft Development Platform

We all loved Visual Basic, what did it provide? a rapid development platform to make quick business applications. By business applications I mean, the one to track your purchases, your activities which are just probably relational database and reports. Business Application makers didn’t have to worry about device drivers, system services, hardware and component versions.

Visual Basic provided very thin layer of application development for rapid turnaround time of small scale but huge in demand business applications. These applications require very less programming language expertise but more of business expertise. But it had limitations, you could not create a huge resource intensive application like CAD programs, Media editing programs, servers, games etc.

On other hand we had Visual C++, a huge development framework with possibility to do almost everything that was possible on Windows Operating System. Where you could fulfill need of any program, be it CAD, games, media editing, or servers etc.

But the development time required was very high, performance was great and the intelligence required to create system applications was very high. Getting talent to build such applications weren’t easy and even it is not easy today, because you need real in depth knowledge of how every part of the system functions. There is more dependency upon device drivers, component versions and there was no drag and drop.

Apart from any other platforms existed so far, Microsoft clearly and distinctly divided development into two major categories. Rapid vs System, or Native vs Thin applications.

Evolution of .NET

Ever since c# came into existence, we started seeing quick shift from tedious MFC/COM/ATL to c#, because all technologies were simply extension of c/c++ and each needed separate runtime to exist. Even still today, some of my components are written in ATL/COM and compiling them in newer version of Visual Studio is always pain. Compilation time is huge.

Where else, .NET based project took less time to compile, even the 1.0 versions are still in use and still in good shape.

Earlier it was expected that it will only replace the Visual Basic segment of programming, but somehow all devs started liking it and preferred it as an alternative to ATL/COM/MFC as its native capability and speed provided easy development and quick turnaround.

Windows Forms did provide an alternative to Visual Basic. But there was lack of more powerful, GUI interface in .NET. So came WPF. Not only this, .NET being neutral, the compiled apps are independent of 32 bit or 64 bit platforms.

Windows Presentation Framework

As we clearly see, Microsoft has its plan to make WPF as its primary GUI framework against all Win32 components. WPF is very easy to write as it is very simple XML, XML is very easy to read, and its very easy to organize, even the editors and compilers need less overhead in parsing and taking decisions based on XML.

The challenge here was to imitate almost everything that existed in Win32 inside WPF, and WPF became very feature rich, but once again it requires more intelligence to write complicated and big applications. Having talent already expert in HTML+JS area, and transforming them into WPF talent was little difficult.

Plus the way WPF was built, it was built more tight coupled with system operating system, just like the way MFC/ATL/COM were built. But WPF is very fast and very rich in features. It is now possible to write CAD, games and such high performance applications in WPF which can utilize latest hardware technologies.

And it is exact alternative for COM/ATL/MFC today.

Silverlight

Realizing that converting HTML+JS and Visual Basic devs to WPF was more challenging, silverlight pop in to existence, Which is very light weight, a smaller counterpart of WPF, although the syntax remains same, the ability to develop apps are limited in silverlight as it is not very tightly coupled with operating system.

However, you can develop apps pretty fast, but only focused on business logic, which here is one step ahead amongst all being platform independent. The devs are not required to have in depth knowledge of system, nor silverlight are more dependent on hardware, resources or other components.

But you cant develop high performance apps like CAD, games and media editing apps.

Indeed, it is an exact alternative for Visual Basic.

Conclusion

You need to choose WPF when you are creating any application of following type,

  1. Interfaces with custom hardware.
  2. You need to control memory and control the performance of app.
  3. Create application that requires very high memory, CAD programs etc.
  4. Connect to system components and used to manage system, hardware.
  5. Want to connect to native system via COM/DLL interfaces.
  6. Media (Audio/Video/Picture) editing applications.
  7. Where your target audience can download and install .NET platform easily.

However you can use Silverlight for following alternative type of applications,

  1. Provides smooth and quick animation on the web.
  2. Make Rapid Business Applications, which can connect to your enterprise apps.
  3. Make typical CRUD applications.
  4. Registration, Dashboard type of applications.
  5. Lightweight gaming and interaction websites.
  6. Run in browser, with very small installation needed.

Coming Up:

UI Atoms from NeuroSpeech, a set of controls to develop rapid business applications on both WPF as well as Silverlight. A true alternative for DataForm on Silverlight and WPF, to have unified coding for Business Apps. Please click here to check the preview.

  • Share/Bookmark
Tagged with:  

Apple-iPad

Apple announces iPad, a bigger version of iPod Touch. With a big screen of 1024×786 pixels. And it comes with basic need of surfing internet and be online. So called magical and revolutionary device does not support Flash and Silverlight yet. And most of business apps today, built upon RIA are running either on Flash or on Silverlight. And IT Devs are heavily investing in RIA technologies due to snail speed of WWW group. However, the device can replace a laptop for most of users who just spend time on internet doing their regular business, studies or entertainment. So lets analyze what will be future of Web for different type of users.

Students

Today students need a good web browser and an internet with lot of social media websites to study, interact, entertain and play games. Apple iPad is a best bet for students. Do they really care that it does not support Flash and Silverlight yet? Answer is no. They will certainly buy iPad, come to the website, and if it has Flash or Silverlight, they will call website’s support instead of Apple’s support and say,

Your website is not working on my iPad.

Sales Reps and Business Owners

Looking at the cost, and attractive looks, Sales Reps and Business Owners will buy iPad because they usually do not type anything great whole day, all they do is, look at websites, present demos (which are powerpoint or keynote), and access their office through online business portals. For all these purpose they will be very happy with iPad. However, once they come to your business app through online portal, they cant see Flash or Silverlight, they are not going to call apple support. They will call IT devs and say,

What the hell IT devs are doing, cant they make our business app work on iPad?

Independent Professionals

Independent professionals like Doctors, Lawyers, Photographers, Actors .. anyone who probably does not sit in front of PC for more then 2 hours a day, will certainly like to get rid of big laptop bag with 4-10 external wires and device connectors. All what they do mostly is, check their emails, surf the websites, fill simple forms on some business web apps and which they can do it on iPad. Today iPad may not have great drawing tools but some professional apps on App store will certainly provide capability of tagging, drawing and marking tools needed by these professionals. Today lot of business applications are on Flash and new ones are coming on silverlight. But iPad will not support !! , once again, they will pickup the phone to vendor and say,

Your website is not working on my iPad.

Who needs any of following?

pc_vs_macClerks,  Graphics/Media artist and IT Developers, which comprises of small part of computer users. Because their applications and workspace requires bigger screens and multiple devices, connectivity and computing performance. Apple’s iPad will be useful only to test the business apps and for other entertainment to this group.

It seems iPad will spread in Home Entertainment, Education and Independent Professional sectors very fast because of low cost solution. And that will shake the developer community.

Troubles for IT Devs

  1. Current investment in Flex or Silverlight is at stake, as usage of mobile devices is increasing heavily, supporting business apps on these devices will not be possible until device OS creators, Adobe or Microsoft work towards supporting RIA technologies.
  2. Silverlight/Flex are heavy and costly to run on battery based devices, they will consume more cpu and battery to create consumption problems.
  3. Rewriting apps in light HTML5 is a big challenge, training, planning and supporting all existing modules will be a big pain. However looks like World Wide Web Consortium (W3C) has been sleeping for 10 years to create features of RIA required today. Need of consumers were high, that created innovations like DHTML, Flash and Silverlight, and the problem was, W3C never observed in market what consumers (Internet users) really need.
  4. Even if you decide to invest heavily on iMac and decide to make apps that can run on iPad, your Apps are at mercy of Apple Employee doing approval, here is the funny process.

AppStoreComic

Death of Free and Open Internet

IT Devs will slowly loose the independence over distributing apps against open free internet distribution. Today any release, distribution of media (song, movie, play) etc are controlled by major Labels.

If The  Intelligence will be controlled by major Labels in IT with narrow route to success by Apple, Google, Microsoft etc giants, then the growth we saw in last decade in IT industry will slow down very rapidly and independent innovators will become slaves to major labels.

Will Bubble of RIA Burst now?

Once again, just like Dot Com, if RIA (Flex/Silverlight) Bubble bursts and all IT Devs will be blamed again.

  • Share/Bookmark
Tagged with:  

Retouch! I would say – why not?

On February 6, 2010, in Business, Technology, by Akash Kava

Its less of a risk then getting yourself a liposuction or a nasty boob job :) ..

Before I answer WHY let me answer WHAT! For all of you who don’t know what I am talking about watch this video “The Photoshop Effect”

 

Why Retouching

On a serious note, Human psyche has been on a constant Endeavour to achieve perfection. Retouching is a means to persue that human pursuit. How else would you preserve and portray the invaluable momentary short lived tequila shots of your life. A retouched image would give you that well deserved kick time and again.

Besides not all of us can carry a Cindy Crawford mole as a beauty spot the way she does. Come on, would you want that dark spot seen in your wedding snaps. You would rather get them retouched. Similarly you would more often then not, want to get a brighter retouch-er if you are from the Naomi Campbell or a Hale Berry progeny. "I don’t mean to be a racist here" unless you want to spend a bomb to look as good.

Retouching the History

Beginning from our inception, Adam was perfect as a first masterpiece, as a human being, but as a man he was lacking. Later, Adam with Eve became a perfect couple until they fell prey to Satan’s handiwork and since then we’ve been living in an imperfect world. I need not elaborate on this any further and no wonder everything around us is (believe it or not) imperfect.

Retouched – Do We Even Know?

BTW If you see a problem here, sure do something, lets run a campaign to make it a mandate to put an * (asterisk) symbol on every retouched image. I bet you would see 99.9 % of photographs retouched in any magazine or billboard or for that matter any print media with an asterisk sign, the way we notice "*" or "Conditions Apply" on every shop running a SALE.

Lately there has been a lot of hype around retouching and its adverse effect or so they call it, just because some nuts went on an indefinite dieting spree to fulfill there fantasies of attaining that perfection portrayed by a retouched image of a model. I have a question here, if some one ignores that ‘asterisk’ on a FOR SALE sign board and happens to pick up stuff and queued up at the counter only to realize that there was some other exception, what do you think would happen. Wouldn’t you ask her to go back to shopping basics. She’s not duped! An asterisk is supposed to be taken for granted.

Retouching  & The Craving Need of It

As I proclaimed above I see no moral hang-up in retouching a photo but the reality is that it can change a picture from something you dislike to something enjoyable. We all understand the difference between tweaking the truth and portraying the expected. Perfect moments do not always prove to be perfect and that’s where we need the so called digital liposuction.

Let me sum up with a practical example:

A stunning model sitting right in front of you that has potential but several flaws. By several I mean the following two major flaws apart from a few here and there that can otherwise be taken care of:

Dull Hair
has a pimple right on the face of the camera lights

What do you do ?

1) Hand over the best shampoo available and wait for the results + wait for the pimple to even out.
2) Click the snap and retouch it. Its simple and worth while.

I leave it for you guys to decide. Any takers!!

For all of you guys who want to try the first option you need to keep visiting my blogs for the rest I know you guys understand how difficult it is to get a boob job done, and how difficult it is to get that perfect look unless we go to RetouchMAX.com

  • Share/Bookmark
Tagged with:  

Current Problems of Windows 7 for Developers

On September 13, 2009, in Programming, Technology, by Akash Kava

After visiting Microsoft TechNet Seminar everyone was quite excited about Windows 7 and everyone was saying that Windows 7 is far better then Vista and its now ready to go alive. I did stick to my plan of upgrading my development machine to Windows 7 only after Service Pack 1 arrives. But everybody argued that no its ready for developers even. Fine I tried to install it on my laptop which I rarely use for development and here is the experience.

It took drivers and it was pretty faster then Vista as far as installation goes, but then immediately I found two problems.

Move Files Progress Bar Bug

I took backup on my other D drive and I have both administrator and basic user and while copying files back on basic user I found this bug. When you are trying to move files, and if you are an administrator and it doesnt need any UAC permissions then you can see progress bar as shown below.

Original

But if your destination folder/drive requires some UAC permission then the UAC dialog box comes and when you accept everything after that the progress bar no longer displays progress as shown below.

MoveBug

This happens if you try to copy something into windows/program files or anywhere for some other users when running from basic user.

And we have to wait endlessly for this window to get closed automatically and that probably proves that operation was successful.

I am really disappointed to see bugs on very critical operations like file operations are most crucial. Even on Vista, Move operation did not work correctly as it did not delete the source files/folders and that leaves us with confusion.

Canceling Move Operation Creates Inconsistencies

While the Move operation is on, if you decide to cancel, you are left in bad position because then you are left with half files from old location and half in new. Sure its not great problem as we can consolidate immediately.

Cant Install Remote Server Administration Tools (RSAT)

This is really great bug, because on development machine, we really cant live without RSAT. We need them to manage servers. I found this link from live search, RSAT for Windows 7 . When I try to install this update it gave this error message “This update is not applicable for your computer”. Further more in Event Viewer, I got this message.

Windows update  could not be installed because of error 2149842967

I did report this bug to lot of places, hope it gets resolved soon, but I think on Microsoft Download website they should put some feedback about the item being downloaded.

Visual Studio 2008 Installation Problems

I am not sure whether VS 2008 installed successfully or not, because although it said it was successful, there were certain errors in Event Viewer.

Product: Microsoft Visual Studio 2008 Professional Edition – ENU — Error 1935.An error occurred during the installation of assembly ‘Microsoft.Windows.Design,
version=”3.5.0.0″,
publicKeyToken=”b03f5f7f11d50a3a”,
processorArchitecture=”MSIL”,
fileVersion=”9.0.30729.1″,
culture=”neutral”‘.
Please refer to Help and Support for more information. HRESULT: 0×80070005. assembly interface: IAssemblyCacheItem, function: Commit, component: {7A515F16-7D3F-4A41-910A-E704ABC9E8CA}

I havent yet started using VS on 7 but I will soon and I am sure there will be many problems.

Cant Install Visual Studio 2008 Service Pack 1

However when I tried to install Visual Studio 2008 Serivce Pack 1, it didnt install and gave following errors in log.

Product: Microsoft Visual Studio 2008 Professional Edition – ENU – Update ‘KB945140′ could not be installed. Error code 1603.

And another error at the last,

Product: Microsoft Visual Studio 2008 Professional Edition – ENU – Update ‘Visual C++ 2008 SP1 Design-Time Components for x86 – KB947888′ could not be installed. Error code 1603. Additional information is available in the log file C:\Users\***\AppData\Local\Temp\Microsoft Visual Studio 2008 SP1_20090913_140916022-Microsoft Visual Studio 2008 Professional Edition – ENU-MSP0.txt.

Cant Install SQL 2008 Management Tools

I tried to install SQL 2008 Management Tools, it gave me compatibility issue and warned me that you must install SQL 2008 SP 1, I agreed. And I went ahead with installation and Installation stopped because Visual Studio 2008 SP 1 was not installed.

Cant Instal SQL 2008 Tools

Conclusion

I think I am on conclusion that Windows 7 is not yet ready for Developers and they should wait for Windows 7 SP1 to arrive.  And it should only be used by Testing Teams to test the products.

  • Share/Bookmark
Tagged with:  

This document only refers to optimization of Vista Machine for faster development only intended for the ones who are doing development on C#, ASP.NET and Optional VC++, no VB.NET.

Installation of Limited Visual Studio 2008

We probably dont need Compact Frameworks and VB.NET and other tools, unnecessary installing them doesnt waste much of Hard disk space but what happens that your registry grows too big as you install more number of items. Registry is very costly database, and its accessed very regularly, more items in registry, slower and slower the PC. So here is list of items you should install.

Visual Studio Items

Visual Studio Items

Disable High End Graphics, Faster Performance

Disable High End Graphics

Disable High End Graphics

Disable System Restore Points

Now, System Restore Points are good, but usually on development machine, they run very slow, and they never do any good if system crashes, the restore time is as big as and as problematic as to reinstall OS.

Disable System Restore Points

Disable System Restore Points

Increase Paging Size

Increase it as much as you can in different drive but the acceptable range is 2GB to 4GB only.

Increase Paging Size

Increase Paging Size

Remove Unnecessary Vista Items as shown below

Remove Unnecessary Programs and Features

Remove Unnecessary Programs and Features

Setup Taskbar and Start Menu

Taskbar and Startmenu Properties

Taskbar and Startmenu Properties

Expand Items for Quicker Use

Expand Control Panel

Expand Control Panel

Expand Documents

Expand Documents

Expand Admin Tools

Expand Admin Tools

  • Share/Bookmark
Tagged with:  

The quest to store large number of files in database or on regular file system began at a time when number of files to manage went beyond 1 million in one of our project. We started noticing a huge drop in performance of our windows server. After investigating we found out that using pure file system to store more then million files is really a bad solution. And following are key points.

  1. Each operation of file open/close requires kernel operation, because it needs to do various security checks.
  2. Every file operation requires some minimum locking mechanism which uses your cpu in kernel mode.
  3. Above operations being kernel operations, they slow down entire server even if your file access may be of least priority then any transactional database operation.
  4. Each services on server slows down.
  5. Even operating system itself manages a file system database (typically known as File Allocation Table and similar names in other systems).
  6. These databases are optimized but not for millions or trillions files. They are good to work under million files.
  7. It causes huge fragmentation on your storage media.
  8. Not only media, but even File System Database gets fragmented, leading to more slow down.
  9. Durability of storage media also can reduce because of too much fragmented usage.
  10. Backup and Restore operations take too long time. You can easily conduct an experiment, on any ftp client, try to upload only one 1Meg file and then try to upload 100 10KB files, although the total transfer is only 1Meg, you will notice uploading 100 files of smaller size takes longer.
  11. Keeping track of changes/deleted items are even more difficult.
  12. Tools for replication and change tracking for file systems aren’t available for huge file storages.
  13. The web server will need write access to some folders which is always a big security hole.
  14. And file system crash = operating system crash and thats  a huge challenge to bring it back up.
  15. For transferring files you need to open ftp and develop some tools to replicate them.

Finally, after all these observations, we started considering other options.

  1. Network File System, it looks promising, but even at other end of node, its simply an operating system. It still has same problems as mentioned above.
  2. Distributed File Systems like Hadoop and other tools require too much of learning, management and I think they are good when you need file storage as huge as Facebook, Yahoo etc. We are mid size company and our need is 1TB for now.

Database Solution:

Finally we began testing database solution with MySQL and then we moved onto MS SQL, however both have good advantages and disadvantages that we will discuss further.

We have following advantages over file systems, and also I have provided solution detail later on this article.

  1. Database systems have matured enough to handle large data easily today.
  2. They use small number of files to store all relational data in well organized form.
  3. They keep their database files open all the time, so the kernel operations of locks are reduced.
  4. You can consider as if your load of entire server is now concentrated only on your database.
  5. Databases are much advanced in terms of their scheduling of queries, you can reduce priority of your file database and database will easily offer more performance on other transactional databases.
  6. Data storage is transactional, where else file systems are not completely transactional. And file systems require more programming to make them transactional.
  7. Remember if its your customers data, even if its a small picture/icon any video.. if they are paying for your service then its better to store those media files in transactional storage.
  8. Database crash doesnt crash entire server and nor even other databases on same server.
  9. Backing up and restoring databases are easier because of the inbuilt tools.
  10. Replication on database are much easier.
  11. Change tracking is available on database.
  12. Database access is standard its not dependent on ftp/http like tools.
  13. Database can easily take over failures of neighbor nodes in network.
  14. You can easily query database and do multiple operations on files.
  15. The biggest point is, your web server does not need any write permission on any folder !!

Comparison between MySQL and MSSQL for file storage

  1. MySQL offers replication over internet, MSSQL doesnt, you will have to write your own replication program.
  2. MSSQL offers auto grow option for database file, with which you can reduce fragmentation. MySQL’s innodb doesnt have such option for database file auto grow method which leads to more fragmentation.
  3. MSSQL offers easy incremental backup/restore and more over, in case of crash, you can use actual data folder files to restore, where else MySQL’s innodb doesnt support hot backups so either you buy their hotbackup tool or rely on mysql’s backup tool which is not incremental.
  4. MSSQL costs $1600 for standard edition, where else MySQL innodb is free, but hotbackup or incremental backup tools will cost exactly the same. MSSQL wins over mysql for offering better file management and increasing disc durability.

Sample Solution

After reading various articles, we came to conclusion that storing entire file in one blob or image doesnt make sense as it will deteriorate performance like anything.

So we came with easy solution, which is already used by existing file systems. Thats “Breaking down file into smaller blobs, max 512kb”.

As MySQL and MSSQL both have network packet size limit, you should not store more then 512kb in one row. Otherwise you will have to increase network packet size and that will slow down database server. Following is easy small table structure we used.

Table: NSFiles

NSFileID (Auto Number) (bigint)
NSFileName (varchar 50)
NSContentType (varchar 100) ** This is most important for web access

Table: NSFileBlobs

NSFileBlobID (Auto Number) (bigint)
NSFileID (bigint) (indexed) (Reference of NSFiles.NSFileID)
NSBlobIndex (int)
NSBlobData (medium blob or image)

Following are Storage/Retrieval methods specified in C# with using Linq or any similar ORML tool.

//Upload Handler
NSFile file = new NSFile();
file.NSFileName = .....
file.NSContentType = Request.Files[0].ContentType;
file.Insert(); // <-- insert into database and get new unique NSFileID
byte[] buf = new byte[512000];
int i = 0;
using(MemoryStream ms = new MemoryStream(Request.Files[0].FileData))
{
int count = ms.Read(buf,0,512000);
while(count>0)
{
NSFileBlob blob  = new NSFileBlob();
blob.NSFileID = file.NSFileID;
blob.NSBlobIndex = i++;
if(count==512000)
{
blob.NSBlobData = buf;
}
else
{  // last blob will always be less then 512kb
blob.NSBlobData = new byte[count];
Buffer.BlockCopy(buf, 0 , blob.NSBlobData, 0 , count);
}
blob.Insert();
}
}

And following is simple code for Download Handler

// Download Handler
long fileID = long.Parse(Request.QueryString["FileID"]);
NSFile file = NSFile.Adapter.Get(fileID);
Response.ContentType = file.NSContentType; // important for web browser
// following line causes "Save As" box on client
Response.AddHeader("content-disposition","attachment;filename=\"" + file.NSFileName + "\"");
// following loops over all file blobs whose NSFileID is fileID and they are sorted by blob index
NSFileBlob.Adapter.ForEach(
NSFileBlob.Schema.NSFileID == fileID,
NSFileBlob.Schema.NSBlobIndex.SortAs(),
(t)=>{
Response.OutputStream.Write(t.NSBlobData,0,t.NSBlobData.Length);
}
);

  • Share/Bookmark
Tagged with:  

C# Optimizations Via Caching – Part 2

On March 22, 2009, in C#, Programming, by Akash Kava

I decided to write part 2 of optimization, with C# Project, to actually test the performance for accessing NameValueCollection and Property access.

I had lot of comments by extra smart people quoting regarding my previous post at "C# Optimizations Via Caching" . That all methods posted do not do any significant impact on performance, I wonder people just have habit of posting any thing without even thinking once.

So I decided to write a piece of code to actually demonstrate the optimization impact with statistics. In this Visual Studio 2008 C# Console Project, I wrote a simple code to access an application config value directly for 10,000 times in a loop and then to access it via statically cached variable. And in second part, I implemented accessing property and accessing a local variable nearly 10 million times to detect noticeable effect.

The tests are as follow,

Lets look at the test code to access config values, also please note that config values are stored in NameValueCollection, which is same object used in Request, Response and Session objects in web request.

// Configuration Access Test
Console.WriteLine("Testing Direct Config Access");

Test(1000000, () => {
     string v = System.Configuration.ConfigurationManager.AppSettings["Key"];
});

Console.WriteLine("Testing Cached Access");
Test(1000000, () => {
     string v = SettingVal;
});

Following is the result, on Intel Centrino Duo with 1GB of RAM, this shows that the code with cached access in static variable is 100 times faster.

Testing Direct Config Access

Time Difference 1125 MilSecs

Testing Cached Access

Time Difference 15.625 MilSecs

So now next time you code, remember it to not access frequently in loops.

Lets talk about property access,

// Property in Loop Test
int pc = 10000000;
Console.WriteLine("Testing Direct Property Access");
Test(() => {
    Person p1 = new Person();
    for (int i = 0; i < pc; i++)
    {
        string v = p1.Name;
    }
});

Console.WriteLine("Testing Local Variable Access");
Test(() => {
    Person p1 = new Person();
    string t = p1.Name;
    for (int i = 0; i < pc; i++)
    {
        string v = t;
    }
});

In order to detect any noticeable difference, we have to loop for about 10 million times, however, in any usual code, you will be accessing 100s of properties, so it may make a good difference when you write code, which executes million times parallel.

Testing Direct Property Access

Time Difference 140.625 MilSecs

Testing Local Variable Access

Time Difference 46.875 MilSecs

Now based on the amount of free memory, and cpu speed, you might have to configure the number of iterations up and down to get a good noticeable effect of two different ways.

I can clearly see the difference, remember on normal piece of code, you will be accessing over 10 to 100s of properties again and again.

Click on Caching Stats Visual Studio Project to download and test by yourself.

  • Share/Bookmark
Tagged with:  

Day and Night time format

On March 7, 2009, in Business, Technology, by Akash Kava

Conventional AM/PM time format is very confusing. At NeuroSpeech we decided to use new format to distinguish visually the day and night format. Rules are as follow,

1. Day time is considered between morning 6 to evening 5.59 as assuming range of average sun shined day.

2. Night time is considered as 6 of evening till 5.59 of next day morning.

Representations:

Print and computer

White background:

1. Day time should be written with black box around the time and white background inside the box with black text color.

2. Night time should be written as black background of text with white color text. No border.

Black Background

1. Day time should be written as white background with black as text color with no background. No border.

2. Night time should be written as white border around the white color text.

Handwritten Format:

1. Day time should be written as normal dark ink color.

2. Night time should be written as normal dark ink color with a border around it.

  • Share/Bookmark
Tagged with:  

Second Ringtone

On December 14, 2008, in Music, by Akash Kava

I guess I am still learning and trying to master music, I can only create small bits and pieces only in music yet so thats why name “Ringtone” because this music is practically not useful for anything else.

This was made with progression “1 3 4 2 1″.

I just chosen a random progression to begin with, I am still searching for some way to learn and understand progression much at depth in order to create good music.

Glass 2 Ringtone

Feel free to download and use it.

  • Share/Bookmark