Showing posts with label ASP.NET newbies. Show all posts
Showing posts with label ASP.NET newbies. Show all posts

Jul 14, 2011

Application suddenly becomes slow

I experienced this while I was developing my application in Visual Studio.
It happened for no apparent reason (I didn't remember to make any signifficant changes in this application).

It was really frustrating. The thought that I may need to rething the whole application was a nightmare.

I was in panic and started to think what the problem for this sudden degradation might be.

And guess what?
It appeared to be because of a conditional breakpoint I have set in one of the complex modules.

The program flow was passing through this line of code hundreds of thousand of times so Visual Studio was kind of slow determining if the condition for the breakpoint is true or not.

So remember this for the rest of your life:
"Conditional breakpoints may slow your application considerably, before doing stupid things in case of sudden performance degradation - be sure to remove your breakpoints first (Debug Menu => Disable All Break Points), then check the performance again.".

Jun 28, 2011

WebForm_InitCallback is not defined error (and some resolutions)

I was happilly working while all the sudden I started to get this message.
It took some googlin' in order to understand what is going on.

It was because my development server date was wrong (few months in the past).
Synchronizing it resolved the issue.
Also I read you may experience this problem in case you are changing the current thread culture.

Hope this helps ...

May 27, 2011

Programming - Rule #1 follow your data from the UI to the Database and back

It can save you a lot of time :).
I had to fix a bug with a value not updating on the UI.
I attached with the debugger and followed the code to the Save() method of the manager.
Then I started looking for some problems in the database (asynchronous triggers failing etc.).

I wasn't quite sure where the problem is for a while.
Then I decided to hit F11 on the Save() method of the manager with the hope to see what query it was generating.

Guess what?
It wasn't the query but the fact that the Manager was overriding the Base Manager Save() method, as it needs to convert a DTO object to DataObject in order to save it.
Well I didn't even need to read through all the properties to know for sure that the property that wasn't updating was missing in the list of assignments in the convert method (in order to defend myself I would say that 99.9% of our managers aren't overriding save methods, it is very unlikely so I didn't considered that to be the problem).

Happy coding and remember Assumptions are your worst enemy :). They are the things that waste most of your time.

May 6, 2011

Coding Practice : Always refresh the 2nd Visual Studio Solution :).

I had a problem with some code in a Visual Studio, the errors were something like when you have a missing file, or a missing method or stuff like that.

They were happening all the time and I was wondering what is going on.

The problem was that I was having 2 Visual Studio instances running with different solutions loaded in them, I was coding in the first solution and touched a shared project (.csproj).

The second Visual Studio asked me to refresh. I answered no and the old code was in the Visual Studio #2.

To overcome this, you may:

1. Always answer “Yes” to the refresh dialog (bad practice) as you may forget sometimes or accidentally click “No”.

2. Click refresh on the solution file in the second visual studio (bad solution, it is a bit slow and you may forget to do this).

3. Go to Options –> Environment –> Documents –> and check the following checkboxes:

   3.1. Detect when file is changed outside the environment (check).

   3.2. Auto-load changes, if saved : (check)

I will go with approach #3 and see if it has some shortcomings as I can’t think any right now.

A screenshot bellow shows the exact settings:

image

Having column display name in RadGrid Column chooser but not in the header of the grid

A little bit of background for this one.

I had a Telerik RadGrid that was having few columns ...

It had the column chooser enabled. Few of the columns were icons (for example “Answered”, “Rating”).

I wanted to have them without header text so I added the Template column and everything was just fine.

Until I right clicked on the header in order to show the column chooser. It was displaying the columns with auto generated names like “GridTemplateColumn7”, “GridTemplateColumn10”.

My goal was to keep the header of the grid clean (e.g. no label) because the icons were 16x16 and that’s all the space I needed to occupy with those columns, having a header “Answered” would extend the entire column. So to solve this case here is what I did:

Solution:

1. Added header text to the column and saw that the header text is appearing in the column chooser.

2. To hide it from the header of the column I added an empty <HeaderTemplae>.

The column should look like this:

<telerik:GridTemplateColumn HeaderText="Bookmark">
    <HeaderTemplate>
    </HeaderTemplate>
    <ItemTemplate>
    </ItemTemplate>
</telerik:GridTemplateColumn>

 

This would solve the problem for Template columns (and all column types that allow you to define HeaderTemplate). This will not work for GridBoundColumn for example as this type doesn’t have HeaderTemplate.

 

Hope this helps someone out there …

Apr 17, 2011

Unable to start debugging on the server.

Lot's of such errors, lots of resolutions.
I had another one, the full message is:

Unable to start debugging on the server. An authentication error occured while communicating with the web server. Please see Help for assistance.

It looks like it is an issue with permissions but the problem is that I disabled the "HTTP Keep-Alive" signals for the web site.

Hope this saves few minutes of research ;).

Feb 2, 2011

Copy XmlNode from one XmlDocument to another

This one is more for the archive, but it is not widelly used so you may not know it.

In case you need to copy XmlNode from one XmlDocument to another, you need to do two things.

1. Import the XmlNode from the source XmlDocument to the target XmlDocument, using Import(XmlNode node, bool deep) method of the target node,
2. Get the result from this method (it is XmlNode) and use AppendChild method of the node that should be parent of the node to be transfered.

In other words:
XmlDocument sourceDocument = new XmlDocument();
XmlDocument targetDocument = new XmlDocument();

sourceDocument.LoadXml("");
targetDocument.LoadXml("");

XmlNode nodeToImport = sourceDocument.SelectSingleNode("//nodes/sourceNode");
XmlNode importedNode = targetDocument.ImportNode(nodeToImport, true);
XmlNode parentTargetNode = targetDocument.SelectSingleNode("/nodes/targetParentNode");
parentTargetNode.AppendChild(importedNode);

is enough to import the sourceNode with all its child nodes under the targetParentNode of the target document.

Nov 5, 2010

The status code returned from the server was: 12031

If you checked anything on your mind about this code, it may be because of StackOverflow exception rised within your code / or in .NET which is less possible.


Just to let you know as it happened to me ;).

Jul 19, 2010

Site is recycled + ThreadPool.QueueUserWorkItem


Just to let you know that you may experience this issue.

If you have an unhandled exception it may be because of a job queued using ThreadPool.QueueUserWorkItem method.

Actually it appears that although the exception is not affecting the main thread (it was in another one) - the .NET will kill the running process (w3wp in our case).

As far as I read this behavior is implemented since .NET Framework 2.0.
It is because you may miss unhandled exceptions in a child thread (if it's in the main thread the process will be terminated in a windows application).

I imagine each request to a web server as a separate thread so I am kind of worried why unhandled exceptions aren't killing the W3WP process as well.
It only seems to be killed if you create another thread in the request thread and this another child thread exits with unhandled exception.

Will need to investigate a bit more about that.

Jul 14, 2010

Thread was being aborted. Exception on Response.Redirect()

This is actually an old issue but I try to make sure I have most of the things that stopped me at some point so I can easilly search.

So if you experience the "Thread was being aborted." exception on Response.Redirect(string Url), it is because this method internally calls Response.End().

In order to prevent it to do so, you will need to use the overloaded version that requires another boolean parameter (something like "bool endResponse", don't remember it exactly).

So the thing that should solve it is:

Response.Redirect("http://donchevp.blogspot.com", false);
This way you should avoid "Thread was being aborted.".

Hope I helped a bit ...

Aug 25, 2009

Determine if your site is running under IIS or Casini

For the people who don't know - Casini is the built in Visual Studio server which is by default running when you debug ASP.NET project.
You can use the following to check if the site is running under IIS:

bool isUnderIIS = this.Request.ServerVariables["SERVER_SOFTWARE"].IndexOf("IIS") > -1;

Not the most clever thing I've ever done but seems to be the only way at the moment.
If you know a better way - let us know...

To clarify - IIS will return something like : "Microsoft-IIS/5.1", while Casini will let you bump your head with
string.Empty.
Anyway, this covers my scenarios 100% so I can use it.

Aug 10, 2009

A nice DOM property I bet most of you have missed ...

In my previous post on this topic I mentioned the properties you can use to detect changes in HTML input controls:
http://donchevp.blogspot.com/2009/08/nice-dom-property-i-bet-most-of-you.html

Now I want to inform you that I have found an article which has all the controls included with the property you can use to track for changes:

http://www.codestore.net/store.nsf/unid/DOMM-4UTKE6

The first thing I noticed is that it is kind of inconvenient for the SELECT DOM object for example.
You should iterate through all the items and check their selected property with their defaultSelected property ...

Aug 5, 2009

A nice DOM property I bet most of you have missed ...

Have you ever heard about the defaultValue and the defaultChecked properties?
They seems to be a standard DOM properties so the major browsers seem to support them.
What they do?
The defaultValue property is about textboxes (input type="text") and it will contain the value which the textbox has at the time it was rendered on the page.
The defaultChecked property is almost the same, it is about a checkbox and it tells you whether the checkbox was rendered checked or not.

So doing something like:

function hasTextBoxChanged(textBox) {
return textBox.defaultValue == textBox.value;
}

would tell you whether the textbox passed as an argument has changed its value since it was rendered on the page.

Same function for checkbox would be something like:

function hasCheckBoxChanged(checkbox) {
return checkbox.defaultChecked == checkbox.checked;
}

I find those properties very helpful. If you play a bit with jQuery you can find a real life application of them.
I am however wondering if there are such properties for dropdowns and some other controls.
If I find - I'll definatelly post again.

Hope it helps someone outthere ...


P.S. if the control is a part of update panel and it was udpated in the code behind it will not be counted as a change as the defaultValue / defaultChecked properties will be set again (those properties are taken to be the value of the control when it was rendered).

Aug 2, 2009

Work in a cooperation with your compiler. Always tell the truth about your datatypes!

When you have a cast you should avoid asking the compiler to figure out what kind of data should be returned. This is more about objects and the string data type.
For example I've seen (and to be honest I myself did the following mistake when getting data from DataSet. Don't laugh in .NET 1.1 and 2.0 there was no Linq :)

foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
string strName = row["name"].ToString();
}

The compiler will let you think that it knows how to do the fastest transformation from object (in the dataset all the columns in a row are objects) to the destination type (in our case - string). But it will only let you think so. What will actually happen is that the compiler will slow down the data acquisition due to some internal checks and conversions ...

Instead do the following (as you are more than sure that this column is string):

foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
string strName = (string)row["name"];
}

This way you tell the compiler - "Look, don't even bother to try to infer the type for me. I am telling you this is a string, so please just treat it as string). And it makes sense - after you have a column of type NVARCHAR in the database it will always come to you as a string (masked as object :).

Now there are even worse cases like:

foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
int iId = int.Parse(row["id"].ToString());
}

As you can see you are parsing the id column. You know it's int. But int.Parse can only work on strings, so you are required to turn this object to string, calling its .ToString() method. This will slow down your code insignifficantly on few rows and signifficantly on more rows (few thousands for example).

The following is also wrong:

foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
int iId = Convert.ToInt32(row["id"]);
}

Here you are telling your compiller that you are sure the parameter (row[
"id"]) will cast to Int32 without problems.
But here you are telling your compiller only 50% of the truth. After you KNOW it is int, just be honest and say:

foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
int iId = (int)row["id"];
}

This applies not only to DataSets but everywhere you have a fixed datatype and you know what the type is.


Don't let your compiler do the work.
Just look at your project and try to find places where you are uncertain about fixed datatype.
Change it to be a direct cast and I am pretty sure you will experience speed improvements.

Aug 1, 2009

Why your HttpHandler has the Session set to NULL?

I was in a need to create HttpHandler. I also needed to use the session.
Here is my first attempt:

  
public class ChbHandler : IHttpHandler
   {
     #region IHttpHandler Members

    
public bool IsReusable
     {
        
get { return true; }
     }

    
public void ProcessRequest(HttpContext context)
     {
        
HttpRequest req = context.Request;
        
HttpResponse resp = context.Response;
        resp.Write(
"HttpHandler: Hello World!");
     }
     #endregion
   }

In Here if you try to use the Session object you will not it is null. Why is that?
I googled a bit and found that in order to support session, your HttpHandler should inherit the

IRequiresSessionState or IReadOnlySessionState in order to have the session state in the context parameter (the one that is passed to the ProcessRequest() routine.
Luckilly both interfaces are just marker interfaces, meaning you are not required to implement any additional methods.
So something like this:

  
public class ChbHandler : IHttpHandler, IRequiresSessionState
   {
     #region IHttpHandler Members

    
public bool IsReusable
     {
        
get { return true; }
     }

    
public void ProcessRequest(HttpContext context)
     {
        
HttpRequest req = context.Request;
        
HttpResponse resp = context.Response;
        resp.Write(
"HttpHandler: Hello World!");
     }
     #endregion
   }

Should work just fine for you.
The only change is :
IRequiresSessionState in the list of Interfaces that the class will inherit.

May 15, 2009

Visual Studio Tips & Tricks 1- Re-register the controls in the .designer.cs file (recovering .designer.cs file)

Okay, I suppose all of you know what the .designer.cs file is, but I will shortly explain...

When you add a control to the page (via the markup editor), this control is also registered in the .designer.cs file, so you can have a reference to it in the code behind class (.cs).
So if you have a page Test.aspx, you will have a group of 3 files in it:

1. Test.aspx - this is the markup code, containing HTML and ASP markup, defining the control, css and so on.
2. Test.aspx.designer.cs - the designer file, where all controls are registered as a variables so you can reference them,
3. Test.aspx.cs - the code behind where you add your code. There you can use the controls, referencing them by the ID you gave them in the markup.
What happens behind the scene is that each runat="server" control is registered as a variable in the designer class like this:

protected global::System.Web.UI.WebControls.DetailsView dvMine

I recently did the following mistake - after added a lot of controls, then a lot of code, and a lot of changes to other files, I accidently got the latest version of the designer file (from the source control) of one of my aspx pages. This way I was having the controls markup, but the control registrations were lost. I wasn't able to CTRL + Z until I got my things back as I had already closed / opened the Visual Studio few times.

As a result When I hit F5 to start in debug mode, I got about 20 compilation errors, stating that I am referencing objects that don't exist.
I didn't want to re-register those controls manually in the .designer.cs, neither to delete them in the markup and re-create them (thus registration in the .designer.cs file will be automatically created).

I was wondering what to do, so I finally got the idea. I hit CTRL + K + D (which should reformat your markup) and the missing controls were auto re-created in the .designer.cs file.

Hope this helps someone out there.

May 13, 2009

Nice tool to help you build IE ready sites

I found accidently this tool:



It can help you make your site run smoother under all versions of IE.
It's name is DebugBar go to the official site here.

Mar 23, 2009

Read various elements from the connection string.

I saw a question in ASP.NET forums. There was a guy asking how to extract the Username and Password from a connection string, stored in the web.config.

I recalled doing something like this but was not able to recall which class I used.

After about a day another guy posted an answer on this question - the class was SqlConnectionStringBuilder. You can use this class to easilly manage SqlConnection string properties such as DataSource, Username, Password etc.

Here is my post on how to get a connection string from the web.config:
Read connection string from web.config

Here is some more info about SqlConnectionStringBuilder from MSDN:
SqlConnectionStringBuilder class

Combining both resources will help you manage your connection strings easilly.

Mar 18, 2009

Read the connection string from the web.config file

Here is this code, it is replicated bilions of time in Internet, yet I fill obliged to paste it here...

This is the first way, which I took from Microsoft.
It checks if there is a connection strings section, then it checks if the count of connection strings is more than zero:

        System.Configuration.
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
        System.Configuration.
ConnectionStringSettings connString;
        
if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
        {
           connString =
             rootWebConfig.ConnectionStrings.ConnectionStrings[
"MyConnectionString"];
          
if (null != connString)
           {
            
// Do something with the string, for example - create SqlConnection object:
             SqlConnection con = new SqlConnection(rootWebConfig.ConnectionStrings.ConnectionStrings["MyConnectionString"].ConnectionString);
           }
        }


This one is the short line (no checks if anything fails, after all if you don't have a connection string in 99% of the scenarios you will want to have exception rised).

string cString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["mine"].ConnectionString;

Feb 20, 2009

Microsoft SQL Management Studio - Saving changes is not permitted error message.

If you are using Microsoft SQL Management Studio 2008 you may have across this message while trying to edit a table in database:

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.



It is so self exlpanatory still a lot of people have problems to solve it.



You can follow the steps bellow to fix this:

Select "Options" from the Tools menu:



Then Uncheck the "Prevent saving changes that require table re-creation" option and click OK: