ASP.Net browsing by category


Unexpected consequence of Environment Variable change

Saturday, April 16th, 2016

While working on an Azure-bounded .Net project today, I ran into some error that required me to shorten the temp folder path. So I went ahead and changed the default user environment variable value from %USERPROFILE%\AppData\Local\Temp to C:\App\Temp. But before I made the change, I forgot to create the physical path C:\App\Temp first; not sure this is a Windows 10 bug – when I saved the change, the system environment variable editor just let me do it without checking if the path already existed. I strongly believe this should be part of Windows Environment Variables Editor’s enhanced feature to stop user from saving if the path does not exist.

This small omission turned out to be a huge problem – since the temp folder path: C:\App\Temp did not actually exist, it led to all kinds of weird behaviors as listed below:

  • My Visual Studio 2015 would not compile any project
  • My OneNote 2016 suddenly stopped working
  • When I tried to re-install VS 2015 or any program, it would just go into limbo – nothing happened
  • And I could not uninstall any program from the Programs list.
  • All these strange and frustrated Windows behaviors logged no errors into the Event Log so there was no much to go about and find answers by Google search.

Sure, I knew all these bad things were caused by the change of Temp file path, so I quickly restored the original settings – but that did not make these weirdness disappear.

While I was almost at the point to submit a HelpDesk ticket to have IT rebuild my machine, my director came to rescue – he suggested I change the Temp file path again to something like C:\Temp but this time we made sure I create the folder C:\Temp first. Well, after that and a reboot of my machine, everything came back normal and functional as expected.

So, two things worth shouting out loud:

  • Never never change the Windows Environment Variable to point to a path that has not been created yet.
  • For Windows 10 developer, PLEASE PLEASE include some Path.Exist() checking to prevent user from saving the change if the path does not exist yet. Such a simple feature enhancement could play a huge role in enlightening one’s Windows life.



Fixing error “ attempt was made to load a program with an incorrect format.”

Tuesday, April 14th, 2015

For a few hours I had been struggling with this error message when I tried to launch a WCF service (MyProductService.svc) from IIS7 hosted site:

Could not load file or assembly 'SomeExistingDotNetAssembly' or one of its dependencies. An attempt was made to load a program with an incorrect format.

The assembly was not built on my 64-bit machine initially so I suspected there must be something to do with that. After many failed internet searches, I decided to search for the detail error message below:

System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12857578
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503
   System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +148
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +172
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151


And that finally got me to a post from Stackoverflow which had these sacred words in it:

 Bad Image Format Exception usually means you tried to load a x64 Assembly / native DLL into an 32Bit process or vice versa a 32Bit Assembly into an x64 Process.

I felt I was close to hitting the jackpot! Then another user’s comment on IIS Application Pool setting settled the win for me:

 ...go into your IIS 7 manager console, find the application pool your app is running in, right-click on it, go to Advanced Settings, and change the Enable 32-bit Applications setting to true

And that was all it take to clear my error; after that change on the Application Pool, I clicked my “MyProductService.svc” again and now it rendered the wsdl xml nice and clean.

I am so grateful to these folks who shared and spent time to answer questions. So I reminded myself to do the same whenever I could.

Simplified process of creating and publishing nuget package to local host

Monday, March 9th, 2015

The simplified steps to pack and publish nuget packages to local host:

Add NuGet executable path to system variables:

  • Opened Properties page of Computer and click on Advanced System Settings and select Environment Variables
  • Highlight the Path under System Variables and click on Edit
  • Located the folder where the Nuget.exe is located, in this case, C:\Program Files (x86)\NuGet\Visual Studio 2012 and add this path to the Variable value – separated by semi-colon;
  • Need to re-start the computer in order for this to take effect.

 Package the libraries that are to be published to the server:

    • Launch the Developer Command Prompt for VS2012 and browse to the folder where the project file is located; in this case G:\Development\Tryout\NugetServer\Demo.Nuget.Lib>
    • Run command nuget spec to create the .nuspec file first:
      G:\Development\Tryout\NugetServer\Demo.Nuget.Lib>nuget spec -f Demo.Nuget.Lib.cs
      Created 'Demo.Nuget.Lib.nuspec' successfully.

      use -f to force overwrite if the .nuspec file already exists.

    • Open the .nuspec file and remove these entries from the file for now:
      <tags>Tag1 Tag2</tags>

      and make sure also change the text of releaseNotes to something other than the default; if you don’t to this, you will get an annoying warning message asking you to change.

    • Then run nuget pack command:
      G:\Development\Tryout\NugetServer\Demo.Nuget.Lib>nuget pack Demo.Nuget.Lib.cspro
      j -includeReferencedProjects
      Attempting to build package from 'Demo.Nuget.Lib.csproj'.
      Packing files from 'G:\Development\Tryout\NugetServer\Demo.Nuget.Lib\bin\Debug'.
      Using 'Demo.Nuget.Lib.nuspec' for metadata.
      Successfully created package 'G:\Development\Tryout\NugetServer\Demo.Nuget.Lib\D

Publish the package to local server:

      • Finally, do a push to publish to localhost:
        G:\Development\Tryout\NugetServer\Demo.Nuget.Lib>nuget push Demo.Nuget.Lib.1.0.0
        .2.nupkg -s http://localhost:{portnumber if not default 80, for example 8090 was what I used} {api key this has to be obtained from}
        Pushing Demo.Nuget.Lib to 'http://localhost:8099'...
        Your package was pushed.
      • The local server was previously setup by following this article at

Consume the packages from the local Nuget Server:

Now that the package are published to the local server, here are the steps to consume it from inside a Visual Studio 2012 solution:

  • Added a Console project “Demo.Nuget.Consumer”
  • Go to Tools->Nuget Package Manager->Manager Nuget Packages for Solution
  • Click on Setting on the lower left corner and select Package Sources under the Package Manager from the Options pane on the left; click on the “+” sign to add a new package source
  • Type in the Source text box the local Nuget server url that was used in the publishing process, and add nuget at the end, for example in this case :http://localhost:8099/nuget
  • Once the Package source is added, then all the .nupkg files in the Packages folder on the server will be displayed on the “Manage NuGet Packages” screen and ready to be installed to the solution.
  • To make more packed assemblies to be available to the source, just simply copy the desired .nupkg file(s) to the Packages folder on the server and they will automatically show up for your solution.


How to clear the error “ExtensionlessUrlHandler-Integrated-4.0″ has a bad module “ManagedPipelineHandler” in its module list

Monday, December 22nd, 2014

Started with another MVC4 web application that requires Https today and got this error when I tried to browsed the app from local IIS 7:

ExtensionlessUrlHandler-Integrated-4.0″ has a bad module “ManagedPipelineHandler” in its module list

Thanks to this post at and followed the instruction to run
regiis, I was able to clear this error and successfully browsed to the local site’s landing page. Here were what I went through (I was on a Win7 x64 bit machine):

  1. All Programs -> Visual Studio 2012 -> Visual Studio Tools
  2. Right clicked on the “Developer Command Prompt for VS2012″ selected “Run as administrator“; this was a must or the next step would not be executed.
  3. Went to directory at C:\Windows\Microsoft.NET\Framework64\v4.0.30319 and ran this command line: aspnet_regiis.exe -i
  4. The whole thing should look like this after done:
    C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
    Microsoft (R) ASP.NET RegIIS version 4.0.30319.18408
    Administration utility to install and uninstall ASP.NET on the local machine.
    Copyright (C) Microsoft Corporation.  All rights reserved.
    Start installing ASP.NET (4.0.30319.18408).
    Finished installing ASP.NET (4.0.30319.18408).
  5. After that, I went back to IIS and re-started the website (which was assigned to a port 44300 for https) then browsed to the landing page and now everything looked pretty.

Observations: @Html.EditorFor and @Html.TextBoxFor in MVC4

Monday, November 24th, 2014

A few tricks learned today when I was working on a email template manager project:

1) If an Action method was marked as [HttpPost] to handle the post event from a form, then there must be a same name Action without [HttpPost] attribute existing in the same controller or you will get a “Page cannot be displayed” error and there was very little debug info to go about.

For example, I have

public ActionResult FileUpload(EmailTemplateModel model)
{ //doing files upload }
then I must have a plain action with same name but different signature:

public ActionResult FileUpload()
EmailTemplateModel model = new EmailTemplateModel();

model.Attachments= PrepareAttachmentNewModel();

return View(model);


or I will get “Page cannot be displayed” error when I try to submit the form with one or multiple “file” html element.

2) Interestingly, when I return the model to view, only when I used @Html.EditorFor, I will be able to render the properties related to the file upload into each textbox; but then the other textboxes will become empty for those fields that were are already there on the form prior to posting the form. Instead, using @Html.TextBoxFor() will retain those values.

Have yet to understand the mechanism underneath, but for now these are my observations and just a quick note first.

Simple fix to error: “Newtonsoft.Json.Serialization.DefaultContractResolver.set_IgnoreSerializableAttribute(Boolean)”

Friday, October 17th, 2014

After installing SQL Server 2012 and took out SQL server 2008 on local machine last week, today it was first time I tried to load the ..DS.Admin.Web project on local machine and when rendering the Home/Index page, got this error first:

System.MissingMethodException was unhandled by user code

Message=Method not found: 'Void Newtonsoft.Json.Serialization.DefaultContractResolver.set_IgnoreSerializableAttribute(Boolean)'.
.Web.Admin\Global.asax.cs:line 22

Searched the error “Void Newtonsoft.Json.Serialization.DefaultContractResolver.set_IgnoreSerializableAttribute(Boolean)” and led to this post:

So, I first tried this:

Install-Package Newtonsoft.Json –IncludePrerelease
PM> Install-Package Newtonsoft.Json –IncludePrerelease
'Newtonsoft.Json 6.0.5' already installed.
Successfully removed 'Newtonsoft.Json 4.5.1' from Corestream.PPDS.Web.Admin.
Successfully added 'Newtonsoft.Json 6.0.5' to Corestream.PPDS.Web.Admin.

But that led to a different message:

Could not load file or assembly 'Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition d
downloaded 3.5 from and copied the Newtonsoft.json.dll to

Thought it might be that I needed to go back to older version of newsoft.json.dll as I am developing this project in VS2010 while some other projects in VS2012; so I went to Newtonsoft site to download the 3.5 version, based on some advice given online. Did that and set the project reference to point to the Newtonsoft.Josn.dll 3.5 version. Not that was not it, still got error about assembly mismatch. Did some more search and found some even suggested removing Newtonsoft.json.dll from GAC. It proved that was nonsense as when I ran this:

Windows+R and typed assembly

The Newtonsoft assembly does not even show up – it is not in GAC, at least for my machine.

Then I tried another smart advice and added this entry to web.config:

<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="" newVersion="" />

Well, only bit further, this time got this error:

System.IO.FileLoadException was unhandled by user code
Message=Could not load file or assembly 'Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
FileName=Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed

Well, finally, I realized the best and the simplest solution to this is well under my own nose and I cursed myself for wasting so much time on wandering around on the wild web – so here come the real deal that got me out of this hole:

“The Best Solution is the Simplest Solution” – it proved true again: 

  • Started a brand new project in VS2010 and chose MVC4/Internet Application template as project type.
  • After the project compiled and flied smoothly, rendering that nice Home page that has been missing for hours from me, I checked the project’s references and noticed that now it pointed to a 4.5.6 version of Newtonsoft.Json.dll, instead of 4.5.1 or 4.5.0 that I used in the troubled project. This is in the new project’s packages folder.
  • So I just went back to the troubling project and changed the reference to point to here at this 4.5.6 version that was brought in with the mighty MVC4/Internet Application wizard for my dummy project, and as I expected, everything just went back to normal and it ended my Friday afternoon on a happier note.

How to connect to BizTalk Management database (BizTalkMgmtDb) via BizTalk API?

Friday, September 12th, 2014

When calling Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer.ConnectionString and assigned it a connection string like
“Data Source=sqlservernameorIP;initial catalog=BizTalkMgmtDb;user id=userid;password=pwd;” providerName=”System.Data.SqlClient”

I would get an error even I know the credential is correct and the SQL Server is setup with Mixed mode so it will take both SQL server authentication and Windows Authentication:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.

With the same user credential, I can connect to other database on the same server if I don’t use BizTalk API call. That indicates that the BizTalk API only accept Windows authenticated domain user account.

Then, how will I pass a domain user account through web?
1) Go to IIS where the web application is hosed.
2) Select the ApplicationPool for the app and click on Advanced Settings
3) Select Identity and change it to use Custom Account (from Built in Account). Click on Set and enter a domain account; you must enter the domain name such as TGIF\syang; this domain account must exist and must have proper access to the server where the BizTalk database resides.
4) If the domain account has not been given proper access to the BizTalkMgmtDb, now it is time to go to the database server, expand the Security folder then select the Logins. Add TGIF\syang to Logins as new user if it is not already there.
5) Then you must make sure the user is mapped to the database with proper role. This is done by clicking on User Mapping page after you bring up the user’s Properties. Select the BizTalkMgmtDb database by checking the Map box, then in the “Database role membership” window below, check BTS_Admin_Users.

Then, is it true that the connection string with a sql server user account no longer needed?
No, it is still needed. After I made the changes in IIS and was able to connect to the BizTalk Explorer, I intentionally passed in an invalid userid to the sql server connection string as in [“”Data Source=sqlservernameorIP;initial catalog=BizTalkMgmtDb;user id=userid;password=pwd;” providerName=”System.Data.SqlClient”], immediately, I got an error from BizTalk API call where it initializes the connection to BizTalkMgmtDb.

So, in summary, BizTalk Explorer API requires:
1) An authenticated and authorized Windows domain account to access its management database (where information like Receive Locations, Ports, etc reside)
2)If the application is a web application hosted in IIS, IIS Application Pool must be setup using Custom Account instead of the default Built-in Account
3)When passing in a SQL server connection string, this connection must be set to use Integrated Security or SQL server authentication with a user that is grant proper access. If using SQL Server authentication, steps 1 and 2) are still needed.

The bad (might be good to some) attribute introduced in MVC4 – [InitializeSimpleMembership]

Thursday, August 21st, 2014

Yesterday I deployed a MVC4 app to Winhost and got this error below when I clicked on “Log In” or “Register”, which I didn’t when deployed to local IIS.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

I had seen such error before; mostly the error was due to some misspelled SQL server name or firewall blocking remote access, etc. I checked my SQL server connection strings for both SqlClient and Entities Framework model and were able to connect to the remote SQL db hosted at Winhost. When I submitted a support ticket to Winhost tech team, their server side log showed that my app tried to connect to a SQL Express instance which they don’t support. How strange was that? I do not use SQL Express and my database which contains the ASP.Net Membership objects resides on a full version local SQL Server, not Express. There is no place in my web.config that has anything to do with SQL Express instance. So I examined the Controller codes where the Log In link is clicked; here it was, the new “InitializeSimpleMembership” attribute on the AccountController class which was created automatically by my selecting the “Internet Application” MVC4 project template. This was something new introduced by MVC4 team at Microsoft, where a bunch of genius are always trying to come up with some dummy robot codes to  make everything so automatic – by “simply” looking for a SQL Express db to initiate the Membership provider for Web.Security; this “InitializeSimpleMembership” attribute, as it turns out, was the only culprit for all these non-simple headaches when you deploy your site to hosting server that usually do not support SQL Express. And there was no warning or error when I used the Publishing wizard from VS2012 to deploy the site to Winhost.

The fix? Simply commented out the attribute, as shown below,and re-deployed to Winhost; then everything works!


    public class AccountController : Controller
        // GET: /Account/Login

        public ActionResult Login(string returnUrl)
            ViewBag.ReturnUrl = returnUrl;
            return View();

Fix for ASP.Net webform postback error, “..Operation is not valid due to the current state of the object”

Wednesday, November 13th, 2013

Got this error sometimes ago and, today in another application, it appeared again. This occurred when I had a relatively large number of rows of data to be posted back in a web form, said, 178 rows, in this case. Before the Postback event handler even got hit, the IIS already complained and threw this at me:

DotNetNuke.Services.Exceptions.PageLoadException: Operation is not valid due to the current state of the object. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object. at System.Web.HttpRequest.FillInFormCollection() at System.Web.HttpRequest.get_Form() at System.Web.HttpRequest.get_HasForm() at System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) at System.Web.UI.Page.DeterminePostBackMode() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --

There was no much explicit information to derive more useful details from; but it is obvious that this must have something do with the number of data post back to server since in an earlier upload, with rows less than 30, the same Postback event did not have any problem. I remembered last year I had done some research on this issue after I got this error first time while posting back a large data grid, so I dug out that application’s web.config file, and copied one line from that file and pasted it to the AppSettings in the web.config under the DotNetNuke portal root (where my app was running as a Module), and that fixed the Postback error. This time, I want to share this out loud and also it will help myself in search for solution if I will encounter the same issue again later.

So all I had to do was to add this line anywhere in the appSettings section in a web.config that is in the root of the website:

 <add key=”aspnet:MaxHttpCollectionKeys” value=”1000″/>

The number here is the maximum number of rows of a server data-bind control such as a GridView or a Repeater control. In general, however, it is not a very good practice to have a large number of rows post back over wire and that’s probably why IIS has this implicit cap on this at first place.

Manually added Elmah to a deployed Asp.Net website

Tuesday, June 18th, 2013

Sometimes I found that it was frustrating to not know what exception detail was when an exception was thrown from a production website. At that point, the all-mighty Elmah error logging and exception handling plug-in came to my mind. But all my previous Elmah plug-in was added during web project development and deployed along with the project to hosting server. How to go about plugging in an Elmah when my website is already up there and running? Here were the steps I went through the other day to accomplish exactly that:

  1. Downloaded the elmah sql script file from and executed it against the sql database ProdDB on the host. It went through and created the Elmah_Error table and related stored procs inside ProdDB database
  2. Now let’s manually add elmah.dll and configure the web.config to register elmah.
  3. Copied elmah.dll from one of my old projects that had Elmah already working to the target bin folder.
  4. Added to <configuration><configSections> the following:
    <sectionGroup name="elmah"><section name="security" type="Elmah.SecuritySectionHandler, Elmah" />
    <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
    <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" /></sectionGroup>
  5. Added to <httpHandlers>:
    <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
  6. Added to <httpModules>:
    <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
    <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
    <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
  7. Added <elmah> to <configuration> right after </system.web> and before <>
    <!--<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/App_Data/Errors" />-->
    <errorLog applicationName="AppName" connectionStringName="connToProdDb" type="Elmah.SqlErrorLog, Elmah" />
    <errorMail subject="Website error via Elmah" to="" from="" aysnc="true" />
    <security allowRemoteAccess="no" />
  8. Last, but not least, in order to get the alert email sent out automatically to me, I needed to add the SMTP parameters to the mailSettings section in the <>
    <smtp deliveryMethod="Network">
    <network host="" userName="" password="password" port="numberthatworks" />

    (there was no <>, so just created one)

  9. Added the following right after </> and before <system.webserver>
    <!--deny annonymous access to error log-->
    <location path="elmah.axd">
    <allow users="*"/>
    <!--<deny users="?" />-->
  10. Added to <system.webserver><modules>:
    <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
    <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
    <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
  11. Added to <system.webserver><handlers>
    <add name="Elmah" path="elmah.axd" verb="POST,GET,HEAD" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
  12. Finally, it is completed! Now browsed to the site and manually generated some errors; immediately, I got an email alert; then I browsed to the elmah.axd, and it also rendered all the errors in a tabulated format nice and neat. Of course, more detail info is obtained by clicking on the detail link and you will be surprised how much exception stack trace has been caught.