.Net Framework

...now browsing by category


Used command line to turn on .Net framework 3.5 on Windows 10

Friday, January 15th, 2016

Steps taken to fix the “.net 3.5 not installed on Windows 10″ issue:
1. followed this blog at [http://www.kunal-chowdhury.com/2015/08/windows-10-dotnet-framework.html] and [http://www.kunal-chowdhury.com/2015/07/download-windows-10.html]
2. Downloaded the media creation tool *MediaCreationToolx64.exe*
3. Ran the .exe and chose the 2nd option for creating installation file then select the ISO file and saved to c:\Documents\Windows.iso; it took more than 1 hour to download and created the .iso image for Windows 10
4. After the windows.iso was created on C:\..\Documents, right clicked on the .iso file and mounted to E: drive
5. Executed command:  DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:E:\sources\sxs

Microsoft Windows [Version 10.0.10586]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:E:\sources\sxs

Output indicates this finally succeeded:

Deployment Image Servicing and Management tool
Version: 10.0.10586.0

Image Version: 10.0.10586.0

Enabling feature(s)
The operation completed successfully.


6. Went back to the Windows Features On/Off and now the .Net Framework 3.5 checkbox is checked, which meant that the .net 3.5 is now installed on my Windows 10 machine.

Fixing error “..an 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 Nuget.org}
        Pushing Demo.Nuget.Lib to 'http://localhost:8099'...
        Your package was pushed.
      • The local server was previously setup by following this article at https://docs.nuget.org/create/hosting-your-own-nuget-feeds

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.


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 http://json.codeplex.com/releases/view/50552 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.

good reference on abstract class vs interface

Friday, August 29th, 2014

This reading really makes it crystal clear about the similarity and difference between an abstract class and an interface http://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx and it is easy to read. Here are the key points I took away from this casual reading:

  • Abstract class and interface both are to be inherited to be useful – this is one similarity.
  • The differences are many:
    • One subclass can inherit only one abstract class but can multiple interfaces or one base class + one or more interfaces.
    • Abstract class can have implementations but Interface does not have implementation.So if you want to have complete control of how a method is implemented, you build an abstract class to include it; otherwise, use interface to allow the inheriting class (subclass) to implement their own; in this sense, an abstract method in an abstract class is acting like a public method in an interface – they both must be implemented or overriden in a subclass.
    • An interface can be passed as an argument or initiated as an object such as:
       void GetEmailTemplate(ITemplate t) 
                     { //implementation ;
       or  void SaveEmailTemplate()
             IEmailTemplate t=new EmailTemplateClassThatInheritTheInterface(); 

      But an abstract class has no such freedom.

    • Interface has no knowledge and control of how its contract methods will be implemented; only thing for sure is all its public methods must be implemented in the subclass. If viewing the interface as a universally observed law – “crimes must be punished”, then while different countries must enforce the punishment but implementation of punishment can vary greatly, such as Singapore can canning you for spitting on street while other country just jails you even you murdered people, like in US.
  • So, in designing a solution, if I want to have some control over certain core operations of the classes, I would wrap those base methods with my desired implementations in an Abstract class so all the subclasses inheriting from it will automatically have my implementations, no kidding around.
  • And if I want to allow certain methods to be implemented in a subclass that I don’t give a damn, then I will add a few virtual methods in my abstract class – that give me some of those Interface power and flexibility; virtual can have some basic implementation for subclass to override with its own implementation or use directly without second thought.
  • Another concept is an Abstract method, what about that? Well, think this way, you want to force a subclass that inherits your abstract class to behave like inheriting from an interface (but you don’t want to use an interface because you want to have a tight grip on certain base implementations), what will you do? Yes, an abstract method – there is no implementation in base class but subclass must override it with its own implementation.




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();

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 https://code.google.com/p/elmah/downloads/detail?name=ELMAH-1.2-db-SQLServer.sql&can=2&q= 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 <system.net>
    <!--<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="stevey@yangsoft.com" from="webmaster@yangsoft.com" 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 <system.net>
    <smtp deliveryMethod="Network">
    <network host="mail.domainname.com" userName="webmaster@domainname.com" password="password" port="numberthatworks" />

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

  9. Added the following right after </system.net> 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.

What is this error, “Uncaught SyntaxError: Unexpected token o”?

Wednesday, June 5th, 2013

It seemed that from time to time, we ran into this error “Uncaught SyntaxError: Unexpected token o“. Without more specific info, sometimes this can be very frustrating.

As matter of fact, this error was simply a result of sloppy coding in creating a JSON string that was not parsed correctly. Tracked down to the piece of code where error was thrown – it occurred where JSON.Parse was called. If the string s passed into the JSON.Parse(s)  is not properly formatted JSON string, the above error is thrown. In the sample code snipe below, r is a json string returned from a AJAX call from C# code; if I called JSON.parse(r), I would get the “Uncaught SyntaxError: Unexpected token o” error; and if r is not properly formatted, I also got the same error. Correct way to parse the returned json string is to call JSON.parse(r.d), instead of JSON.parse(r). I also tried to call JSON.parse(r.responseText), as it worked with the the xhr returned in the error function, but I got a different error, “Uncaught SyntaxError: Unexpected token u“, very interesting. Only r.d worked! Who came up with such super terse object name?!!


function fetchEmployer(code) {

        var account = null;
        var url = "<%=AjaxPath%>/GetEmployer";
        var json = JSON.stringify({EmployerCode: code});

            type: "POST",
            url: url,
            data: json,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (r) {
                account= JSON.parse(r.d); //the error will be thrown if you just parse r instead of r.d

            error: function (xhr, ajaxOptions, thrownError) {
                   if (xhr != null) {

                    var err = JSON.parse(xhr.responseText); //you can throw a code-behinde Exception and it will automatically                                                 //render to a valid JSON string when we rerieve the responseText
                    alert("ErrorMessage: " + err.Message + " StackTrace: " + err.StackTrace);


        return account;


Error while running PM>install-package MSBuildTasks

Thursday, March 14th, 2013

Got this error today while trying to install MSBuildTasks for a DNN Module development project and used NuGet:
install-Package : Method invocation failed because [NuGetConsole.Host.PowerShell.Implementation.PSTypeWrapper]
doesn’t contain a method named ‘AddFromFile’.”

I copied this error message to Google and found no match. After some digging, with portion of error words, found some tips linking to the fact that NuGet might need a face-lift. So I went back to VS2010 project, uninstalled the NuGet and re-installed it. Then run PM>install-package MSBuildTasks again, it went through with not error.

Hopefully this tip will be picked up next time someone would run into the same error message I got here.