Best asp.net questions in April 2011

formatting string in MVC /C#

13 votes

Hi all:

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?

Thanks.

If you're dealing with a long number, you can use a NumberFormatInfo to format it:

First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):

NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = "-";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;        

Next, you can use it on your numbers:

long number = 731478718861993983;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);

After all, .Net has very good globalization support - you're better served using it!

MVC 3 - How is this ever going to work?

13 votes

I'm either missing something out or Microsoft has really messed up MVC. I worked on Java MVC projects and they were clean and simple. This is however a complete mess IMO. Examples online such as NerdDinner and projects discussed on ASP.Net are too basic, hence why they "simply" work. Excuse if this sounds negative, but this is my experience so far.

I have a repository and a service that speaks to the repository. Controllers call service.

My data layer is NOT persistence independent, as the classes were generated by SQL metal. Because of this I have a lot of unnecessary functionality. Ideally I'd like to have POCO, but I didn't find a good way to achieve this yet.

When creating entites I can use object binding:

[HttpPost]
public ActionResult Create(Customer c)
{
    // Persistance logic and return view
}    

This works great, MVC does some binding behind the scene and everything is "jolly good".

As soon as I'd like to do some more complex, e.g. - save Order which is linked to the customer everything seems to break:

    [HttpPost]
    public ActionResult Create(Order o)
    {
        // Persistance logic and return view
    }

To persist an order I need Customer or at least CustomerId. CustomerId was present in the view, but by the time it has got to Create method, it has lost CustomerId. I don't fancy sitting around debugging MVC code as I won't be able to change it in a hosting envrionment either way.

Alternative is to use FormCollection:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
   // Here I use the "magic" UpdateModel method which sometimes works and sometimes doesn't, at least for LINQ Entities.               
}

This is used in books and tutorials, but I don't see a point in a method which has an alternative: TryUpdateModel - if this crashes or model is invalid, it attempts to update it either way. How can you be certain that this is going to work?

Another approach that I have tried is using ViewModel - wrapper objects with validation rules. This sounds like a good idea, except that I don't want to add annotations to Entity classes. This approach is great for displaying the data, but what do you do when it comes to writing data?

[HttpPost]
public ActionResult Create(CustomViewWrapper submittedObject)
{
    // Here I'd have to manually iterate through fields in submittedObject, map it to my Entities, and then, eventually, submit it to the service/repository.
}    

Am I missing something out or is this the way Microsoft MVC3 should work? I don't see how this is simplifying things, especiialy in comparisson to Java MVC.

I'm sorry if this sounds negative, but this has been my experience so far. I appreciate the fact that the framework is constantly being improved, methods like UpdateModel get introduced, but where is the documentation? Maybe it's time to stop and think for a little bit? I prefer my code to be consistent throughout, but with what I have seen so far, I have no confidence whatsoever that this is a right way forward.

I don't think your issue is with asp.net MVC but with all the pieces You Choose to use together.

You want it raw and simple?

Use POCOs all around, and implement the repository where you need it.

I haven't used Java MVC, but it'd make the whole question look less like a rant if you include how you solved the particular problem in there.

Let's clear some misconceptions or maybe miscommunication:

  • You can pass complex objects through a post to the view. But you only want to do so if it makes sense, see next bullet
  • The sample you picked there rings some alarms. Accepting Customer data or CustomerID for an order and not checking authorization can be a Big security hole. The same could be said for an Order depending on what you are accepting/allowing. This is a Huge case for the use of ViewModels, regardless of POCOs, LINQ, Asp.net MVC or Java MVC.
  • You can pass simple values not being showed through a post to the view. It's done with hidden fields (which asp.net MVC supports very simply to use the model value), and in some scenarios it generates the hidden fields for you.
  • You are in no way forced to use linq2sql with Asp.net MVC. If you find it lacking for how you intend to use it, move away from it. Note I love linq2sql, but how it is tied to your view of what you can do with asp.net mvc is weird.
  • " I worked on Java MVC projects and they were clean and simple". Working on a project is not the same as designing the project yourself. Design skills does affect what you get out of anything. Not saying is your case, but just wanted to point that out given the lack of specifics on what you're missing from Java MVC.
  • "My data layer is NOT persistence independent, as the classes were generated by SQL metal. Because of this I have a lot of unnecessary functionality. Ideally I'd like to have POCO, but I didn't find a good way to achieve this yet". You picked the wrong technology, linq2sql is Not meant to fit that requirement. It haven't been a problem in the projects I've used it, but everything is designed in such a way that way less tied to its specifics than you seem to be. That said, just move to something else. btw, You should have shared what you used with Java MVC.
  • "CustomerId was present in the view, but by the time it has got to Create method, it has lost CustomerId." If the property is in Order, You can bet your code has the bug. Now, that'd have been a totally different Real question, why it isn't using the CustomerId / such question would come with: your Customer class, the View, what you are passing to the View ... answers would include, but not be limited to: inspect the HTML source in the browser to see what value you are really posting with the source (alternatively use fiddler to see the same), make sure that CustomerId really has the value when you pass it to the View.
  • You said: ""magic" UpdateModel method which sometimes works and sometimes doesn't". It's not magic, you can see what it does and certainly find information on it. Something is off in the information you are posting, my bet is non optional fields or wrong values for information that's parsed ... views support adding validations for that. Without the validations, this can be lacking.
  • You said in a comment: "After UpdateModel is called, i can't explicitly set the CustomerId, I'll have to retrieve a customer object and then assign it to the order, which seems like an overhead as all that I need is CustomerId" ... you are accepting a CustomerId that is user input (even if it is a hidden field), you really want to Validate that input. Additionally you are contradicting yourself, you claim to just need CustomerId, but then you say you need the full Customer Object related to the order bound. Which is it, if you are only binding the CustomerId, you still need to go get that Customer and assign it to the property. There is no magic besides the scenes ...
  • Also in a comment: "Update model is something I'm avoiding completely now as I don't know how it will behave with LINQ entities. In the view model class I have created constructor that converts LINQ entity to my view model. This decreased amount of code in controller, but still doesn't feel right". Reason to use ViewModel (or EditModel) is not because it is linq2sql ... it is because, among many other reasons, you are exposing a model that allows to manipulate way beyond what you actually want to allow the user to modify. Exposing the raw model, if it has fields the user shouldn't be allowed to modify, is the real issue.

How to determine distributed architecture?

11 votes

I'm trying to get my head around the thought process when designing a large scale application.

Let's say I have a client who needs a new customer website and he is estimating 40,000 orders per day with an already 25,000 user base. When desiging the application, how do you about determining if a distributed architecutre is needed? Should I use a web farm? etc.

I've mostly build 2 tier (physical) applications in the past and I really want to improve my understanding.

Any insight would be great!

It's going to depend on a lot of other factors than just the number of orders per day. Where will it be hosted? What does that physical architecture look like? What else does the application do besides ecommerce? Does it need to integrate with other applications (besides the payment gateways of course)? Etc.

A simple two tier application in the right cloud hosting environment (say VMware for instance) that can scale dynamically would work just fine for an ecommerce website. A simple two tier application in the right on-premises hosting environment (load balanced web farm) should also work fine for an ecommerce website. It's the difference between scaling up (potentially hidden with virtualization, which ends up being a scale out of sorts) and scaling out (adding more servers).

A distributed architecture would allow you to distribute the system load (say order processing) to 1:M servers that sit (perhaps) behind a load balancer. This is a very common approach, and would also work very well for an ecommerce website.

In my opinion, there isn't one architecture or system design that fits every mold. The closest architecture to fit every mold (again, my opinion) would be a service oriented architecture. If all business processes and logic are services (and designed correctly), then no matter how your requirements change, no matter what your hosting environment looks like or changes to, and no matter what integration requirements you have, your system can handle it with little or no changes.

What so different about Node.js's event-driven? Can't we do that in ASP.NET's HttpAsyncHandler?

10 votes

I'm not very experienced in web-programming and stuff, and I haven't actually code anything in Node.Js yet, just curious about the event-driven approach. It does seems good.

The article explain some bad things that could happen when we use thread-based approach to handle request, and should opt for event-driven instead. In thread-based, the cashier/thread is stuck with us until our food/resource is ready. While in event-driven, the cashier send us somewhere out of the request line so we don't block other request while we wait for our food. To scale the blocking thread-based, you need to increase the thread number. This seems to me this is just a bad excuses for not using the thread/threadpool properly.

Couldn't that be properly handled using IHttpAsyncHandler? ASP.NET receive a request, use the ThreadPool and run the handler (BeginProcessRequest), and then inside it we load the file/database with a callback. That Thread should be free to handle other requests. Once the file-reading is done, the ThreadPool is called into action again and execute the remaining response. Not so different for me, so how's that not so scalable?

One of the dis-advantage of the thread-based that I do know is, using thread needs more memory. But only with these, you can enjoy the multi-core benefit. I doubt node.js is not using any of the thread/cores at all.

So, based on just the event-driven vs thread-based (don't bring the "bcoz it's javascript and every browser..." argument), can someone point me out what is the actual benefit of using node.js instead of the existing technology?

That was a long question. Thanks :)

First of all its not multi threaded. This is important. You have to be a very talented programmer to design programs that work perfectly in a threaded environment. Threads are just hard.

You have to be a god to maintain a threaded project where it wasn't designed properly. There are just so many problems that can be hard to avoid in very large projects.

Secondly the whole platform was designed to be run asynchronously. Have you see any ASP.NET project where every single IO interaction was asynchronous? simply put ASP.NET was not designed to be event driven.

Then there's the memory print for the fact that we have a thread per open connection and the whole scaling issue. Correct me if I'm wrong but I don't know how you would avoid creating a new thread for each connection in ASP.NET.

Another issue is that a node.js request idle's when it's not being used or when it's waiting for IO. A C# thread sleeps. Now there is a limit to the amount of these threads that can sleep. In node.js you can easily handle 10k clients at the same time in parallel on one development machine. You try handling 10k threads in parallel on one development machine.

JavaScript itself as a language makes asynchronous coding easier. If your still in C# 2.0 then the asynchronous syntax is a real pain. A lot of developers will simply get confused if your defining Action<> and Function<> all over the place and using callbacks. An ASP.NET project written in an evented way is just not maintainable by your average ASP.NET developer.

As for threads and cores. Node.js is single threaded and scales by creating multiple node processes. If you have a 16 core then you run 16 instances of your node.js server and have a single node.js load balancer in front of it. (Maybe a nginx load balancer if you want).

This was all written into the platform at a very low level right from the start. This was not functionality bolted on later down the line.

Other advantages

Node.js has a lot more to it then above. Above is only why node-js way of handling the event loop is better then doing it with asynchronous capabilities in ASP.NET.

  • performance. It's fast. Real fast.
  • One big advantage of node.js is the low level API. You have a lot of control.
  • You have the entire HTTP server integrated directly into your code then outsourced to IIS.
  • You have the entire nginx vs apache comparison.
  • The entire C10K challenge is handled well by node but not by IIS
  • ajax and json communication feels natural and easy.
  • real time communication is one of the great things about node.js. It was made for it.
  • plays nicely with document based nosql databases.
  • Can run a TCP server aswell. Can do file writing access, can run any unix console command on the server.
  • You query your database in javascript using for example couch db and map/reduce. You write your client in JavaScript. There are no context switches whilst developing on your web stack.
  • rich set of community driven open source modules. Everything in node.js is open source
  • small footprint and almost no dependecies. You build the node.js source yourself.

disadvantages of node.js

It's hard. It's young. As a skilled JavaScript developer I have difficulty writing a website with node.js just because of the low level nature and the level of control I have. It feels just like C. A lot of flexibility and power either to be used for me or to hang me.

The API is not frozen. It's changing rapidly. I can imagine having to rewrite a large website completely in 5 years because of the amount node.js will have changed by then. It is do-able, you just have to be aware that maintenance on node.js websites is not cheap.

further reading

http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/

http://blip.tv/file/2899135

http://nodeguide.com/

How do I progressively render a header before content in ASP.NET master pages ?

10 votes

I have a large slow ASP.net site that uses master pages.

I've identified that the user will have a better experience if they can see the header and navigation while the rest of the page is being generated/processed/loaded from the database.

I've done some simple tests and I can do Response.Write() followed by Response.Flush() in page_load(), and IIs will use chunked encoding and send the output to the browser immediately while the rest of the page renders.

I want to do the same thing, but only send the master page header and navigation.

Any pointers on how to achieve this?

Using ASP.net 4 and IIs 7.5

Edit

If anyone can give some pointers on how to change the site to use AJAX without having to change every page and link, I'd appreciate it. Thanks!

I suggest you use control caching. Asp.Net provides native caching of pages and controls. See these links to know more.

ASP.NET Caching: Techniques and Best Practices

http://msdn.microsoft.com/en-us/library/aa478965.aspx

ASP.NET Caching

http://msdn.microsoft.com/en-us/library/xsbfdd8c(v=VS.100).aspx

Control caching

As you have mentioned, it appears that you already use page-caching. Try using control-caching to further improve the caching. To use control caching, place PartialCachingAttribute over the control class. You can use the ControlCachePolicy of the control to set caching behavior:

control.GetCachePolicy()

static variables in asp.net/C#

8 votes

I'm using extensively static variables in my web application project. Now I have read from some articles that it is a global variable for the whole project and the data that is in the static variables can be shared or overwritten by other users (I mean it is not user specific or session specific).

So is it general programming practice not to use static variables in the normal web application development?

Are static variables not used at all just like GOTO statement/keyword meaning there are extensive restrictions to use them and preferably not used at all? Then in what cases do we use the static key word?

Then i have this requirement that a particular variable has to be initialized only once in a particular webform.aspx.cs and the scope has to be restricted to only to that particular .aspx.cs and to that particular user who has logged in ? How do i meet this requirement ? If possible can any one illustrate this with code ?

PS: If some one doesn't like this question, please you can delete it after being answered instead of flagging or down voting it?

Personally I try to avoid static variables as much as possible. They make the code difficult to unit test and also could introduce subtle bugs due to concurrent access and race conditions.

As far as your requirement is concerned you could use store the variable as a property of the control in the ViewState. If it is user specific data that you are trying to store then you could use the Session state.

What are all the user accounts for IIS/ASP.NET and how do they differ?

8 votes

Under Windows Server 2008 with ASP.NET 4.0 installed there is a whole slew of related user accounts, and I can't understand which one is which, how to they differ, and which one is REALLY the one that my app runs under. Here's a list:

  • IIS_IUSRS
  • IUSR
  • DefaultAppPool
  • ASP.NET v4.0
  • NETWORK_SERVICE
  • LOCAL SERVICE.

What is what?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

I hope this helps clear things up.

Simple integer regular expression

7 votes

I have ValidationRegularExpression="[0-9]" which only allows a single character. How do I make it allow between (and including) 1 and 7 digits? I tried [0-9]{1-7} but it didn't work.

You got the syntax almost correct: [0-9]{1,7}.

You can make your solution a bit more elegant (and culture-sensitive) by replacing [0-9] with the generic character group "decimal digit": \d (remember that other languages might use different characters for digits than 0-9).

And here's the documentation for future reference:

NLogConfigurationException - Invalid cast from 'System.String' to 'System.Uri'

7 votes

Nlog is throwing an exception now that I have updated from 1.0 -> 2.0.

When NLog.Config.XmlLoggingConfiguration.Initialize is called the following exception occurs:
"Error when setting property 'Url' on WebService Target[Target_AuditLog_WebService_Global]"
with an innerException of:
"Invalid cast from 'System.String' to 'System.Uri'.

the target looks like this:

<target name="Target_AuditLog_WebService_Global" xsi:type="WebService" namespace="http://ourLoggingServer.corp/" protocol="Soap12" methodName="AddLog" url="http://ourLoggingServer.corp/Logger.asmx">
  <parameter /> <!-- Several params, none of type system.uri -->
</target>

I found this however it seems they think its fixed: http://nlog.codeplex.com/workitem/5352

This is a bug and has been fixed, however, a version with the fix has not yet been released officially or via NuGet, if you run across this issue you will need to use a nightly build version:
http://nlog.codeplex.com/releases/view/64708 (which I have confirmed works)

If there has been an official release after 4/27/2011 you should try using it.
http://nlog.codeplex.com/releases

How does ASP.NET routing work internally ?

7 votes

OK I have seen many tutorials on how to use URL routing. However, I'd like to know how it is implemented internally by Microsoft.

Check out the following links

  1. How ASP.NET MVC Routing Works and its Impact on the Performance of Static Requests
  2. How URL Routing works in ASP .Net 4.0

How to Generate absolute urls with https in MVC3?

6 votes

Hello,

I am using MVC3 and am trying to serve content from https, the problem is that when I call Url.Content the files are still served from http using a relative url. I thought this problem was addressed in MVC3 but i can't seem to find any solution. Does anybody know if this issue is inherently solved in MVC3 and how to accomplish it or do I need to create my own helper methods to generate absolute Urls based on protocol?

You can probably implement your own solution using VirtualPathUtility.ToAbsolute. Probably something like this:

public static class UrlHelperExtension {
  public static string Absolute(this UrlHelper url, string relativeOrAbsolute) {
    var uri = new Uri(relativeOrAbsolute, UriKind.RelativeOrAbsolute);
    if (uri.IsAbsoluteUri) {
      return relativeOrAbsolute;
    }
    // At this point, we know the url is relative.
    return VirtualPathUtility.ToAbsolute(relativeOrAbsolute);
  }
}

which you would use like:

@Url.Absolute(Url.Content("~/Content/Image.png"))

(Didn't test this myself, feel free to play around to make it work right.)

This helps to you to generate absolute URLs for your content files. In order to change the scheme of the resulting URLs, you can create an additional extension method that manipulates the scheme of the given URLs so that they are HTTPS, or something else.

As Khalid points out in the comments, similar extension methods are already available in various open-source projects which you can make use of (given that the license permits). An example one can be found here.

Is it bad practice to have a ViewModel with a propety typed as another ViewModel in ASP.NET MVC

6 votes

Hey guys,

Would it be considered bad practice to have a viewmodel that has a property of another view model?...as in:

public class PersonViewModel
{
     public PersonJobViewModel Peron { get; set;}
     //other properties here...
}

EDIT

A little more about my particular situation:

I have a view model that currently contains 2 domain classes. I pass this viewmodel to a view that loads 2 partials views(one for each domain class in the viewmodel)

So with this I end up passing pure domain models directly into the partial views.

My thinking is that I can make a view model for each domain model that go to the partials...and then wrap those 2 in another viewmodel that gets passed to my parent...

or is there a better way to accomplish this?

No, it's not bad at all. It's perfectly fine code. It allows you to reuse portions of view models between different views.

How to find performance hot spots in .Net application?

6 votes

I have an existing ASP.NET 2.0 web service serves several WinForms clients. In our application, We belive we have performance problem in several levels.

  1. Sending toomuch data in syncrounous request
  2. Lazy loading, Too many round trip between web service and database
  3. POCO <-> Sql object mapping using untyped datasets and reflection[no caching]

This is an existing application with large code base, I would like to instrument this app to find out hotspots.

  1. How can I instrument remote apps like winforms client deployed in remote places?
  2. How can I instrument Web Service?
  3. Edit** Are there any profilers better than VS profiler?
  4. Can I trust the profilers to tell me the hot spots, so I don't pollute my code with instrumentation? Or Do I have to take the middle road, profiler + instrumentation?

This may help:
ASP.NET and WorkerThreads – Interesting performance tweaks
20 Tips to Improve ASP.net Application Performance
Use Custom Http Handlers To Improve Performance in ASP.NET
Best practices for ASP.Net applications
Scaling Strategies for ASP.NET Applications

ASP.Net Post timeout

6 votes

Hello There,

I am stuck with asp.net post issue with last 2 weeks.

Scenario:

My application page has 3 controls. A WYSIWYG editor (Free Textbox), a text box to get name of the article being edited in WYSIWYG editor, another text box to accept key words.

Order of the controls in page from top to bottom as follows,
first, Name text box
second, WYSIWYG Editor
last, Key Word text box

Problem:

When ever users tries to save their edited documents, IIS server returns time out (Production runs on win 2008). But interestingly, "Name text" box information and half of WYSIWYG Editor (its not exactly half, it varies for each case) information is saved to database. but last "keyword text" box is not saved. During this web server hangs for a while, kicks out the user and later after few mins back to normal speed. I think app pool is recycled. But all works fine on my development environment (in My PC runs on Win 7 64bit). Also i have set ValidateRequest="False" in page directive for Production and Development environment.

Environment:

Environment .NET 4.0, ASP.NET
FreeText box WYSIWYG editor
Shared Hosting windows 2008
SQL Server 2008

Tried solutions (but no breakthrough):

Tried with Different Browser Firefox, chrome, IE and same error.
Added ValidateRequest="False" in page directive and replaced WYSIWYG editor with plain text box and tried to save, same issue.
Just tried to log the post data directly from page.request object. Still getting full data for "Name textbox" half for WYSIWYG textbox and nothing for rest.
There is no issue on DB connection or table field. I have triple checked.

Possible Suspicions and Questions:

Based on my knowledge there is no limitation on post data length. but in IIS is it possible to override this ? wondering if this is set on my shared hosting.
Basically http post data gets truncated somewhere between browser and server.request object. What would be the reason if this is happening?
If http post is truncated why whole application hangs (or restarts)?
What are the precaution need to be taken when posting html content as http post?

Thank you.

New Finding:

Checked my post using httpfox. Post size was about 9958 bytes. But firefox sends first 330 bytes of data and then web page hangs. After about a minute, i am getting NS_ERROR_NET_RESET error code in httpfox.

Checked my post using filder2 with IE9. It tries to send first 512 bytes then hangs. Returns "ReadResponse() failed: The server did not return a response for this request."

Question:

This likely would be browser issue or server issue. I think if browser issue, this wont happen for IE and Firefox.

Update:

Most likely isolated the problem towards web hosting. Tested by changing form post url to different domain and see if values can be retrieved at that domain. Yes it works. Only it didn't work for my domain. Interestingly i tested this for normal html page post. it also didnt work. So most likely a security installed to prevent this or server misconfiguration. Already put a ticket to them and waiting.

Any how all of your feed back helped me to isolate the problem.

Solved:

Yes this issue was on our web hosting site. So far i heard from them is like some firewall blocking the big post from http. They said now our domain is white listed. Anyway, now its works. But this ate 2 weeks of my time, but it was good learning experience. Thanks guys for your help. Really appreciated.

I have face the same error on one web page. Its was very wired because if I was use proxy, the error go way, if I was called from my computer direct I have time out, and never go on.

After many checks I discover that the problem was with the very big viewstate !. How I find it: I save an html part of my page, as its rendered and start remove items from the html and make post, until I discover that the post continue when I cut down the viewstate post.

The solution was to disable viewstate on many non needed controls and compress+cut in smaller part the remaining viewstate post data.

You can google and find many ways to compress and cut the view state in parts.

Some articles:

http://msdn.microsoft.com/en-us/magazine/cc188774.aspx

how to cut it tutorial:
http://www.dotnetfunda.com/articles/article634-viewstate-patterns-in-aspnet-.aspx

how to compress it
http://www.hanselman.com/blog/ZippingCompressingViewStateInASPNET.aspx
http://www.codeproject.com/KB/viewstate/ViewStateCompression.aspx
http://www.google.com/search?hl=en&safe=off&q=asp.net+compress+viewstate&aq=f&aqi=g1g-b2&aql=f&oq=

Ps: In this demo page of the free TextBox that you use, the viewstate is huge ! and its even empty from text, imagine how big the viewstate can be if you actual have and text inside. Not so free - the cost is the huge viewstate.

Follow up

As Jeyara say on the comments below, final this was the error, a blocking of large post files by a firewall on the hosting server. So the error have to do with large post back data.

LinkButton in ListView in UpdatePanel causes full postback

4 votes

I have a LinkButton in a ListView in an UpdatePanel. I would like the button (well, any of them) to cause a partial postback, but they are causing a full page postback.

<asp:UpdatePanel ID="upOutcomes" UpdateMode="Conditional" runat="server">
  <ContentTemplate>
      <asp:ListView ID="lvTargets" runat="server" onitemdatabound="lvTargets_ItemDataBound">
        <ItemTemplate>
          <asp:LinkButton ID="lnkAddTarget" CssClass="lo" Text='<%# Eval("Title") + " <b>" + Eval("Level") + Eval("SubLevel") + "</b>" %>' runat="server"></asp:LinkButton>
        </ItemTemplate>
      </asp:ListView>
  </ContentTemplate>
</asp:UpdatePanel>

I found another post on stackoverflow which suggested adding this:

protected void lvTargets_ItemDataBound(object sender, ListViewItemEventArgs e) {
  var lb = e.Item.FindControl("lnkAddTarget") as LinkButton;
  tsm.RegisterAsyncPostBackControl(lb);  // ToolkitScriptManager
}

It hasn't made a difference...

There are a few other similar posts too, but I can't find a solution! Any ideas?

The ClientIDMode setting in ASP.NET 4 lets you specify how ASP.NET generates the id attribute for HTML elements.

In previous versions of ASP.NET (i.e. pre 4), the default behavior was equivalent to the AutoID setting of ClientIDMode. However, the default setting is now Predictable.

Read Microsoft Article

AutoId is required for this because of the way the script manager expects the HTML controls to be generated in previous versions of .NET.

Double insert in MS Access?

4 votes

I'm somehow getting a double insert; every time I submit the form, it sends two records to the database. I can't figure out what's going on. This is a general idea of what my code looks like:

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

'Data collection'

'Define Connection'
    Dim myConn As New OleDbConnection
    myConn.ConnectionString = adsGrandmaster.ConnectionString
    myConn.Open()

'Insert command'
    Dim myIns1 As New OleDbCommand("INSERT INTO tableGrandmaster (date_received, prefix, course_number, title, new, changed, inactivate, end_date, credits, description, hours_lecture, hours_lec_lab, hours_lab, hours_total, related_instruction, repeat, challengeable, in_catalog, in_printed_schedule, core_course, core_name, program_elective, program_name, prereqs, coreqs, recommended, green_course, code, dept_code, division_code, changing_depts, acti_code, grading, general_ed, writing, social_science, math, information_literacy, arts_letters, science_computer, speech_comm, cultural_literacy, date_curriculum_approval, date_state_sent, date_state_approval, date_created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", myConn)

'Insert parameters'

'Execute command'
    myIns1.ExecuteNonQuery()

'Close connection'
    myConn.Close()

Update:

The last little piece of my .aspx.vb file:

'Execute command'
    myIns1.ExecuteNonQuery()

    Label1.Text = "Grandmaster submitted."

    'Close connection'
    myConn.Close()

End Sub

Protected Sub btnBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBack.Click
    Response.Redirect("./index.htm")
End Sub
End Class

If I place my breakpoint at or before myIns1.ExecuteNonQuery(), nothing inserts. If I place it after myIns1.ExecuteNonQuery(), it inserts once. If I place it after "End Sub" (under myConn.Close()), it inserts twice.

Make sure that the aspx:button declaration is not wired up to the onclick event on the code-in-front page as well as the code behind page.