Web Development

...now browsing by category

 

Add a website to local IIS7 and browse to it with friendly name

Tuesday, October 2nd, 2012
  1. Launched IIS7 -> Sites -> Add Web Site
  2. Entered yangsoft.com; left application pool with default name
  3. Mapped to physical path H:\Development\yangsoft.com\Yangsoft.Web
  4. Pick a unassigned port: 8092
  5. Host name: yangsoft.com (hopefully, this will precede the real domain name, once the entry is made into hosts file)
  6. After exiting IIS7, browsed to C:\Windows\System32\drivers\etc and opened the hosts file with notepad
  7. Added this entry: 127.0.0.1 yangsoft.com and saved.
  8. Browsed to http://localhost:8092 but get a bad request error 400: invalid hostname
  9. Returned to IIS7 and changed App Pool Identity “yangsoft.com” to use .net 4.0 and Integrated Mode. By default, whenever a website was first setup, it uses .net v 2.0
  10. Now go to browser and type in :yangsoft.com:8092 and it brought up the local site that is in development folder, not in the deployed folder.
  11. In order to launch the website from VS 2010 IDE in the same fashion, I went into VS2010 web project properties and changed the Servers setting from “Use Visual Studio Development Server” to “Use Local ISI Web server” and pasted in the url: yangsoft.com:8092
  12. Ran the project in debug mode and now the website rendered as http://yangsoft.com:8092/Default.aspx instead of the http://localhost:2236/Default.aspx or whatever random port number the IDE picks for you.

Adding the specified count to the semaphore would cause it to exceed its maximum count.

Wednesday, June 27th, 2012

This was a scary error message I got it today while I tried to switch my EF project to connect to a live database. The way I did the switch was have a pair of Entity Framework connection strings in my web.config, with one pointing to development and one to production database, and when the switch turned to production, the system will automatically pick up the live connection string; and that’s it. Test had been going well in development environment and the production database was exact copy, in terms of schema, of the developmental one, so I felt confident to make the switch and expected the codes should run as expected.

But then came this ugly and convoluted error message from the bottom of Entity framework, “Adding the specified count to the semaphore would cause it to exceed its maximum count.”; what on the earth was this? Google search for the phrase returned quite a few answers, some suggesting it might be sql queries had error, other pointing to Microsoft internal bug in db connection pooling. I found this one clicked – disabling pooling; I always favor simple than complex; this was simplest to do, just added an entry to my connection string, which by default was enabling connection pooling. Amazingly, that did it and the error went away! So here was the EF connection string before I made the change, connectionString=”metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=sqlSvr1;initial catalog=sqlDb1;integrated security=false;user id=user1;password=password1234!;multipleactiveresultsets=True;App=EntityFramework"”

and here is the connection string that cleared the semaphore error,  connectionString=”metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=sqlSvr1;initial catalog=sqlDb1;integrated security=false;user id=user1;password=password1234!;pooling=false;multipleactiveresultsets=True;App=EntityFramework"”

More interestingly, after the error went away, I took out the pooling=false, and ran the app again, things just flied without anymore problem; I also switched back to development database, with pooling option enabled, and still didn’t see the semaphore error as I expected that I would. So, if I could regenerate the error at some point, I suspect if I just simply clean the solution and rebuild the entire solution, I might achieve the same outcome – no more this dreadful and convoluted error, “Adding the specified count to the semaphore would cause it to exceed its maximum count.” (got it from the InnerException)


Inject custom message to warn user from closing browser window

Tuesday, June 26th, 2012

In a recent project, I needed to inject a custom message to warn user not to simply close a browser window; they might be doing some online course work and have not sent their course data back to server, and accidentally close down the browser. We didn’t want that to happen. At the beginning, I attempted the window.unload() event, and placed custom message there; but that, strangely, only works in IE7, but not in IE8,9, or recent versions of Chrome.

Naturally, I resolved to jQuery and found that this posting here at http://www.mkyong.com/jquery/how-to-stop-a-page-from-exit-or-unload-with-jquery/ was most useful. The author of this posting gave a good example and even embedded a demo. The thing I wanted to stress is that you must place the javascript code that handles the “beforeunload” event inside the body tag. At first, I placed in in <head> section and the event handler did not fire.

For jQuary library, I used direct reference from Google hosted solution, instead of referencing to local resource. Click hereto see what it looks like with different browsers and view the source. Try to enter a custom message to the text box on the lower part of the page, then try to close your browser. You will see the message you type in the box get added to the browser’s warning message while you try to close the page. For FireFox, it behaves quite differently – the custom message never got displayed and the default message differs from IE and Chorme, as shown in the image.

Use reflection to retrieve SOAP Web service methods

Tuesday, February 28th, 2012

For a local object, retrieving its public methods is quite straightforward using Reflection. Sample codes below will suffice:

using System.Reflection;
using ....;
MethodInfo[] methods = typeof(LocalObjectType).GetMethods(BindingFlags.Public | BindingFlags.Static);
//sort by method names
Array.Sort(methods, delegate(MethodInfo m1, MethodInfo m2)
{ return m1.Name.CompareTo(m2.Name); });
foreach (MethodInfo mi in methods)
{ Console.WriteLine(mi.Name); }

But this does not work if my type is a proxy type to a remote web service. After some readings here and there, I finally was able to get a list of web service SOAP methods from a SOAP ASMX url. Here are the function I created to return a List of the MethodInfo:

using System; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Net;
using System.IO;
using System.Web.Services;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;


public List<MethodInfo> GetSoapMethods()
{
System.Net.WebClient client = new System.Net.WebClient(); string asmxUrl = "http://myservices.mydomain.com/Service.asmx";
if (!asmxUrl.Contains("?wsdl"))
asmxUrl += "?wsdl";
System.IO.Stream stream = client.OpenRead(asmxUrl);
//read service description
ServiceDescription desc = ServiceDescription.Read(stream);
//initialize a service description importer
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(desc, null, null);
//generate a proxy client
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
//import the service into the code-dom tree, this creates proxy codes that use the service
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
if (warning == 0)
{
//System.Xml.Serialization.XmlSchemas mySchema = importer.Schemas;
//Console.WriteLine(mySchema.ToString());
//generate the proxy code
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
//compile the assembly proxy with the appropriate references
string[] assemblyReferences = new string[5]{"System.dll","System.Web.Services.dll",
"System.Web.dll","System.Xml.dll","System.Data.dll"};
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
Type[] types = results.CompiledAssembly.GetTypes();
Type foundType = null;
foreach (Type t in types)
{
if (t.BaseType == typeof(System.Web.Services.Protocols.SoapHttpClientProtocol))
{
Console.WriteLine(t.ToString());
foundType = t;
break;
}
}
//instantiate proxy class
object service = results.CompiledAssembly.CreateInstance(foundType.ToString());
//this will get all the methods, public or not in the webservice
List<MethodInfo> lstMethods = service.GetType().GetMethods().ToList();
return lstMethods;
}
else
{
Console.WriteLine("Warning..");
return null;
}
}

Installed WordPresss to Local IIS7

Monday, February 13th, 2012

Before my memory evaporates again, let’s write down the steps on how this was done:

  1. Downloaded and Installed MySql database engine, then the Workbench (acts like SQL Server Management Studio). No need to write down the version; you will always to go their site to get the latest.
  2. I already installed PHP engine the other day so no need to redo it; this time around, just go to WordPress site http://www.wordpress.org and grabbed the latest .zip file, expanded to D:\Download\Wordpress
  3. Went to IIS7 Manager and added a new site, called “wordpress” and set the physical path to d:\download\wordpress, let the site use default ApplicationPool Identity, wordpress; and set binding to port 8089 and host name “blog.yang.com”.
  4. Before I could browse to http://blog.yang.com:8089, I needed to update the local host file; to do so, browsed to c:\windows\system32\drivers\etc\hosts. The file was not editable by default; so I opened the file property and gave myself  full control permission, changed the entry there from 127.0.0.1 blog.yangsoft.com to blog.yang.com; if the entry is not there, just add one.
  5. Before I could run wp install, I needed to create a database on local mysql server. I launched MySQL WorkBench 5.2 CE ->Server Administration ->File -> New Model. Once I clicked on New Model from File menu, it automatically created a MyDB, clicked on Edit schema and changed name to myblog, selecting collation to be UTF8-UTF8_General_CI.
  6. Added a mysql user account and gave it full db rights.
  7. It is almost there. Now I went to d:\download\wordpress and opened wp-config-sample.php, replaced DB related settings to point to localhost, db name “myblog” and the newly created username. Now I was ready to run WP install, the famous 5 minutes no-brainer!
  8. Went to IIS7, browsed to wordpress/wp-admin/install.php, and it was truly amazing it did only take about 5 minutes to get the site up and running!

How to move your SQL server database from one hosting site to another

Sunday, February 5th, 2012

I normally used backup and restore tool in SQL server to move one sql server database to another server in the same network; but this does not work if your db is in a remote shared hosting site like Godaddy. To get my sql db from Godaddy shared hosting environment and move it to local sql server or a different host server, I had to use Microsoft Database Publishing Wizard. This evening I have downloaded my sql server db (called it remoteDB) to my local sql 2008 express successfully, by going through these steps:

  1. Open a VS2010 Project (existing or create a new).
  2. Go to Server Explorer ->Data Connections, right click and select “Add New Connection”.
  3. Enter remotedb.db.xxxx.godaddyresource.com to “Server Name” and select “use SQL server authentication”; enter username and password assigned by Godaddy for the database.
  4. If server name, and user credential are correct and validated, your target database will now display under the “Select or enter a database name” dropdown box.
  5. Select the database and press OK.
  6. Return to Database Connections, right click on the newly added data connection, select “Publish to Provider” from the context menu.
  7. The Microsoft Database Publishing Wizard appears; just follow the onscreen instruction to script out all database objects for the selected database.
  8. When asked to “Select an Output Location”, I selected “Script to file” and saved to a sql file at local drive. “c:\development\remote\db\sqlbackup\remotedb_published_2-5-12.sql”.
  9. when asked to “Select Publishing Options”, I selected:
    • Drop existing objects in script =True
    • Schema qualify =True
    • Script for target database =SQL Server 2008 (other options are 2005 and 2000)
    • Type of data to publish=Schema and data
  10. Click on Finish.
  11. Now, open the localhost\SQLExpress2008 and attached the remoreDb.mdf from an older version
  12. Open the .sql file “remotedb_published_2-5-12.sql” and executed the sql file
  13. Verified all data and objects were imported as current as of 2-3-2012.

If publishing to another remote sql server, you will use SQL Server 2008 Management Studio to connect to that remote database, and execute the sql file directly against that database.

NT AUTHORITY\NETWORK SERVICE does not have write access to ‘..\Temporary ASP.NET Files’.

Wednesday, January 4th, 2012

Got this error while trying to browse to a WCF service from IIS7: The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to ‘D:\WINDOWS\Microsoft.NET\Framework\v4.0.3019\Temporary ASP.NET Files’. 

What happened? There must be some recent Windows updates to IIS7 that had messed up the previously security settings, but this was just my guessing. Important thing was how to fix this quickly. Found a post here granting access to IIS configuration and other directorys used by ASP.Net, and executed this line of command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -ga “NT Authority\Ne
twork Service”

And that took care of it. “Network Service” is the identity used by the Application Pool used by the WCF service.

ReportViewer Error: could not load Microsoft.ReportViewer.ProcessingObjectModel.dll

Friday, December 16th, 2011

Today I have deployed a .net 4.o website which was upgraded from 2.0 sometimes ago, and found that the ReportViewer that was created back in VS2005 time no longer worked; the error returned was to do with that the Microsoft.ReportViewer.ProcessingObjectModel.dll could not be found; the ReportViewer worked normally on my local machine and I used the Web Deployment project to wrap things up and xcopy needed files to an internal web server. I guess the deployment package did not pickup what was needed for ReportViewer; as it turned out, after reading some useful posts here http://forums.asp.net/t/1723107.aspx/1 , I needed to download the ReportViewer 2010 redistributed package ReportViewer.exe from here http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=6442; after I ran the ReportViewer.exe on the deployed web server, the error was fixed and gone.

Allow other machine to connect to WCF Service hosted on localhost, Win7/IIS7

Thursday, November 10th, 2011

Moving along with my WCF project; today I needed to connect to the WCF services developed and published to my development machine (localhost, let’s mask its name as “dev1″) from another machine, named “user1″,  in the same network domain, and got the “Operation timed out” error 118. My localhost machine is a Windows 7 Enterprise and the WCF services are hosted on IIS7. Obviously, this was a security setting on the firewall on local machine that had blocked remote access.  Below are the steps I went through to get the problem resolved:

  1. First, I checked if I had access to default port, 80 at dev1 from user1 before I did anything; I browsed to http://dev1/Defaultsite/Default.aspx, and fair enough, not a chance – page was not rendering.
  2. On localhost (dev1), I went to Control Panel -> System and Security -> Windows Firewall -> Allowed Programs; highlighted “World Wide Web Services (HTTP) and changed settings -> checked “Domain” and “Home/Work (private)” checkboxes.
  3. Now browsed to http://dev1/Defaultsite/Default.aspx again and it worked!
  4. But when I browsed to a different port at dev1, http://dev1:8088/WcfHost/Service1.svc, I got denied again, error 118, “The operation timed out”, scary..I thought that I might need to turn on Windows Communication Foundation allowed programs inside Windows Firewall; so I did that but then it sill not worked.
  5. Is this WCF issue or port opening issue? To test that, I created a plain website, TestWeb, and hosted at http://dev1:8088/Testweb, and it still cannot be accessed from “user1″ machine. So this must be that port 8088 is not accessible from another machine.
  6. Back to Windows firewall config tool and went to Advanced Security Settings and created a new inbound connection rule, “RemoteAccessToPort8088″ to allow remote connection to port 8088 and 444.
  7. And this did it! Now I was able to access both http://dev1:8088/WcfHost/Service1.svc and https://dev1:444/WcfHost/Service1.svc from “user1″ machine.

Run .Net 1.1 Web Project in Windows 7/IIS7

Tuesday, November 1st, 2011

I have to develop and support three versions of .Net projects on one Windows 7 machine running IIS7. After installing VS2003, VS2008 and VS2010 on the machine, it was not without some struggling to get the legacy .Net 1.1 project to run seamlessly in IIS7, so it is worthwhile to write down a few key steps here:

  1. Created a .Net 1.1 website, called Net1_1 in IIS7 and selected Application pool ASP.Net 1.1 from the available Application pool drop-down. The ASP.Net 1.1 application pool was created automatically when Framework 1.1 was installed. If this application pool is not present, that is an indication that .Net 1.1 framework has not been installed or was not installed properly.
  2. Made sure that the ASP.Net 1.1 app pool “Managed Pipeline Mode” is “Classic”, which is default, instead of “Integrated”.
  3. At this point, I tried to browse to the .Net 1.1 app directly from IIS7, I got all sort of errors. They were caused by that ISAPI filter for .Net 1.1 was not  present by default in IIS7. To fix that, I selected the Net1_1 site -> Features View and double-clicked on “ISAPI Filters” icon; clicked on Add, gave it a name “Asp.Net 1.1″ and set “Executable” to be “C:\Windows\Microsoft.NET\Framework\v1.1.4322\aspnet_filter.dll”.
  4. Lifted the ISAPI and CGI restriction on the filter by going in to ISAPI and CGI Restrictions pane (accessed from Machine level Feature View) and changed Restriction from “Not Allowed” to “Allowed”.
  5. Almost done; I still got “Access denied” error after all these, why? Googled for “running .net 1.1 on IIS7″ and found a useful post at http://blogs.iis.net/rakkimk/archive/2008/03/20/iis7-running-asp-net-1-1-applications.aspx, which pointed me to download and install .Net framework 1.1 service pack 1. After that, I was able to bring the .Net 1.1 site back to live in IIS7!
  6. Another error, “Error while trying to run project: Unable to start debugging on the web server. Access is denied.”, arose when I tried to debug the .Net 1.1 project from VS2003. What’s going on? Well, it’s the notorious Windows 7 “Run as Administrator” thing! I had to run VS 2003 as administrator, open the project from VS2003, and then the error went away. What an inconvenience!