Posts

Showing posts from 2014

Great article on enabling cross origin requests in ASP.NET Web API 2

Useful to get the web api working on different URLs. http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

How to definitively get Web API working with MVC 5.2

I was having a lot of trouble getting web api to working with MVC 5.2 recently. This article definitely works: http://stackoverflow.com/questions/26067296/how-to-add-web-api-to-an-existing-asp-net-mvc-5-web-application-project 

Tutorial: Using Google Cloud Storage from C# and .NET

There is almost no samples or documentation available anywhere for this, so I thought I would write this up myself as using the storage from GCS (similar to Amazon S3 and Azure Blob Storage) is one of the most basic things which people do with the cloud. The very first thing to do after creating the C# project in Visual Studio is to install the Nuget package mentioned here: https://www.nuget.org/packages/Google.Apis.Storage.v1/ There is a lot of confusion with multiple packages available, but this is what you want for GCS. Install-Package Google.Apis.Storage.v1 You are going to need to reference the following namespaces: using Google.Apis.Auth.OAuth2; using Google.Apis.Storage.v1; Setup the basic items you need for making the calls: private static ClientSecrets _clientSecrets = new ClientSecrets();         private static UserCredential _userCredential = null;         private static StorageService _storageService = new StorageService();         private const string

How to read the web responses from the results of the Amazon .NET API

Modify the source code to get this ability: AWSSDK_DotNet35\Amazon.Runtime\ AmazonWebServiceResponse .cs - Add a property to hold the HttpWebResponse object. awssdk_dotnet35\amazon.runtime\internal\transform\ httpwebrequestresponsedata .cs - Add a property to hold the HttpWebResponse object. AWSSDK_DotNet35\Amazon.Runtime\Internal\Transform\ IWebResponseData .cs - Add a property to hold the HttpWebResponse object. There are a series of classes which transfer the data from the internal objects to the output objects within the API: awssdk_dotnet35\amazon.s3\model\internal\marshalltransformations\ deleteobjectresponseunmarshaller .cs private static void UnmarshallResult (XmlUnmarshallerContext context,DeleteObjectResponse response) awssdk_dotnet35\amazon.s3\model\internal\marshalltransformations\ putobjectresponseunmarshaller .cs private static void UnmarshallResult (XmlUnmarshallerContext context,PutObjectResponse response) awssdk_dotnet35\amazon.s3\model\internal\m

How to enable setting the request headers for Get and Delete in Amazon SDK for .NET

From the source code, modify the below files: AWSSDK_DotNet35\Amazon.S3\Model\Internal\MarshallTransformations\GetObjectRequestMarshaller.cs AWSSDK_DotNet35\Amazon.S3\Model\Internal\MarshallTransformations\DeleteObjectRequestMarshaller.cs Modify the public IRequest Marshall (<parameter>) method by adding the below statements: var headers = <requestObject>.Headers; foreach (var key in headers.Keys)       request.Headers[key] = headers[key]; You will need to add the property for the headers to the classes (directly - not in their base classes): private HeadersCollection headersCollection = new HeadersCollection(); /// <summary>         /// The collection of headers for the request.         /// </summary>         public HeadersCollection Headers         {             get             {                 if (this.headersCollection == null)                     this.headersCollection = new HeadersCollection();                 return this.headersC

Getting around modifying the Amazon S3 SDK

It is useful to know the way around some of the code in the Amazon S3 SDK which are the main entry points. AWSSDK_DotNet35\Amazon.S3\ AmazonS3Client .cs – Contains the main entry points. This is the method where the HTTP request is made and the response is retrieved: AWSSDK_DotNet35\Amazon.Runtime\Pipeline\HttpHandler\ HttpWebRequestFactory .cs public virtual IWebResponseData GetResponse () This is the class which makes the HTTP request: AWSSDK_DotNet35\Amazon.Runtime\Pipeline\HttpHandler\ HttpHandler .cs public override void InvokeSync (IExecutionContext executionContext) This is the class where the ExecutionContext and its internal properties like RequestContext and ResponseContext are created: AWSSDK_DotNet35\Amazon.Runtime\ AmazonServiceClient .cs protected TResponse Invoke <TRequest, TResponse>(TRequest request, IMarshaller<IRequest, AmazonWebServiceRequest> marshaller, ResponseUnmarshaller unmarshaller) where TRequest: AmazonWebServiceRequest

Is there anyway to programmatically handle Amazon S3 RequestTimeTooSkewed error without changing the local clock?

This is the solution. I had to figure it out myself: https://stackoverflow.com/questions/27367405/is-there-anyway-to-programmatically-handle-s3-requesttimetooskewed-error-without/27388502#27388502

Unable to connect to 3G network on Airtel?

I am traveling in India and even though I got a 3G data plan, I was unable to use the 3G network no matter what I tried. Turns out in my area, Airtel does not provide 3G service, but Idea provides 3G service for Airtel. So, I had to manually select IDEA from my carrier list and then it showed up as Airtel network with 3G.

Windows Update not working

For me this was happening due to hard disk corruption in my SAN. This was a VM whose hard disk was on the SAN. To fix it, I used: http://support.microsoft.com/kb/2509997 Method 4

Windows 8.1 hyper-v does not support Windows 7 as a Guest OS with a Gen 2 VM

I was stuck on this since last week. http://blogs.technet.com/b/jhoward/archive/2013/11/04/hyper-v-generation-2-virtual-machines-part-7.aspx Q: Why don’t we support 64-bit Windows 7 or Windows Server 2008 R2 as a guest operating system in generation 2 virtual machines? A: Certainly it is true that Windows 7 support UEFI, the first requirement for generation 2 virtual machines. However, Windows 7 has a hardware dependency on a Programmable Interrupt Controller (PIC) which is not present in generation 2 virtual machines. Even if Secure Boot is disabled, an attempt to install Windows 7 will result in an apparent hang at “Starting Windows” shortly after boot, consuming 100% VP utilisation. A similar effect to this will be seen if attempting a network install from a WDS server which has a Windows 7 era boot PE image – network boot will appear to hang as well. For that reason (along with the keyboard issue in Windows 8 PE) I strongly recommend any WDS server are upgraded to th

How to use IgnoreResourceNotFoundException with the latest Azure SDK Version and System.Data.Services.Client

It will ask you to add another dll which conflicts with this one. To resolve this problem, you need to add the other dll and use the steps mentioned here to give it an alias so that both dlls can be referenced without conflicting with each other: http://blogs.msdn.com/b/ansonh/archive/2006/09/27/774692.aspx Nobody else gives you a straight answer of how to do this.

This tip just saved me hours of debugging

Got a used macbook pro 13 late 2010 model, was trying to install mavericks from usb - failed with weird error cannot be verified. Did the below to get it to work: http://blog.mconserv.net/2013/10/install-os-x-mavericks-application-cant.html

How to return a custom object in an AJAX call when the server is MVC ASP.NET

This is not straightforward if you are new to MVC. For this, you need to reference Json.NET from the package manager. http://stackoverflow.com/questions/10869724/return-multiple-objects-using-json-net

Visual studio hangs with refactor enabled on super specd PC

My PC is an extremely new dell workstation with 16GB RAM and Intel Xeon Core i7 CPU. It was dog slow. No idea why - turns out to be the video card. Replaced it with a $60 year old video card with 1GB RAM - super speedy now. Visual Studio does not hang with refactor enabled.

Troubleshooting Windows Update Issues

This can be done by: http://windows.microsoft.com/en-us/windows/windows-update-error-800b0100#1TC=windows-7

Windows Experience Scores in Windows 8.1

This is quite important to know, as it can tell you what is slowing down your system. http://www.cnet.com/how-to/find-your-windows-experience-index-scores-in-windows-8-1/

Windows VM very slow and hanging in VMWare environment?

This could be a disk corruption issue because you hard powered it off. This happens when you have an old OS like Windows 7 without SP1 and it is slow to begin with. Run chkdsk and all should be ok after that.

Program is running but not showing on the desktop?

This is a bad issue to have and I have Windows 8.1 and nothing worked but this: " Bring the troubled window to focus by clicking on it in the taskbar (or Alt+Tab). Now you can simply  hold the Windows key on your keyboard  and tap the arrow keys. With any luck, your missing window will snap back into view. " http://www.techspot.com/guides/226-bring-lost-window-back-desktop/

So your TPL Threads just die and no idea why?

Let us say you create a TPL thread which runs a loop inside. And you are processing a set number of items in the loop. If the processing takes time, on some servers I have observed that the thread dies after running for a very long time. And the process just enters a state where it does nothing and simply hangs on to memory. These VMs are old and slow, that could be part of the problem. To resolve this, add a time based check so that any loop won't run for more than half an hour (say). This fixed the problem for me. I was investigating this issue for months now.

Model on the data not the UI

I found an interesting idea today - this is something which most people do wrong in software. Sometimes we want to display information differently than what we have already shown on the screen - most developers just simple change the UI code directly to change the way it renders on the screen. This may not be the best approach to handle this situation. If the display is complex enough, it might be better to simply create a data structure of the same data, tuned to showing it in the different way. Then you just create the data structure, populate it and rendering it becomes easy. I used a similar technique in another more complex project as well. There data coming from disparate sources had to be shown in a unified manner in a grid. Rather than getting raw data and squeezing it to show the information directly on the screen - I developed a domain model which directly represented the generic model of the disparate data. Then the work of showing this on the UI became significantly

Great article on software..

http://arstechnica.com/information-technology/2014/04/how-has-an-increase-in-system-complexity-affected-new-programmers/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+arstechnica%2Findex+%28Ars+Technica+-+All+content%29

Optimize windows for programs or background services?

This is really a setting for a "quantum" a.k.a the amount of time a thread is permitted to run before it is pre-empted (not a problem for fibers). If you set it to programs/ applications it is a small value like 2 clock intervals. If you set it to background services, it is a large value like 12 clock intervals. The value for background services is larger and meant for server OS because throughput and performance are more important. Shorter quantums would mean more context switching and worse performance.

Difference between windows threads and fibers

You would have seen this from SQL Server preferences. This could have come with the .NET framework at some point in time, but they kept it separate. http://stackoverflow.com/questions/796217/what-is-the-difference-between-a-thread-and-a-fiber This link is mostly correct. But not fully correct though. Windows NT will interrupt threads so that multiple threads can execute at the same time - true. But this will not cause any problems in normal course because if that was the case, half the programs in the world would not work properly. In reality, it is able to easily manage swapping one thread from kernel to user mode and vice versa along with loading all the data to and from the registers without losing information. In the C++ world, you have a lot of control and can change lots of stuff all over the place which can cause problems and data corruption.

TFS 2012 and 2013 slower than older versions?

http://blogs.msdn.com/b/phkelley/archive/2013/05/29/server-workspaces-vs-local-workspaces.aspx - Just use the classic server workspace which is much faster if your projects have greater than 100K items.

The difference between native thread termination and managed thread abort

When the managed thread is aborted, an exception is introduced at the thread's current instruction pointer. This allows the finally blocks to execute as the thread winds down. The runtime is also aware of code that are performing non-interruptable operations like manipulating system state and so it will delay introducing the abort exception until a safe point has reached. Terminating a native thread does not free the user-mode stack. The thread can hold onto locks that after termination will remain in the acquired state. This thread could also have been modifying critical system state which gets corrupted when interrupted. If you terminate a native thread, you should probably be terminating the process as well.

Overwriting the same line on a C# Console

This is a good one which is very useful: for ( int i = 0 ; i < 100 ; ++ i ) { Console . Write ( "\r{0}" , i ); } http://stackoverflow.com/questions/888533/how-can-i-update-the-current-line-in-a-c-sharp-windows-console-app

How to handle application crash in code and do cleanup/ save state

AppDomain .CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; private   void  CurrentDomain_UnhandledException( object  sender,  UnhandledExceptionEventArgs  e)         {              Exception  ex = e.ExceptionObject  as   Exception ;              if  (ex !=  null )             {                  //Log error             }              if  (e.IsTerminating)             {                  Console .WriteLine( "The app is terminating because of an unhandled exception." );             }             CleanupTasks();         } Another thing - IsBackgroundThread is actually useful to just let the OS know that this thread will not keep the process alive. I.e., the process in windows terminates when the last non-background thread exits. So, if you have a non-background thread and it is running your process will remain running. Did you know that unlike native code, in .NET the finally area is executed even if the application crashes? - this only happen

PC slow for no reason?

I just found there is significant difference especially when running a server, if you change the power options from balanced to high performance. This is especially when your server is hyper-v and has VMs.

jQuery Mobile ASP.NET Gotcha

I have been working on jQuery Mobile recently. Specifically the feature where new pages are loaded in the background via AJAX calls. It is tricky to get everything working properly with ASP.NET AJAX and multiple ASP.NET pages. The point to remember is that jQuery Mobile "pages" are really the areas we mark as page in the HTML. So, when it loads the next "page" in the background, you don't get what you would normally expect - i.e., you only get the stuff inside the jQuery Mobile page. What this means is that: 1. All Javascript files have to be referenced in all pages. 2. All web service ASP.NET references have to be referenced in all pages. 3. Make sure that Javascript used for one page does not clash with that of other pages. When I was initially working on the pages, why something did not work simply made no sense. Then it started making sense in an intuitive manner which I liked a lot.

Metro Apps not Working? - No wonder nobody likes Windows 8

Took months for them to come out with this workaround: http://social.technet.microsoft.com/Forums/windows/en-US/6f119828-dd1b-42da-b8b5-c6e6c0d5617c/no-apps-or-windows-store-work-after-upgrading-to-windows-81-enterprise?forum=w8itproinstall As I had to do this all over again, here are the steps: The following finally fixed all issues for me (Store and all apps broken with black X, can't access PC Settings): 1) Fixing the app store:   1. Open registry editor typing regedit.exe from a command line.   2. Browse to the registry key at HKEY_CURRENT_USER\Software\Classes\Local Settings\software\microsoft\windows\currentversion\appmodel\repository\packages.   3. Right click on the “packages” key and bring up the “Permissions” tab.   4. Click the “Advanced” button located at the bottom right corner.   5. Check to see the account name that shows up as the “Owner” (this is the first line of text on the “advanced security settings” dialog for the “packages” key). It should say

Using jQuery Mobile with ASP.NET generating Javascript on server

If you are using jQuery Mobile which does downloads the next page via AJAX instead of via the browser, note that the Javascript still runs within the scope of the first page you loaded. So, use different variable names for the JS for different pages, and also the script which gets generated into the web page needs to go into the jQuery Mobile header, footer or content - otherwise it will not get loaded when the AJAX call retrieves the next page. I really like jQuery Mobile a lot because it takes away the pain of building mobile UIs in HTML5 [Update] I have been trying to debug a very difficult issue for the past few days and yesterday night I finally figured out - the reason why my AJAX call was not updating the content list on a different page than what I initially loaded is because each page needs to have content lists with different ids. If the ids are the same, then the code to clear and add items to the content list do not go to the correct content list.

Use Linq to update items in a list without using a for loop!

class   Program     {          public   class   MyEntity           {              public   int  property1;              public   int  property2;              public   int  property3;         }          static   void  Main( string [] args)         {              List < MyEntity > entities =  new   List < MyEntity >();             entities.Add( new   MyEntity () { property1 = 1 });             entities.Add( new   MyEntity () { property1 = 1 });             entities.Add( new   MyEntity () { property1 = 1 });             entities.Add( new   MyEntity () { property1 = 1 });             entities.ForEach(p => p.property1 = 2);              Console .ReadLine();         }     } Also, to make a select call without using for syntax: List < MyEntity > filter = entities.Where(p => p.property1 == 2).ToList(); Where and Select without using for syntax: list.Where(p => p.Property1 == value).Select(p => p.Property2Name).FirstOrDefault()

Showing rows in reverse chronological order using Windows Azure Table Storage a.k.a order by descending

We can set the RowKey to be a fixed length string equivalent of DateTime.MaxValue.Ticks -  DateTime.UtcNow.Ticks. This allows the RowKey to sort the items by an offsetted time from newest items to older items. string rowKeyToUse = string.Format("{0:D19}",  DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks); This works because when you move ahead in time, DateTime.UtcNow.Ticks increases in value - thereby the difference between max value and this value decreases - hence these rows will go to the top. let us assume that a blog can be rated from 0-5 and we want to ensure that blogs are listed such that they are sorted by   (Rating   in desc order, Created time in desc order).    This means that they are storted first by rating, and then sorted within each rating by the created time.     Here we can set the row key to <Rating>+<Ticks to force items to be sorted from newest to older items>. So taking the same example as above, in the two blogs above, let us assume