Web Development

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

 

 

Mysql Database repaired after Windows 8.1 upgrade

Friday, December 20th, 2013

Another disaster came with the Windows 8.1 upgrade over weekend  was discovered Monday morning when I was in desperate need for my local WordPress blog where I kept tons of valuable info for the project I have been working on. I clicked on the blog link and got an “Error establishing a database connection” message. Using that error message to search Google and returned many complaints about the same problem and basically it was that the upgrade has somehow disabled the underneath MySQL database.  Below were the steps I took to fix the problem and got my WP blog back online:

  1. Launched MySql installer and first selected Add/Modify Products and Features:

    Started MySql Installer to remove and reinstall MySql database engine

    Started MySql Installer to remove and reinstall MySql database engine

  2. First applied all the updates:
    MysqlInstaller_3
  3. After product updates were completed, trying to connect to 127.0.0.1: 3306 and still got the database not connected error; so decided that un-installing and re-installing MySql Database engine was the only option.
    MySql DB Uninstall
  4. When asked if to clean the existing data, did not check the “Remove server datafiles” option or I would lost all my old blogs!
    MySql DB Uninstall - 2
  5. After uninstalled, relaunched the MySql Installer and re-installed the MySql 5.6 Community Edition (default):
    MySql DB re-install
  6. After installation, just followed the configuration process through and added the same user account back (find user account info in wp-config.php); started the MySql Workbench and made sure it could connect to local host instance.
  7. Then that’s it! I browsed to the same work blog site and everywhere was sunshine again!

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.

wordpress update and plug-in install errors fixed

Wednesday, August 28th, 2013

WordPress blog (yangsoft.com/blog) Update and Plug-in install errors and fixes:

Error 1: when clicking on “WordPress 3.6 is available! Please update now.”:

[Downloading update from http://wordpress.org/wordpress-3.6-new-bundled.zip…

Download failed.: Destination directory for file streaming does not exist or is not writable.

Installation Failed]

Fix:

1. Submitted a Support ticket to Winhost and got back a reference link http://forum.winhost.com/threads/wordpress-permissions.10078/
2. Somewhat useful and tried the steps below:

1) Downloaded wp-config.php to local folder; and added this entry to it:
define(‘WP_TEMP_DIR’, ABSPATH . ‘wp-content/’);
2) Uploaded it back to wp root folder.
3) Re-run the Update to version 3.6 and it worked!

3. Then installed Plug-in “wp-DBManager” which wasn’t installed before and now it went through just fine.

It turned out Winhost tech team was pretty decent by forwarding those links from its forum. Thanks!!!

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>
    <elmah>
    <!--<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" />
    
    </elmah>
  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>
    <mailSettings>
    <smtp deliveryMethod="Network">
    <network host="mail.domainname.com" userName="webmaster@domainname.com" password="password" port="numberthatworks" />
    
    </smtp>
    
    </mailSettings>

    (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">
    <system.web>
    
    <authorization>
    <allow users="*"/>
    <!--<deny users="?" />-->
    </authorization>
    </system.web>
    
    </location>
  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.

ASP.NET Web service call error, “Unable to generate a temporary class (result=1)”

Tuesday, February 19th, 2013

Got this obscure error while calling a web service method that requires a Xml serializer:

Unable to generate a temporary class (result=1).\r\nerror CS2001: Source file ‘C:\\Windows\\TEMP\\qdrb02m1.0.cs’ could not be found\r\nerror CS2008: No inputs specified\r\n”}  System.Exception {System.InvalidOperationException} “

 

Web searches on key phrase “Unable to generate a temporary class (result=1)” returned some useful results but none could directly resolve my issue. But general direction was pointing to the proper permission of the ASP.Net surrogate identity that most likely does not have sufficient right to the local I/O where XML serialization takes place.

To prove this, I fired up a console application and called the same web service method; as anticipated, the Console app did not throw error at all. So that’s true – it is to do with the Windows account that IIS uses to run the ASP.Net process.

By default, IIS7 uses “ApplicationPoolIdentity” as the Identity for the Application pool automatically created when a new website is added to the IIS/Sites. But what’s underneath this mysterious “ApplicationPoolIdentity” – you could not even find it in Windows by looking up user accounts? Below are several things I tried and let’s see how they fared:

  1. I tried to give “Full Control” permission to ASP.NET Machine Account on c:\windows\Temp folder. Not work.
  2. Changed the app pool identity to “Network Service” (via IIS7/Site/Advanced Settings) and gave the “Network Service” full control permission to c:\windows\temp (via Windows Explorer). It worked! Then I reduced permission to only “Read, List Folder Contents”, and it still worked.
  3. Changed the app pool identity to “Local System”, of course that worked too.

 

So, at the end, to get rid of error “Unable to generate a temporary class (result=1)..”,  I ended up using the “Network Service” as the Application Pool identity (leave the security mode as Integrated) and granted the “Network Service” account permission “Read, List folder contents” on “C:\Windows\Temp” folder.

P.S.: after I deployed the web app to my staging web server, the error returned. The staging server is running IIS6 and the app pool identity by default was already tied to “Network Service” account. So I went directly to the c:\windows\temp folder and as I anticipated, the account did not have “read, list folder contents” permission. So I granted the permission to “Network Service” account and then it all worked!

Asp.Net Form Postback error:Error – Operation is not valid due to the current state of the object

Wednesday, December 12th, 2012

Sometimes when there are a large number of input fields on a Asp.Net form, and doing postback, I would get this error:
“Error – Operation is not valid due to the current state of the object”

As it turned out there is a restriction on how many fields can be posted back to server and the large grid that contains a large number of textbox fields probably was the culprit. Google search returned some postings that all point to the configure setting

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

 

After I stuck this line into the appSettings, the problem went away.

Smtp Permission error at Winhost

Friday, December 7th, 2012

When I was developing my ASP.Net app on local machine,  I had no problem sending email by calling directly the SMTP relay server assigned by my hosting company Winhost, with port set to 587 of course. But when I deployed the app to the winhost server, the email tool threw this exception :

Request for the permission of type ‘System.Net.Mail.SmtpPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.

I did suspect some some security permission to Smtp related assembly and have done some search toward that direction. First I got a lead from some post via Google search and one suggested added this entry into the <system.web> section; but that did not work, so I am not going to give reference to this post.

<securityPolicy>
<trustLevel name=”Full” policyFile=”internal”/>
</securityPolicy>

Today, I went into Windost support site and did another search on their forum, and they pointed me to using this instead:

<system.web>

<trust level=”Full” />

</system.web>

Yes, that was all it needed!

Setting up Elmah SQL Server objects manually

Tuesday, December 4th, 2012

1. Run Elmah.axd on localhost and got this error,”Could not find stored procedure ‘ELMAH_GetErrorsXml'”.
What happened was that the Elmah sql objects were not installed properly when I run NuGet package-install elmah from inside VS2010 IDE.

2. Remedy was downloading the elmah-1.2-db-sqlserever.sql script from here
4. Open SQL Server 2008 Management studio and connected to the remote database hosted at Winhost
5. Opened the Elmah db sql script file and executed it on the remote database.
6. Now returned to localhost/Elmah.axd and error log is showing.

Open a new window from aspnet code-behind

Thursday, November 29th, 2012

While creating a Cmi course launch Simulator, I run into the need to open up a new window from asp.net code behide, instead of simply doing a Response.Redirect, which will just transfer the browser window to the target AU entry window, and the window where Cmi Simulator launched the course will be lost.

After reading posts here and there, I learned there were three possible ways to achieve what I needed and I picked the one that best suit me to implement in the end solution.

Soution 1: Simply open a new tab to display AU Entry page

On the CmiSimulator.aspx, I had a server-side button called btnLaunchCourse, when the button is clicked, it simply grabs the

LaunchUrl on the page and does a response.Redirect to the website and page defined in the LaunchUrl. To make sure the target page is displayed in a different tab on the browser, just added the OnClickClick attribute like below:

Text=”Launch Course” CssClass=”submitButton” OnClientClick=”form1.target=’_blank';” />

The code-behind OnLaunchCourse has only this line of code:

Response.Redirect(LaunchUrl);

Here Form1 is the id of the aspnet form on the page. If the page is embedded in a master page, the form tag is located in the master page.

Solution 2: Open a pop-up window

Keep the button html code as it is,

Text=”Launch Course” CssClass=”submitButton” />

And register javascript to open a new window from code-behind “OnLaunchCourse”:

protected void OnLaunchCourse(object sender, EventArgs e)
{

//Response.Redirect(txtLaunchUrl.Text);
string url = txtLaunchUrl.Text;
string newWindow = “window.open(‘” + url + “‘,’_blank’,’height=700,width=800,status=yes, toolbar=no, menubar=no,location=no,scrollbar=yes, resizable=yes, titlebar=no’);”;
ScriptManager.RegisterStartupScript(this, typeof(string), “OpenWindow”, newWindow, true);

}

Solution 3: Extension method

public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
{
//credit to this posting at http://stackoverflow.com/questions/104601/asp-net-response-redirect-to-new-window

//windowFeatures example:

windowFeatures=”directories=no,toolbar=no,menubar=no,location=yes,status=no,resizable=yes,width=800,height=600″;
if ((String.IsNullOrEmpty(target) || target.Equals(“_self”, StringComparison.OrdinalIgnoreCase)) &&

String.IsNullOrEmpty(windowFeatures))
{
response.Redirect(url);
}
else
{
Page page = (Page)HttpContext.Current.Handler;

if (page == null)
{
throw new InvalidOperationException(“Cannot redirect to new window outside Page context.”);
}
url = page.ResolveClientUrl(url);

string script;
if (!String.IsNullOrEmpty(windowFeatures))
{
script = @”window.open(“”{0}””, “”{1}””, “”{2}””);”;

}
else
{
script = @”window.open(“”{0}””, “”{1}””);”;
}
script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page, typeof(Page), “Redirect”, script, true);
}
}

At the end, the most elegant solution is the extension method and that was implemented in my final solution. I thank the author of this extension method, Tančev Saša, you’re my hero of the day!