Best asp.net questions in July 2011

What is the difference between Func<string,string> and delegate?

9 votes

I see delegates in two forms:

A. Func<string, string> convertMethod = lambda 

B. public delegate string convertMethod(string value);

I'm uncertain of what actually the difference between these two are. Are they both delegates? I believe the first one would use a lambda and the second would have to have a method to actually perform the work. I may be confused too.

First of all, your two examples are doing two totally separate things. The first is declaring a generic delegate variable and assigning a value to it, the second is just defining a delegate type. Your example, more completely, would be:

public static class Program
{
    // you can define your own delegate for a nice meaningful name, but the
    // generic delegates (Func, Action, Predicate) are all defined already
    public delegate string ConvertedMethod(string value);

    public static void Main()
    {
        // both work fine for taking methods, lambdas, etc.
        Func<string, string> convertedMethod = s => s + ", Hello!";
        ConvertedMethod convertedMethod2 = s => s + ", Hello!";
    }
}

But more to the point, both Func and delegate string convertMethod(string) would be capable of holding the same method definitions whether they be methods, anonymous methods, or lambda expressions.

As for which you should use, depends on the situation. If you want your delegate to be defined more by what it takes and returns, then the generic delegates are perfect. If you want the delegate to have some special name that gives more definition of what that delegate should do (beyond simple Action, Predicate, etc) then creating your own delegate is always an option.

Is it possible to create routes dynamically in .NET 4?

9 votes

In our application we use the new .NET 4 routing system to route certain requests to other parts of the site. We are only allowed to publish our site code in late evenings which means we have to stay late at work to publish any code changes. We frequently have the need to create custom routes to support legacy links to old content and route them to the new content. These are often needed right away and as our routes are defined in compiled global.asax we reach an impasse when we need these live immediately but cannot do a code push.

Is there a way that we could define routes in some sort of configuration file and have the site read them in programmatically without restarting the application?

Phil Haack gives a solution for dynamically registering routes here: http://haacked.com/archive/2010/01/17/editable-routes.aspx

I think that covers what you want, including not having the whole Web App restart.

differences between doing ajax using a page method, a web service and a custom http handler

7 votes

I'm looking to create json objects in the client and then transfer these objects back to the server for processing. These are the following options I'm considering:

  • a page method

  • a web service

  • a custom http handler

I'm looking to use jquery to send the objects. The plan is to convert the json object into c# objects that in turn go into queries. During the processing, I'll need access to the users' session that's working in SQL server session mode. The pages where these calls will be running will be on https. The return objects will also be json objects. I'll consider scalability, security and performance.

I was wondering what would be the ups/downs of using each option.

Thanks for your suggestions.

This is my order of preference:

  • web service
  • httpHandler (asp.net web services are httpHandlers behind the scenes)
  • page method

Web service gives the maximum flexibility and scalability. ASP.Net web services are in fact HttpHandlers conforming to XML/SOAP standards.

Page Methods are least flexible. They best for one off communication between a piece of javascript with the aspx page. Even then, you have better ways to handle that rather than going through a page method.

Here are few benefits of using a web service:

  • Standards based
  • Provide loose coupling between systems
  • Can be scaled easily
  • Provide greater security as you can implement security at many levels (Authorization, Authentication wise)

Architecture of an ASP.NET MVC application

7 votes

I'm in the process of doing the analysis of a potentially big web site, and I have a number of questions.

The web site is going to be written in ASP.NET MVC 3 with razor view engine. In most examples I find that controllers directly use the underlying database (using domain/repository pattern), so there's no WCF service in between. My first question is: is this architecture suitable for a big site with a lot of traffic? It's always possible to load balance the site, but is this a good approach? Or should I make the site use WCF services that interact with the data?

Question 2: I would like to adopt CQS principles, which means that I want to separate the querying from the commanding part. So this means that the querying part will have a different model (optimized for the views) than the commanding part (optimized to business intend and only containing properties that are needed for completing the command) - but both act on the same database. Do you think this is a good idea?

Thanks for the advice!

  1. For scalability, it helps to separate back-end code from front-end code. So if you put UI code in the MVC project and as much processing code as possible in one or more separate WCF and business logic projects, not only will your code be clearer but you will also be able to scale the layers/tiers independently of each other.

  2. CQRS is great for high-traffic websites. I think CQRS, properly combined with a good base library for DDD, is good even for low-traffic sites because it makes business logic easier to implement. The separation of data into a read-optimized model and a write-optimized model makes sense from an architectural point of view also because it makes changes easier to do (maybe some more work, but it's definitely easier to make changes without breaking something).

However, if both act on the same database, I would make sure that the read model consists entirely of Views so that you can modify entities as needed without breaking the Read code. This has the advantage that you'll need to write less code, but your write model will still consist of a full-fledged entity model rather than just an event store.

EDIT to answer your extra questions:

What I like to do is use a WCF Data Service for the Read model. This technology (specific to .NET 4.0) builds an OData (= REST + Atom with LINQ support) web service on top of a data model, such as an Entity Framework EDMX.

So, I build a Read model in SQL Server (Views), then build an Entity Framework model from that, then build a WCF Data Service on top of that, in read-only mode. That sounds a lot more complicated than it is, it only takes a few minutes. You don't need to create yet another model, just expose the EDMX as read-only. See also http://msdn.microsoft.com/en-us/library/cc668794.aspx.

The Command service is then just a one-way regular WCF service, the Read service is the WCF Data Service, and your MVC application consumes them both.

OutputCache serving long-stale data

6 votes

I'm flumoxed... re this and this "meta" questions...

A very basic http request:

GET http://stackoverflow.com/feeds/tag?tagnames=c%23&sort=newest HTTP/1.1
Host: stackoverflow.com
Accept-Encoding: gzip,deflate

which hits a route decorated with:

[OutputCache(Duration = 300, VaryByParam = "tagnames;sort",
    VaryByContentEncoding = "gzip;deflate", VaryByCustom = "site")]

is repeatedly and incorrectly serving either a 304 (no change) if you include if-modified-since, or the old data for a 200, i.e.

HTTP/1.1 200 OK
Cache-Control: public, max-age=0
Content-Type: application/atom+xml; charset=utf-8
Content-Encoding: gzip
Expires: Fri, 01 Jul 2011 09:17:08 GMT
Last-Modified: Fri, 01 Jul 2011 09:12:08 GMT
Vary: *
Date: Fri, 01 Jul 2011 09:42:46 GMT
Content-Length: 14714
(payload, when decoded = some long-stale data)

As you can see, it is serving this nearly half an hour past the 5 minute slot; it looks like the internals of OutputCache simply didn't notice the time ;p It will expire eventually (in fact, it has just done so - my Fri, 01 Jul 2011 09:56:20 GMT request finally got fresh data), but not anywhere like punctually.

UPDATE:

I believed that it was working if we took away the accept-encoding header, but no; this fails too - it just fails on a different cycle (which is what we should expect since the keys are different, courtesy of VaryByContentEncoding):

GET http://stackoverflow.com/feeds/tag?tagnames=c%23&sort=newest HTTP/1.1
Host: stackoverflow.com

gives:

HTTP/1.1 200 OK
Cache-Control: public, max-age=0
Content-Type: application/atom+xml; charset=utf-8
Expires: Fri, 01 Jul 2011 10:09:58 GMT
Last-Modified: Fri, 01 Jul 2011 10:04:58 GMT
Vary: *
Date: Fri, 01 Jul 2011 10:17:20 GMT
Content-Length: 66815
(payload = some stale data)

Once again, you'll notice it is being served after Expires.

So: what could be wrong here?

Additional; while we are using a custom option, our GetVaryByCustomString() correctly calls base.GetVaryByCustomString(ctx, custom) for options it doesn't recognise, as per MSDN (indeed this works fine for the second example above).

Is there any chance you're using a custom output cache provider? Hypothetically, if there was a custom provider using say a sliding expiration instead of an absolute one, you'd see symptoms like this.

Why do ASP.NET JSON web services return the result in 'd'?

6 votes

I wrote some ASP.NET web services that use JSON encoding, a la:

[WebInvoke()]
[OperationContract]
public int SetInformation(int recordid, string data)
{
    return 42;
}

and the returned JSON is:

{"d": 42}

Why is the parameter named d? Can I control that? Say, to e?

For reference, a few similar questions I've finally been able to dig up:

This is a "security" feature that prevents the JSON from being returned from being able to be directly executed javascript inside an Eval statement. Or something very similar along these lines.

More information on this topic: http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/ take a look at the section labeled Waiter, there’s a .d in my msg soup!

How do I stop other domains from pointing to my domain?

6 votes

I recently found out that there are other domain names pointing to my website (that don't belong to me) and I was wondering how people can stop/prevent this from happening. I'm hosting this on peer1 using IIS and I'm using ASP.NET C#.

Can I use an HttpModule or some other code to reject domain names that aren't mine?

Is there a better way?

You should activate name-based virtual hosting and only show your real website for the desired domain names. For all other names, you can display a suitable error message.

Details: Your webserver is contacted by its IP address. There is nothing you can do to stop that. Anyone can say, "connect to that IP address". For instance, anyone can register new domain names to point to your server's IP address. However, inside the request, there is a field Host with a name like www.example.com.

Upon receiving the request, your server may choose to inspect the Host field and deliver different content depending on that value. In the simplest case, the server ignores the field entirely and always prints out the same content. But in a more sophisticated set-up, so called "name-based (virtual) hosting", the server chooses the content depending on the hostname.

This is how shared webhosts work: There's a single server, but depending on the requested hostname it spits out a different website for each name.

Therefore, if you want to tie your server content to your hostname, you have to tell your server to produce your website only for your desired name, and to produce a different (error) website for all other cases.

In Apache this is trivial to configure, just check their documentation; for IIS I wouldn't know but I imagine it's equally simple.

how to get the three previous dates for the given date .net

6 votes

I would like to get the 3 dates from the current date or if user enters a date like 16/07/2011 i would like to show the 3 previous dates for this like

15/07/2011,14/07/2011,13/07/2011

Simple steps:

  • Parse the date to a DateTime. If you know the format to be used, I would suggest using DateTime.ParseExact or DateTime.TryParseExact.
  • Use DateTime.AddDays(-1) to get the previous date (either with different values from the original, or always -1 but from the "new" one each time)

For example:

string text = "16/07/2011";

Culture culture = ...; // The appropriate culture to use. Depends on situation.
DateTime parsed;
if (DateTime.TryParseExact(text, "dd/MM/yyyy", culture, DateTimeStyles.None,
                            out parsed))
{
    for (int i = 1; i <= 3; i++)
    {
         Console.WriteLine(parsed.AddDays(-i).ToString("dd/MM/yyyy"));
    }
}
else    
{
    // Handle bad input
}

Checking if user has changed cookie value, manually

6 votes

I am busy with a login system for my project.

Just for an extra step to the security.. How can I check/detect if a user has manually changed a cookie value?

Is there some easy way of doing this? Or do I have to set an extra Session variable and match it up with that? With this being said, is a normal ASP.Net Session traceable by the browser? And viewable to the user?

Thanks.

You could append a digital signature to the cookie value and check the signature when you read it back. That way, if the cookie value is tampered with it will be very apparent.

private string sign(string hashStr, byte[] secret) 
{
    // Compute the signature hash
    HMACSHA1 mac = new HMACSHA1(secret);
    byte[] hashBytes = Encoding.UTF8.GetBytes(hashStr);
    mac.TransformFinalBlock(hashBytes, 0, hashBytes.Length);
    byte[] hashData = mac.Hash;

    // Encode the hash in Base64.
    string hashOut = Convert.ToBase64String(hashData);

    return hashOut;
}

Edit: Fixed the encoder so it's explicitly UTF-8.

As usual, you should also be sure to add some salt to your string before calling this, see: Secure hash and salt for PHP passwords

Get msbuild to deploy clean app remotely

5 votes

We are using msbuild to deploy an ASP.NET MVC application to a few different servers. However, msbuild does not appear to delete the remote application folder first (it just seems to update files). Our msbuild command-line looks like this:

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" OurWebProject.csproj /P:BaseIntermediateOutputPath=c:\temp\tempfolder\ /P:Configuration=Release /P:DeployOnBuild=True /P:DeployTarget=MSDeployPublish /P:MsDeployServiceUrl=https://192.168.0.83:8172/MsDeploy.axd /P:AllowUntrustedCertificate=True /P:MSDeployPublishMethod=WMSvc /P:CreatePackageOnPublish=True /P:UserName=ARemoteWebDeployUser /P:Password=SomePassword

Is msbuild really 'smart' enough to sync the files, eliminating the need for a clean deployment each time? If not, is there an easy way to have the files deleted first?

We are using web.config transforms, so the web.config is rebuilt/redeployed every time (a good thing, since we want the app pool to restart on each deploy).

I'm not sure if there are some specific options to msbuild command, but maybe you could add a target to your project? You could create:

<Target Name=CleanServerFolders>
  <Exec Command="psexec \\$(serverIP) -u $(serverUserName) -p $(serverUserPassword) del $(projectFolderOnServer)"
</Target>

If you don't know PsExec, look here: http://technet.microsoft.com/en-us/sysinternals/bb897553 . It's a lightweight tool from Microsoft, probably the best option to run commands on server. And then modify your msbuild command to call this target (but then you need to specify all other default targets in this command):

msbuild.exe /t:Build,CleanServerFolders,Deploy ...etc

Eventually you can add a post build events to your project file(s).

<Project>
  ...
  <Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.targets" />
  <Target Name="AfterBuild"><CallTarget Targets="CleanServerFolders"/></Target>
</Project>

Of course Microsoft.VisualBasic.targets is a file for .vbproj projects. If you're using c#, then try Microsoft.CSharp.targets (better check the name on MSDN)

DotNetNuke module Page_Load fires twice

5 votes

My module's Page_Load event is firing twice for each "actual" load. On the initial load both loads' Page.IsPostBack property is false.

I've renamed Page_Load to Module_Load to verify the name wasn't an issue. I've made sure the method isn't handling both Me.Load and MyBase.Load, which has been the case in the past.

The only thing I'm doing out of the ordinary is that my module is inheriting from an intermediate base class. Could this be the culprit?

My module:

Namespace Modules.RedactedNamespace
    Public Class List
        Inherits RedactedModuleBase

        Protected Sub Module_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Me.Page.IsPostBack Then
                BindList()
            End If
        End Sub

    End Class
End Namespace

My base:

Namespace Modules.RedactedNamespace
    Public MustInherit Class RedactedModuleBase
        Inherits DotNetNuke.Entities.Modules.PortalModuleBase

    End Class
End Namespace

Edit (This fixed it) - I had an Image without an ImageUrl. Presumably this is set by my CollapsiblePanelExtender but rendered with a blank src.

This can happen if you have an img tag with an empty src attribute.

I know this sounds strange, but I believe it has to do with the web browser trying to figure out how to load the image with a blank SRC.

I don't know the protocols involved, but I'd bet there is some ambiguity regarding how to resolve empty string.

So, in the case of some browsers, it actually fires a web request to the current URL hoping the image comes back.

Sounds like a reasonable assumption, but it just so happens to break many ASP.Net web forms.

View Model Patterns and usage in ASP.NET MVC3 (Also, using EF 4.1)

5 votes

I have been searching for an answer to this question for days and it is driving me insane. Currently I am working on a project using ASP.NET MVC 3 and am trying to utilize a ViewModel per controller approach as has been suggested by so many articles and tutorials I have checked out. To better illistrate what I am asking I will outline below:

Lets say I have a pretty simple and straight forward model. Users, Customers, Addresses, Phone Numbers, Orders, Products, Categories, etc... When a user registers for a new account on my site I would like to: 1) create an account for them (this is just an account id, customer type) 2) Add their customer demographic data to Customers 3) Add N-addresses and address types 4) Add N-phone numbers with type as well.

As far as I have got is deciding that I need a RegisterCustomerForRegistrationControllerViewModel. My predicament is what does this model look like? I am trying to be as DRY as possible yet when implementing this pattern I seem to repeat myself at each turn. At what level do I put DataAnnotations for validation? So do I simply new up a new Customer() even if I only want to use one property from the class in a given ViewModel?

I'm not even confident at this point that this is a correct assumption. There seems to be so much opinion on the topic yet so few concrete examples of implementation. I am hoping someone can point me in the right direction and maybe present some code snippets along the way... I hope this is all clear enough and if not please feel free to ask follow up questions.

Again, Thanks in advance!

Repeating simple properties across two distinct layers of an application is not a violation of DRY. Its just good design.

DataAnnotations go on ViewModels.

ViewModel will look something like

public class RegisterCustomerViewModel
{
    [Required]
    public string Name { get; set; }
    public List<AddressViewModels> Addresses { get; set; }
    public List<PhoneNumberViewModel> PhoneNumbers { get; set; |

} 

Is it bad practice to store SQL queries in resource file?

5 votes

I have a web application that communicates with SQL server. Rather than hard-coding all of the query strings, I have opted to store them in a global resource file. Is that considered bad practice?

On a side note, when I do this, Visual Studio yells at me about the possibility of SQL injection, despite those queries being parameterized (not to mention the "spelling" warnings inside the resource file).

I don't see anything particularly "bad" with doing this. It really isn't much different than hard coding the sql code within your code, and only minorly different than generating the SQL ad-hoc at runtime.

You say that you are using parameterized queries, so you shouldn't have to worry about script injection.

If you are storing the sql in a resource file to adhere to the DRY principle, then you may want to use some kind of DAL for that purpose instead. Like Entity Framework (EF) or Linq-to-SQL

Can I modify an MVC route outside of Global.asax?

5 votes

Is it possible to modify the the routes (and thus the RouteTable) outside of the global.asax file, maybe in a controller? Is this even advisable?

My reason for asking has to do with IIS 6 and Integrated Mode not allowing for Request context calls. I'm implementing internationalization for a site and keeping track of the culture in the URL. The culture is originally read from a .config file and loaded as a route default. This file read is what ends up throwing the error (another few steps up the stack). I based this off the method described here.

You can access the routing table pretty much anywhere like so System.Web.Routing.RouteTable.Routes, have tested this from a controller and it worked fine.

How to impelment password check delay in an ASP.NET MVC application?

5 votes

I want all the login attempts to my web application to take no less than 1 second, to make brute force attack less feasible. If I just put something like this in my code:

Thread.Sleep(1000)

I expect that I become susceptible to a very simple ddos attack: just launch several dozen login requests to the site, and thread pool starvation will happen. (I don't believe that Thread.Sleep returns thread to the thread pool, does it?)

What is the correct way to implement this feature?

What you could do instead of sleeping the thread (you're right to be concerned about starvation) is to have a sliding window based upon unsuccessful login attempts for a given username. You could store this in the in-memory cache and ignore login attempts for that username if the sliding window has not yet elapsed.

There's a decent blog post on one possible implementation of this here:

Brute Force Protect Your Website

Weird extension method issue with inheritance

5 votes

I'm trying to extend Page class to add some new functionality (ease of use for some methods as they will be called directly within the code of that page) in ASP.NET, and I'm getting a weird error:

My method is called SetQuery,
if I type SetQuery in a Page class, it is not recognized (yes, I've added using [Namespace];),
if I type base.SetQuery it is seen in IntelliSense, but doesn't compile saying no method or extension method is actually found in Page,
if I type (this as Page).SetQuery it is recognized and works.

Especially the second case seems to be a bug to me, as IntelliSense recognizes it as an extension method, but no compilation.

Is there any 'more natural' way to type SetQuery as I go, without casts etc.?

Extension methods always require an (explicit) target object, so it is impossible to call an extension method via just TheMethodName(). I suspect that if you type:

this.SetQuery();

it will work. There is never an implicit this. with extension methods. Odd but true.

The above explains why SetQuery() doesn't work; base.SetQuery() won't work, since the extension method is defined for Page, not for the base-class. (this as Page).SetQuery() will work for the same reasons as this.SetQuery(), and actually since this as Page is obviously true, the compiler will treat that as a no-op - i.e. this.SetQuery() and (this as Page).SetQuery() should generate the same IL (as long as the actual page doesn't have a more specific SetQuery() method, obviously).

MVC 3 and "Javascript-Disabled" browsers.

4 votes

I have a requirement to implement a web application using MVC 3, which works on browsers even if javascript is disabled. There are a lot of concepts in MVC 3 which rely on the use of jquery.

  1. What are the concepts which won't work in the case of "javascript-disabled" browsers?
  2. For those concepts which won't work, are there any alternative ways to implement those concepts in MVC 3?
  3. With these requirements, is it a good idea to implement such a website using MVC 3, or should it be implemented in asp.net (with every thing done on server side)?

MVC 3 does NOT depend on jQuery to function properly

The beauty of MVC 3 is that it is pre-packaged with a jQuery plugin which provides unobtrusive form validation. Unobtrusive means that it will work even if Javascript is disabled. MVC 3 does NOT require jQuery nor Javascript to work as intended.

Take a moment to read this blog post. The author does a good job explaining how MVC 3 and jQuery work together.

http://www.matthidinger.com/archive/2011/02/22/Progressive-enhancement-tutorial-with-ASP-NET-MVC-3-and-jQuery.aspx

Is it possible to raise an event of other control on selecting another

2 votes

I am having a drop down and a radio button on my form. What i would like to do is i would like to call radio_CheckedChangedon drodown_SelectedIndexChanged. Can any one tell me the best way to do

Just write radio_CheckedChanged(sender, EventArgs.Empty). Its very much like calling a method which is infact what it is.

EDIT

This is not an elegant way to do this so it would be better if you could encapsulate the code logic into seperate methods and then call these in the respective handlers based on your conditions

IIS6 App Pool state

2 votes

I was wondering if there is a way to capture the state of an IIS6 App Pool using DirectoryEntry in C#?

I have seen people use AppPoolState for IIS7 but is there an equivalent that will work for IIS6? Or do I need to use a different namespace?

EDIT: Is there anything that will display a string for status? AppPoolState looks like it only accepts integers.

Looks like you'd use the same property: Check the status of an application pool (IIS 6) with C#

.Net division rounding/decimal differences between web servers.

2 votes

I've got a problem that's currently baffling me a bit.

Here's a bit of background: We are in the process of upgrading a asp.net 2.0 web app to .net 4 onto a 64 bit server. We have a test app deployed to both the new and old servers to make sure things work as expected before we go live; both of which point to the same database on another server.

Here's the problem:

double totalGross;
double totalNet = 9999999.00;
float taxRate = 15.00f;

totalGross = totalNet * (1 + (taxRate / 100));

On the old server, the .ToString() on totalGross produces: 11499998.85

On the new server, the .ToString() on totalGross produces: 11499998.6115814

Currently at a loss as to why this might be? The latter value doesn't even represent the first number un-rounded?

By the way - I'm not after ways to correct/improve the code... just after possible reasons why this could happen!

Update

I created a console app and built it in x86 and x64 and ran both versions on the server and it outputted the two different figures. So indeed it does seem to be some sort of loss of precision between 32bit and 64bit when using double. It does surprise me that the 'loss of precision in question is 0.2 this doesn't seem that precise to me and quite a difference?! As someone suggested it's probably better to use the decimal type (in my defence I didn't write this code :P)

I suppose the old server was a 32bit Machine? Check http://msdn.microsoft.com/en-us/library/system.double.aspx, especially the paragrahp Floating-Point Values and Loss of Precision. Can you force the new server to run the process 32bit, does it change anything?