Unexpected consequence of Environment Variable change

Written by stevey on 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.

 

 

 

Table variable vs tamp table in a T-SQL transaction

Written by stevey on March 6th, 2016

There are plenty of posts out there talking about the differences and disadvantages/advantages of using table variable vs temp table in a T-SQL query. The one thing I wanted to illustrate here is the difference on how they behave when a transaction rollback is involved. In short, transaction involving a table variable cannot be rollback whereas in a temp table it can. Here are two examples I tried to prove that:

Example 1 – in-memory table variable

declare @tranTest table (rowId int identity(1,1), rowVal tinyint)

begin try
begin transaction

insert into @tranTest (rowVal) values (200)
insert into @tranTest (rowVal) values (240)
insert into @tranTest (rowVal) values (256)

commit transaction

end try

begin catch
declare @errorMsg nvarchar(4000), @errorSeverity int, @errorState int;

select
@errorMsg=ERROR_MESSAGE(), @errorSeverity=ERROR_SEVERITY(), @errorState=ERROR_STATE();

raiserror (@errorMsg, @errorSeverity, @errorState);
rollback transaction;
end catch
set nocount on
select * from @tranTest

As the tinyint can only holds integer up to 255, inserting 256 throws an exception; since all three inserts are in a transaction, naturally I thought that select statement from @tranTest would return no records; but I was wrong! Actually, it returned:

rowId rowVal
1 200
2 240

Example 2: transaction in temp table

create table #tranTest (rowId int identity(1,1), rowVal tinyint)

begin try
begin transaction

insert into #tranTest (rowVal) values (200)
insert into #tranTest (rowVal) values (240)
insert into #tranTest (rowVal) values (256)
commit transaction
end try

begin catch
declare @errorMsg nvarchar(4000), @errorSeverity int, @errorState int;

select
@errorMsg=ERROR_MESSAGE(), @errorSeverity=ERROR_SEVERITY(), @errorState=ERROR_STATE();

raiserror (@errorMsg, @errorSeverity, @errorState);
rollback transaction;
end catch
set nocount on

select * from #tranTest
drop table #tranTest

Guess what will be returned? Yes, no record; as this time the transaction does what it is supposed to do – rollback all inserts when any of them fails in the transaction.

In conclusion, do not use in-memory table variable if transaction roll back is needed in case of operation error.

 

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

Written by stevey on 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)
[==========================100.0%==========================]
The operation completed successfully.

C:\WINDOWS\system32>
C:\WINDOWS\system32>

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.”

Written by stevey on 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

Written by stevey on 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
      proj
      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:
       <licenseUrl>http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE</licenseUrl>
       <projectUrl>http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE</projectUrl>
       <iconUrl>http://ICON_URL_HERE_OR_DELETE_THIS_LINE</iconUrl>
      <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
      emo.Nuget.Lib.1.0.0.2.nupkg'.
      
      G:\Development\Tryout\NugetServer\Demo.Nuget.Lib>
      
      

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 1.0.0.2 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.

 

 

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

Written by stevey on 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 http://www.brandonmartinez.com/2014/07/02/resolve-an-http-error-500-21-in-iis/ 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

Written by stevey on 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

[ValidateInput(false)]
[HttpPost]
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.

 

Javascript method chaining example

Written by stevey on November 10th, 2014

Javascript method chaining is basically a chain of method calls that instead of call multiple times, just get called once and “chained” to one single object instance – the singleton pattern here. Below are some working samples I created after reading a good reference at http://coursesweb.net/javascript/chain-methods-javascript-object; to try it out, just copy the codes below and paste it to a notepad and then render in any browser.

<html>
<body>
<div id="d1">
<h3>Method chaining example</h3>

<a href="javascript:getArea();">Get Area</a>
<br />
<a href="javascript:getPerimeter();">Get Perimeter</a>
</div>

</body>
</html>

<script type="text/javascript">
var rec=new Rectangule();

function getArea()
{
//alert(rec.Area(3,4)); //this is without chaining
alert(rec.SetParam(3,4).Area()); //chaining

}

function getPerimeter()
{

//alert(rec.Perimeter(3,4));
//method chaining
alert(rec.SetParam(3,4).Perimeter());

}
function Rectangule()
{
var a=0,b=0;

this.SetParam=function(a1,b1){
a=a1;b=b1;
return this; //this is what makes chaining possible.
}

this.Area=function(){
return a*b;

}

this.Perimeter=function(){
return 2*(a+b);

}

}

</script>

 

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

Written by stevey on 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

HResult=-2146233069
Message=Method not found: 'Void Newtonsoft.Json.Serialization.DefaultContractResolver.set_IgnoreSerializableAttribute(Boolean)'.
Source=System.Net.Http.Formatting
...
.Web.Admin\Global.asax.cs:line 22

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

http://stackoverflow.com/questions/16756336/method-not-found-void-newtonsoft-json-serialization-defaultcontractresolver-set

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=4.5.0.0, 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
C:\Empower\Development\PPDS2\Corestream.PPDS.Admin\Corestream.PPDS.Web\packages\Newtonsoft.Json.6.0.5\lib\net40\Newtonsoft.Json.dll

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:

<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.1.0" />
</dependentAssembly>

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

System.IO.FileLoadException was unhandled by user code
HResult=-2146234304
Message=Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, 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)
Source=System.Net.Http.Formatting
FileName=Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
FusionLog=""
....

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.
 

Javascript closure example

Written by stevey on October 7th, 2014

<html>
<body>
<div id=”d1″>
<h3>Closure example</h3>

<a href=”javascript:runCounter();”>Run Counter</a>
</div>

</body>
</html>

<script type=”text/javascript”>
function runCounter()
{
var add=(function(){
var counter=0;
return function(){return counter+=1;} //need return for nested function
//var result=(function(){return counter+=1;})(); //this does not work
//alert(result);
})();

alert(add());
alert(add());
alert(add());

}
</script>