Monday, June 29, 2009

Resolving “A network-related or instance-specific error occurred while establishing a connection to SQL Server…”

SQL Server 2005 Error:“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) ”
Things to check:1. Make sure your database engine is configured to accept remote connections• Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration• Click on Surface Area Configuration for Services and Connections• Select the instance that is having a problem > Database Engine > Remote Connections• Enable local and remote connections• Restart instance
2. Check the SQL Server service account• If you are not using a domain account as a service account (for example if you are using NETWORK SERVICE), you may want to switch this first before proceeding
3. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings in your ASweb P.NET application• Usually the format needed to specify the database server is machinename\instancename• Check your connection string as well

<connectionStrings>

<add name=”SampleConnectionString” connectionString=”Data Source=machinename\instancename;Initial Catalog=AdventureWorks;Integrated Security=SSPI;Min Pool Size=5;Max Pool Size=60;Connect Timeout=30″ providerName=”System.Data.SqlClient”/>

</connectionStrings>



4.You may need to create an exception on the firewall for the SQL Server instance and port you are using• Start > Run > Firewall.cpl• Click on exceptions tab• Add the sqlservr.exe (typically located in C:\Program Files (x86)\Microsoft SQL Server\MSSQL.x\MSSQL\Binn), and port (default is 1433)• Check your connection string as well
5. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings
6. Check SQLBrowser; check that it is running. You may also need to create an exception in your firewall for SQLBrowser.
7. Check that you have connectivity to the SQL Server. Note what you are using to connect: machine name, domain name or IP address? Use this when checking connectivity. For example if you are using myserver• Start > Run > cmd•netstat -ano findstr 1433•telnet myserver 1433•ping -a myserver
Check what ports are IP addresses are being returned.
Alternative:If you still can’t get any connection, you may want to create a SQL account on the server, a corresponding SQL user on the database in question, and just use this username/password combo in your web application.

Source: http://www.sqlmusings.com/2009/03/11/resolving-a-network-related-or-instance-specific-error-occurred-while-establishing-a-connection-to-sql-server/

Wednesday, May 27, 2009

How to convert NameValueCollection to a (Query) String

Most ASP.NET developers know that you can get a key/value pair string from the Request.QueryString object (via the .ToString() method). However that functionality isn’t the same for a generic NameValueCollection object (of which Request.QueryString is derived from).


So how do you take a NameValueCollection object and get a nicely formatted key/value pair string? (i.e. “key1=value1&key2=value2“) … Here’s a method I wrote a while ago:



  1. /// <summary>
  2. /// Constructs a QueryString (string).
  3. /// Consider this method to be the opposite of "System.Web.HttpUtility.ParseQueryString"
  4. /// </summary>
  5. /// <param name="nvc">NameValueCollection</param>
  6. /// <returns>String</returns>
  7. public static String ConstructQueryString(NameValueCollection parameters)
  8. {
  9. List<String> items = new List<String>();

  10. foreach (String name in parameters)
  11. items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name])));

  12. return String.Join("&", items.ToArray());
  13. }

Just in case you didn’t know about the System.Web.HttpUtility.ParseQueryString method, it’s a quick way of converting a query (key/value pairs) string back into a NameValueCollection.

From : http://blog.leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/

Tuesday, December 30, 2008

Server Error in '/' Application ... A potentially dangerous Request.Form value was detected ...

Symptom:

When entering a value with angled brackets into a text box on a .NET application the following error is generated in the browser:

Server Error in '/' Application.

A potentially dangerous Request.Form value was detected from the client (TextBoxN="...")

Cause

The .NET framework is throwing up an error because it detected something in the entered text which looks like an HTML statement. The text doesn't need to contain valid HTML, just anything with opening and closing angled brackets ("<...>").

The reason behind the error is as a security precaution. Developers need to be aware that users might try to inject HTML (or even a script) into a text box which may affect how the form is rendered. For further details see www.asp.net/learn/whitepapers/request-validation/.

This checking was not performed in the .NET 1.0 framework and was introduced with the .NET 1.1 framework.

Remedy:

The remedy is in two parts and you MUST action both:

  1. To disable request validation on a page add the following directive to the existing "page" directive in the file - you will need to switch to the HTML view for this:

    ValidateRequest="false"

    for example if you already have:

    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="MyForm.aspx.vb" Inherits="Proj.MyForm"%>

    then this should become:

    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="MyForm.aspx.vb" Inherits="Proj.MyForm" ValidateRequest="false"%>

    Alternately, you can globally turn request validation off (but in which case be sure to implement item two below). To globally turn request validation off add the following to your web.config file:

    this should go within the section. This will turn off request validation for every page in your application.

    Warning

    With request validation turned off, users will be able to enter html into text boxes on the page. For example entering:

    TalertT('Oops!')

    will be rendered by the browser (when the form is updated and the contents redisplayed) as JavaScript and a message box will appear with the message "Oops!". This is generally considered to be undesirable!

  2. Unless you actually need users to be able to enter HTML you must convert the string to its html encoding equivalent - basically this means that certain characters (like "<") are converted to codes (so "<" is converted to "<"). To perform this conversion use HttpUtility.HtmlEncode, for example:

    MyLabel.Text := HttpUtility.HtmlEncode(MyTextBox.Text);

    You only need to consider this for any text that will be rendered in the browser.


These notes are believed to be correct for .NET 1.1 and .NET 2, and may apply to other versions as well.


From: http://www.cryer.co.uk/brian/mswinswdev/ms_vbnet_server_error_potentially_dangerous.htm

Friday, December 19, 2008

Debugging client JavaScript in VS 2005

Client Java Script is one of the most important things in web development but not the best and easiest to develop. Building of bigger and more complicated scripts, especially using DOM model or form field values can cause a lot of frustration and head pain. Moreover, JavaScript debugging is not easy and obvious as should be. But there is a hope.

One of less known features of Visual Studio 2005 is Script Explorer, hidden in Debug menu where appears only when the debugger is running. This great tool allows easily debug JavaScripts.

Before start, we should ensure that client script debugging is not disabled in IE as it is by default. Suitable options are located on Advanced tab of Internet Options where both script debugging checkboxes should be unchecked.

We can come back to Script Explorer. As it was written before, it appears only while the debugger is working. So after starting project we can go do Debug->Windows where should be Script Explorer. Sometimes, don’t know why, it doesn’t so in this case we have to find it manually. Staying in debug mode right click on tool bar and go into Customize. Then select Debug in Categories on the left side of window and find Script Explorer on the right. Just drag it to Debugging toolbar.

After opening Script Explorer panel we will se the tree of active JavaScripts. At the first level are scripts that are imported from external sources or embedded in the page. There are also auto-generated scripts like postback scripts as well. By double-clicking on the selected script it will open in the main window.

At this moment, we can debug it in well known way using breakpoints, steps, Watch and QuickWatch, just like in the server side, including context variable browsing.

Breakpoints can also be set up in external *.js files before project will be loaded. Then, after loading project, the breakpoint will be activated by debugger. Note, that it is only possible to *.js files not for scripts embedded in pages. These scripts are available for debugging only after loading page.

Taken from:
http://www.developerfusion.com/code/5918/debugging-client-javascript-in-vs-2005/

Tuesday, November 25, 2008

How to delete a row in the DataTable (solution) .

How to delete a row in the DataTable (solution)

The VS .NET / ADO .NET documentation is very poor in the parts about deleting rows from the table. It should tell you the following, but it doesn't.

Let's say you want to delete a record. You read the help, and you write something like:

row.Delete();
table.AcceptChanges();

or, you write something like:

table.Rows.RemoveAt(i);

which is equivalent to the code above.


All is good and well. You have deleted the row from the data table. Now, you want to update the physical database, and you call the Update method.

BZZZZZZZT! Wrong answer! The database rows won't be deleted at all!


What you need to do (and the MS documentation doesn't tell you - just check in the parts about RemoveAt, Delete, Update - it is nowhere to be found) is:

row.Delete(); // mark row for deletion

...Update(); // update the physical database

table.AcceptChanges(); // remove the rows marked for deletion from the dataset


Microsoft, please update your documentation! You could easily put this in the help pages for Delete(), RemoveAt(), or Update()!

Thank you very much!


taken from: http://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=1950

Wednesday, August 20, 2008

How do I – Solve the “Could not create type WebService.Name” error when trying to deploying a web service?

OK, so you wrote a web service and you may even have tested it and everything worked fine. So the you did some "cleanup" and tried to deploy the web service. It compiles and deploys just fine, but when you try to invoke and hit the service you are presented with the following error:

Server Error in '/' Application.

Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not create type 'WebServices.Candidates'.
Source Error:

Line 1: <%@ WebService Language="C#" CodeBehind="Candidates.asmx.cs" Class="WebServices.Candidates" %>

Source File: /Candidates.asmx Line: 1

So just how do you solve this problem?

Here's my checklist of things to check when having trouble deploying web services:

  1. Check that IIS is using ASP.NET 2.0.

    1. Begin by starting up the Internet Information Services manager.
    2. Expand "Web Sites".
    3. Expand your web site e.g. "Default Web Site".
    4. Locate the Virtual Directory to which the web service was deployed and right click it.

    1. On the popup menu, click "Properties".
    2. On the Properties window, select the "ASP.NET" tab.
    3. Ensure that the APS.NET Version is set to 2.0.x and not 1.1.x.
    4. If it is set to 1.1.x, set it to 2.0.x and retry your web service.
  2. Ensure your Visual Studio build properties are set correctly.

    1. Locate the .asmx file in your Solution Explorer pane and right click it.

    1. On the popup menu, click "Properties".
    2. Ensure that the Build Action is set to "Content".

    1. Locate the code behind (.cs or .vb) file in the Solution Explorer and right click it.

    1. On the popup menu, click "Properties".
    2. Ensure the Build Action is set to "Compile".

    1. If either of these weren't set correctly, make the correction, recompile, redeploy and retest.
  3. Ensure ASP.NET 2.0 is an Allowed web services extension.

    1. Open the IIS Manager.
    2. Expand your computer.
    3. Click the "Web Service Extensions" option.
    4. In the right hand pane, locate the "ASP.NET v2.0.x" entry and ensure that its Status is "Allowed". If it is not allowed, the "Allow" button on the left will be enabled. Click it to change the setting.

    5. If it was not allowed, correct the setting and retry your service.
  4. Check for the WebMethod attribute.

    1. Review your code and ensure that you have the [WebMethod] attribute set for all web methods in the service. This does not mean that all methods have to be web methods, but the ones you are trying to consume should have this attribute in its declaration.

  5. Ensure the .asmx and code behind file match definitions.

    1. Open your code behind (.cs or .vb) file.
    2. Look at the web service declaration at the top.

    1. In our example, ensure that #2 and #3 match. If they don't, correct the problem.
    2. Next note the namespace at #1.
    3. Now open the .asmx file. This can usually be done by double clicking it in the Solution Explorer, but if you're not able to get it to open through the IDE, open Windows Explorer, navigate to the file, right click it and select Open in Visual Studio to work around the problem.
    4. Now look at the code.

    1. Note the value of Class in this case is "WebServices.Candidates". The Class value should be the full namespace value as well as the class name. Given our code behind file's values, in this case, the Class value should have been "Crowe.PartnerNomination.WebServices.Candidates", but instead it is just "WebServices.Candidates". This is a common issue when reworking already written web services into a namespace hierarchy. For some reason the .asmx file does not always reflect the changes made which then causes the error message at the beginning of this post.
    2. Change the Class value, recompile, redeploy and retest.

    Taken from: http://www.cjvandyk.com/blog/Lists/Posts/Post.aspx?ID=133

Tuesday, August 5, 2008

Visual Studio 2005 Tools for Office, CommandBarButton FaceId Property

From http://www.kebabshopblues.co.uk/2007/01/04/visual-studio-2005-tools-for-office-commandbarbutton-faceid-property/
I recently started experimenting with Visual Studio 2005 and Visual Studio Tools for Office (VSTO) 2003. This entry is a technical .Net / VS2005 / VSTO blog and will probably not be of interest unless you use these tools yourself.

Yuck. Office applications allow many configuration / add-in options programmatically which are quite impressive, but do not sit well with other .Net development tools. For example, in Forms development, if we want to create a Button on a form programmatically, we declare a new Button(). In VSTO, we declare a new CommandBar, and then have to use the CommandBar.Add() method to create a new button on that toolbar.

One of the first things that I wanted to achieve - after adding a basic toolbar to Outlook 2003, was to add buttons with icons. It was frustrating that this was a topic that seemed to be omitted from the book ‘Visual Studio Tools for Office: Using C# with Excel, Word, Outlook, and Infopath’ (Carter and Lippert), and it almost entirely eluded me as to how to do it. There was the CommandBarButton.FaceId property, useful if you wanted a preset icon on your button (but no apparent documentation of what numbers should be used for which icons). Then there were the Picture and Mask properties that appeared to have relevance to this task, but I could not fathom how to use them. Web searches demonstrated some approaches, even on MSDN, that required the use of the clipboard to load an image; something that could muck up the user’s clipboard and therefore highly undesirable, it seemed to me.

Anyway, I finally found what I needed, on MSDN itself. This was one occasion when a generic web search with Google did not outperform Microsoft’s own site (prior poor recommendations that I had found turned out to refer to previous versions of .Net or VSTO).

But still in all my searches I failed to find documentation of the simplest way of assigning an icon to a button or menu entry, using the FaceId property. Possibly, I missed it; that would be easy in amongst the morass of documentation.

This blog documents the numbers and associated icons as discovered from using the various FaceId numbers in Outlook. I have not yet cross-checked the icon numbering with different applications. Lower down this page, I’ll comment briefly on how I got these images later in the document.

The Icons

The number to the right of the icon is the appropriate FaceId to use:

0000-0099

0100-0199

0200-0299

0300-0399

0400-0499

0500-0599

0600-0699

0700-0799

0800-0899

0900-0999

1000-1099

1100-1199

1200-1299

1300-1399

1400-1499

1500-1599

1600-1699

1700-1799

1800-1899

1900-1999

2000-2099

2100-2199

2200-2299

2300-2399

2400-2499

2500-2599

2600-2699

2700-2799

2800-2899

2900-2999

How I Made These Images

MSDN Support had a very tempting page which refers to ‘Finding FaceID Numbers for Your Microsoft Office 97 Toolbars’; but that text is not linked and does not retrieve anything on a search; though the text suggests that it (should have been) a tool to provide documentation of these FaceId’s in an Excel spreadsheet. Tempting, therefore, but fruitless (even if it referred to past versions, perhaps it might have helped?)

So, I wrote a little piece of code to create an Outlook toolbar with 104 buttons (the first 4 buttons being repeated, so there were 100 unique faceId’s), each with a FaceId and a text caption of the number used to achieve the icon. Making the Outlook window very narrow (so only the first four buttons were displayed) meant that clicking on the toolbar expansion button gave a drop-down with 100 unique buttons on. A bit of jiggery pokery with a screen-shot gave the necessary images. It was a pain to be such a manual process, but there you go; sometimes these things can’t be helped… I did decide to stop at 2999 though ;)

Maybe my OCD will cut in soon though and compel me to find the last icon…

[Added 24/1/07: I have now added a post with FaceId’s 3000 - 3999 for your enjoyment.]