Best asp.net questions in August 2011

Are static variables thread-safe? C#

9 votes

I want to create a class which stores DataTables, this will prevent my application to import a list of details each time I want to retrieve it. Therefore this should be done once, I believe that the following code does so, but I am not sure if it is thread-safe.

The below code is in the Business Layer Section of my three tier application, it is returning a DataTable to the Presentation Layer.

public class BusinessLayerHandler
{
    public static DataTable unitTable;
    public static DataTable currencyTable;

    public static DataTable GetUnitList()
    {
        //import lists each time the application is run
        unitTable = null;
        if (unitTable == null)
        {
            return unitTable = DatabaseHandler.GetUnitList();
        }
        else
        {
            return unitTable;
        }
    }

    public static DataTable GetCurrencyList()
    {
        //import lists each time the application is run
        currencyTable = null;
        if (currencyTable == null)
        {
            return currencyTable = DatabaseHandler.GetCurrencyList();
        }
        else
        {
            return currencyTable;
        }
    }

Any help is appreciated, if there is a better way how to cache a DataTable please let me know.

Update:

Thanks to your opinions, this is the suggested method to do it, if I understood correctly:

public class BusinessLayerHandler
{
    private static DataTable unitTable;
    private static DataTable currencyTable;

    private static readonly object unitTableLock = new object();
    private static readonly object currencyTableLock = new object();

    public static DataTable GetUnitList()
    {
        //import lists each time the application is run
        //unitTable = null;

        lock (unitTableLock)
        {
            if (unitTable == null)   
            {
                return unitTable = DatabaseHandler.GetUnitList();
            }
        }
        return unitTable;
    }

    public static DataTable GetCurrencyList()
    {
        //import lists each time the application is run
        lock (currencyTableLock)
        {
            if (currencyTable == null)
            {
                return currencyTable = DatabaseHandler.GetCurrencyList();
            }
        }
        return currencyTable;
    }
}

It appears as though all you want to do is load it once and keep a reference to it. All you need to guard is initialising the variable if it's null. Null checking, locking and null checking again is called Double Check Locking and will work well for you. It's best practice to provide a separate locking object, so you have good control over granularity of locks.

Note this doesn't stop people from mutating the value inside the DataTable it only stops people from trying to initialise the static member at the same time.

private static readonly object UnitTableLock = new object();
private static DataTable unitTable;
private static bool _ready = false;

public static DataTable GetUnitList()
{
    if (!_ready)
    {
        lock (UnitTableLock)
        {
            if (!_ready)
            {
                unitTable = new DataTable; //... etc
                System.Threading.Thread.MemoryBarrier();
                _ready = true;
            }
        }
    }

    return unitTable;
}

Only read from the result of GetUnitList never write to it.

Amended with reference to http://en.wikipedia.org/wiki/Double-checked_locking

How is ASP.NET MVC wired into ASP.NET?

9 votes

I'm trying to gain a better understanding of the "plumbing" behind ASP.NET and ASP.NET MVC. I've been reading this page, which has helped a lot. From what I understand so far every ASP.NET site has a class that inherits from System.Web.HttpApplication. HttpApplication then has a series of events that trigger HttpModules and HttpHandlers such as BeginRequest, AuthorizeRequest, End Request etc... The HttpModules and HttpHandlers then read and write to and from the current HttpContext.

How does ASP.NET know what HttpApplication class to use? My application has the typical MvcApplication class in a Global.asax file. But I don't see anything in this class related to MVC. Nor do I see any settings anywhere that assign this class as being the "application". Does ASP.NET just always look for a file named Global.asax to figure out what HttpApplication class to create? Or does ASP.NET just look for any class that inherits from HttpApplication in my assembly?

Also, how does it know what modules and handler to use? The page I mentioned above said you specify the handlers and modules through and settings in web.config. But my ASP.NET MVC application doesn't have these settings in its web.config?

If I set a break point in one of my action methods and check HttpContext.Current.ApplicationInstance.Modules I see the following:

OutputCache
Session
WindowsAuthentication
FormsAuthentication
PassportAuthentication
RoleManager
UrlAuthorization
FileAuthorization
AnonymousIdentification
Profile
ErrorHandlerModule
ServiceModel
UrlRoutingModule-4.0
ScriptModule-4.0
__DynamicModule_System.Web.WebPages.WebPageHttpModuleDefaultAuthentication

Where were these specified? Likewise if I check HttpContext.Current.Handler I can see that it's set to a System.Web.Mvc.MvcHandler.

When the first user hits your site:

1) It loads all the Http Modules specified by all the web.configs that bear on your application.

2) If the system is ASP.NET MVC-enabled, a global web.config registers a UrlRoutingModule, incorporating it into the request pipeline.

Now, the class you derive from HttpApplication in your global.asax (such as the standard MvcApplication) is compiled into your dll. Bearing that in mind ...

5) The ASP.NET runtime scans YourApplication.dll for a class that derives from HttpApplication and executes a number of its methods (e.g., Application_Start).

6) When you create routes using the idiomatic ASP.NET MVC MapRoute extension method, it associates the route with an MvcRouteHandler.

7) The UrlRoutingModule (from step 2) uses that routing handler to select the http handler ASP.NET will use to process the incoming request on that route.

You can find the full story here.

div.classname in css file

9 votes

I have seen some developers write

HTML:

<div class="test"> some content </div>

CSS:

div.test {
  width:100px.
}

What is the purpose of doing div.className instead of just .className.

Does this mean this style will be applied only when the class is applied to a div.

So, <span class='test'>content</span> will have no effect of 'test' with the css above? If that is the case, is that best practice? This is almost like style overriding for different type of elements, mixing styles with rules!

To really answer your question, though, first I have to answer a couple of other questions. Because, as you will see, it's all about context.

  • What is the point of HTML?
  • What is a div?
  • How is it different from other HTML elements?
  • And what does it mean when a element has a class (or collection of classes)?

I'll give you my opinion on the answers to those question, and then we can have a meaningful discussion on best-practices.

What is the point of HTML?

The point of HTML is to add context to your data. Text, all by itself, can be a very powerful thing. Since the invention of the printing press, it has served humanity very well as an extremely powerful communication tool. Take the following document for example:

My shopping list
Bread
Milk
Eggs
Bacon

Even with this simple text document, most people can dechiper the intent of the writer; its a shopping list. There is a heading, and a collection of list items that need to be purchased.

So whats the point of HTML then, if simple text documents are enough?

Fair question. If text is enough to communicate, then why do we need HTML?

The reader of the document attempts to parse the information they get. That processes is imbedded with a ton of cultural tricks and learned patterns that are used to reconstruct the origional intent. It is trivial for most people with a basic understanding of english to determine the meaning of the document. However, as the complexity of the document increases (or the familiarity of the reader with the context decreases), then it becomes more and more difficult to parse correctly. Assumptions are made; context becomes unclear. Eventually, the readers ability to accurately decode the message falls apart, and the message is indechiperable.

This is the space where HTML exists. It is desinged to wrap around data, providing context and meaning. So even if you (or the computer) are unable to process the the actual information, you can understand the context in which it should be in. For example the same document with HTML:

<h1>My shopping list</h1>
<ul>
    <li>Bread</li>
    <li>Milk</li>
    <li>Eggs</li>
    <li>Bacon</li>
</ul>

Now, even if we weren't able to understand the actual data, we have a contextual backdrop to intpret the data. We have a heading, an unordered list, which has a collection of list items.

<h1>Xasdk bop boop</h1>
<ul>
    <li>Zorch</li>
    <li>Quach</li>
    <li>Iach</li>
    <li>Xeru</li>
</ul>

I have no idea what that means, but atleast I know its a heading and an unordered list. That is the way the browser sees your HTML document; Some data, wrapped in context.

What is a div? How is it different from other HTML elements?

HTML elements define context; They describe the content they wrap around. HTML shouldn't alter or change the meaning of the data, it simply augments it and defines relationships between the data: parent, child, sibling, ancestor... So a li element describes a list item. A h1 element describes a heading. A table element describes a table, and so on.

So, what is a div then? Well, a div is an block-level HTML element that has no context of its own. By itself, it doesn't mean anything (other than it is a block).

While most other HTML elements (with the exception of the span element) have some kind of implicit context, the div element does not. That is a huge difference. It's a blank box. It's a box that doesn't mean anything. When you put something in a 'div', you are saying that its in a box, but that box doesn't really mean much.

So what is the point of a div then?

The div tag provides a blank slate for you to define your own context. Back to our shopping list example, right now, there is a weak relationship between the unordered list and the heading. They are weakly associated siblings, they just happen to be next to each other, but nothing really binds them together as a unit. What we would really like to say is:

<grocery_list>
    <h1>My shopping list</h1>
    <ul>
        <li>Bread</li>
        <li>Milk</li>
        <li>Eggs</li>
        <li>Bacon</li>
    </ul>
</grocery_list>

But we can't do that within the confines of the HTML spec. But what we can do is this: Stick them in a 'box':

<div>
    <h1>My shopping list</h1>
    <ul>
        <li>Bread</li>
        <li>Milk</li>
        <li>Eggs</li>
        <li>Bacon</li>
    </ul>
</div>

What does it mean when a element has a class (or collection of classes)?

But, again, that box doesn't mean that much right now. What we really would like to do is give that box some context of our own. We want to invent our own element. Thats where the class attribute comes into play. While HTML elements augment data, HTML attributes augment elements. We can say:

<div class="shopping_list">
    <h1>My shopping list</h1>
    <ul>
        <li>Bread</li>
        <li>Milk</li>
        <li>Eggs</li>
        <li>Bacon</li>
    </ul>
</div>

So we are saying that our div is really a shopping_list. That shopping_list has a heading, and an unordered list of items. HTML is supposed to make your data more clear, not less clear.

So, finally, how does this all relate to your question?

When you are writing CSS, you are leveraging your context (elements, classes, ids, and the relationship between elements) to define style.

So back to the shopping list example. I could write a stlye that said

<style>
    ul {
        background-color: red;
    }
</style>

But what am I really saying? I'm saying: "All unordered lists should have a background color of red". And the question is: Is that really what I mean? When writing CSS you should keep your structure in mind. Is it right to say all div elements should look a particilar way, or say only divs with a specific class? For example, I would aruge that this might be better:

div.shopping_list h1 { font-weight: bold; font-size: 2em; border-bottom: 1px solid black; }
div.shopping_list ul li { 
    margin-bottom: 1ex;
}

Here, I am saying that these elements, in this particular context should look this particular way.

So in your example, what does a div with a class of test really mean? What is the content? What context are you trying to clarify? Then that will tell you what your style selectors should look like.

For example.

<div class="shopping_list important">
    <h1>My shopping list</h1>
    <ul>
        <li>Bread</li>
        <li>Milk</li>
        <li>Eggs</li>
        <li>Bacon</li>
    </ul>
</div>

<table class="budget">
    <tbody>
        <tr class="important">
            <tr>Account Balance</tr><td>$0.00</td>
        </tr>
</table>

Is a css selector of .important a good idea? Is an "important shopping list" the same thing as an "important table row in a budget table"?

And only you can answer that, depending on what your data is and how you have decided to mark up that data.

There are a bunch of technical topics to get into about CSS specificty, good practices for maintaining complex style sheets, complex associations between elements. But ultimately it all boils down to answering these questions:

  1. What am I trying to communicate? (Data)
  2. What context is the data in? (HTML)
  3. What should that look like? (CSS)

Once you can answer those questions, then everything else will start to fall into place.

Would it be better to use Asp.net mvc or web services?

8 votes

I have asp.net mvc app written a couple of years ago and the more I add to it, I tend to make REST/AJAX calls to the controller to get data from it.

My question is do I carry on working in this way or should I expose the data as a separate REST services (WCF way of doing things)?

It feels that the boundary on what a mvc app is designed to do and the design of web service is getting blurred. The Mvc app (apart from separation) initially produced web pages, now it is being used to provide service based data.

JD

I see two possible scenarios

Single web app. In this case you carry on adding methods to the controller. This is good because it keeps relevant to the controller functionality in one place and will save you time. It is not suitable if the controller is being called from another web application. Simple, ugly but works, takes little time for development and much time for maintenance.

Web app + web service. You can segregate data retrieval methods into the service interface. The positive side is that you system becomes much more modular and independent, which is good for maintenance. If you predict that there will be other methods that will be added soon or if the methods are used by other web applications, then this path is probably better than extending the current web app. The negative side is that the new service will require some refactoring to the current web application and will take time to be developed/tested etc. This decision brings more complexity, but makes your application easy to be extended.

How to run java script code before page load?

7 votes

I have working in asp.net web application. Here I need to run javascript before page load.

I have gone through

<body oninit="funinit();" onprerender="funRender();" onload="funload();">


</body>

 <script type="text/javascript" language="javascript">
    function funinit() {
        alert("funinit");
    }
    function funload() {
        alert("funload");
    }
    function funRender() {
        alert("funRender");
    }      

</script>

here only funload() is working. plz give me any solution to run script before page load.

You can use window.onpaint for such purpose like :

<script type="text/javascript">
function preloadFunc()
{
alert("PreLoad");
}
window.onpaint = preloadFunc();
</script>

I hope it helps you....

How do I optimize my website for slow data connections?

7 votes

I'm about to start work on performing some performance enhancements for one of our products. Our users connect to the network using radio which is extremely slow. The main bottlenecks in the application are the network and the database. I am going to be focusing on reducing the network footprint of the application.

I am going to start with a few "quick wins" before I get down to the nitty gritty of tearing apart UpdatePanels, removing unnecessary content and whatever else I can think of. Right now I have a few things that I think I'm ready to implement
These include

Edit : The assets minification and white space cleaning tools work quite well together.

However I have a few things that I'm not sure how I'll address.

  1. Some microsoft resources (WebResource.axd?d=blahblah and ScriptResource.axd?d=blahblah) are not minified. This and This and a few others depending on the page. Microsoft.Ajax is fine though. How can I manually minify these files if they aren't being minified automatically? Am I missing a setting somewhere?

  2. Is it possible to combine the microsoft resources into a single js file with my javascript?

  3. 401 errors, In fiddler I can see that my first hit to the website always gives a 401 error it is immediately followed by the normal 200. Also other resources will randomly have a 401 on their first call as well. Is this some sort of IIS setting that needs to be configured to remove this unneeded call?

  4. Javascript inside aspx files. Unfortunately we have a lot of js inside our aspx files as well as a lot of javascript that gets rendered using ScriptManager.RegisterStartupScript in our code behinds. How would I go about minifying javascript within <script> tags in the aspx markup?

  5. Favicon, can this be diabled? If not what's the next best thing?

1 and 2) Optimize .axd: http://madskristensen.net/post/Optimize-WebResourceaxd-and-ScriptResourceaxd.aspx

3) HTTP 401 Unauthorized: You're configured authentication mechanism is doing this. If you have Windows authentication enabled but are not using it...

4) Embedded JS: MS AJAX Minifier

http://www.codeproject.com/Articles/81317/Automatically-compress-embedded-JavaScript-resourc

http://stephenwalther.com/blog/archive/2009/10/16/using-the-new-microsoft-ajax-minifier.aspx

There's not much you can do for JS mixed in with your markup. You could make your own utility to parse it out of the ASPX(s) with RegEx and create a file that contains all of it per page then minify that file and insert the 1 script reference. The regular expressions to capture everything within SCRIPT tags will end up being fairly complex because of corner cases like...

<script type="text/javascript">
document.write("<script>Dynamica, RegEx don't stop here -></script>");
</script>

5) Favicon: you either have a LINK tag on your page(s) that reference it with REL="shortcut icon" or you have a "favicon.ico" file sitting at the root of your web site. If you don't have the LINK tags then the browser will check for the favicon.ico at the root of your website automatically.

Dynamic form creation in asp.net c#

7 votes

So, I need some input refactoring an asp.net (c#) application that is basically a framework for creating dynamic forms (any forms). From a high level point of view, there is a table that has the forms, and then there is a table that has all the form fields, where it is one to many between the two. There is a validation table, where each field can have multiple types of validation, and it is a one to many from the form fields table to the validation table.

So the issue is that this application has been sold as the be-all-end-all customizable solution to all the clients. So, the idea is whatever form they want, we can build it jsut using DB configurations. The thing is, that is not always possible, because there is complex relationship between the fields, and complex relationship between the forms themselves. Also, there is only once codebase, and this is for multiple clients - all of whom host it on their own. There is very specific logic for each of the clients, and they are ALL in the same codebase, with no real separation. Sometimes it was too difficult to make it generic, so there are instances where it has hard coded logic (as in if formID = XXX then do _). You can also have nested forms, as in, one set of fields on its own within each form.

So usually, when one client requests a change, we make the change and deploy it to that client - but then another client requests a different change, and we make the change and deploy it for THAT client, but the change from the earlier client breaks it, and its a headache trying to debug, because EVERYTHING is dynamic. There is no way we can rollback the earlier change, because then the other client would be screwed.

Its not done in a real 3-tier architecture - its a web site with references to a DB class, and a class library. There is business logic in the web site itself, in the class library, and the database stored procs (Validation is done in the stored procs).

I've been put in charge of re-organizing the whole thing, and these are my thoughts/questions:

  1. I think this is a bad model in general, because one of the things I heard one of the developers say is that anytime any client makes a change, we should deploy to everybody - but that is not realistic, if we have say 20 clients - there will need to be regression testing on EVERYTHING, since we don't know the impact...

  2. There are about 100 forms in total, and their is some similarity in them (not much). But I think the idea that a dynamic engine can solve ALL form requests was not realistic as well. Clients come up with the most weird requests. For example, they have this engine doing a regular data entry form AND a search form.

  3. There is a lot of preserving state between pages, and it is all done using session variables, which is ok, except that it is not really tracked, and so sessions from the same user keep getting overwritten, and I think sessions should be got rid of.

  4. Should I really just rewrite the whole thing? This app is about 3 years old, and there has been lots of testing and things done, and serious business logic implemented, so I hate to get rid of all that (joel's advice). But its really a mess of a sphagetti code, and everything takes forever to do, and things break all the time because of minor changes.

I've been reading Martin Fowlers "Refactoring" and Michael Feathers "working effectively with legacy code" - and they are good, but I feel they were written for an application that was 'slightly' better architected, where it is still a 3-tiered architecture, and there is 'some' resemblance of logic..

Thoughts/input anyone?

Oh, and "Help!"

My current project sounds like almost exactly the same product you're describing. Fortunately, I learned most of my hardest lessons on a former product, and so I was able to start my current project with a clean slate. You should probably read through my answer to this question, which describes my experiences, and the lessons I learned.

The main thing to focus on is the idea that you are building a product. If you can't find a way to implement a particular feature using your current product feature set, you need to spend some additional time thinking about how you could turn this custom one-off feature into a configurable feature that can benefit all (or at least many) of your clients.

So:

  1. If you're referring to the model of being able to create a fully customizable form that makes client-specific code almost unnecessary, that model is perfectly valid and I have a maintainable working product with real, paying clients that can prove it. Regression testing is performed on specific features and configuration combinations, rather than a specific client implementation. The key pieces that make this possible are:
    1. An administrative interface that is effective at disallowing problematic combinations of configuration options.
    2. A rules engine that allows certain actions in the system to invoke customizable triggers and cause other actions to happen.
    3. An Integration framework that allows data to be pulled from a variety of sources and pushed to a variety of sources in a configurable manner.
    4. The option to inject custom code as a plugin when absolutely necessary.
  2. Yes, clients come up with weird requests. It's usually worthwhile to suggest alternative solutions that will still solve the client's problem while still allowing your product to be robust and configurable for other clients. Sometimes you just have to push back. Other times you'll have to do what they say, but use wise architectural practices to minimize the impact this could have on other client code.
  3. Minimize use of the session to track state. Each page should have enough information on it to track the current page's state. Information that needs to persist even if the user clicks "Back" and starts doing something else should be stored in a database. I have found it useful, however, to keep a sort of breadcrumb tree on the session, to track how users got to a specific place and where to take them back to when they finish. But the ID of the node they're actually on currently needs to be persisted on a page-by-page basis, and sent back with each request, so weird things don't happen when the user is browsing to different pages in different tabs.
  4. Use incremental refactoring. You may end up re-writing the whole thing twice by the time you're done, or you may never really "finish" the refactoring. But in the meantime, everything will still work, and you'll have new features every so often. As a rule, rewriting the whole thing will take you several times as long as you think it will, so don't try to take the whole thing in a single bite.

How do you duplicate "freeze pane" functionality on an HTML table?

7 votes

I have a widget in an ASP.NET project that I'm developing for my job. It has to be 300 pixels wide and cannot be any wider. Unfortunately what they want has proven to be fairly complicated for such a small widget. Here is what I have right now:

As you can see, this is a jQuery UI accordion control. As each accordion pane expands an ajax call is made to load its contents asynchronously. Right now it spits out an HTML table containing the desired data. The table is within a DIV with style overflow: auto; so that we get scroll bars on the bottom and the right.

My problem is that I want some pretty custom functionality (like the freeze pane ability in excel). When scrolling left and right I want all rows, including header, to scroll left and right except for the far left column, "product name". Like this:

When scrolling up and down I want all columns, including the left column, to scroll up and down except for the header row. Like this:

What is the best way to achieve this functionality? Or is there a way?

I built something somewhat similar, but much less complex: I wanted the first row of the table (the headers) to be frozen while the data rows scrolled vertically. I implemented it as 2 different tables, each with fixed-width cells, each in their own DIV. The "header" div simply sat static, and the "body" div used overflow:auto to scroll.

Your problem is more complex, because you want to "freeze panes" on both axes, and support scrolling on both axes (I had a lot more real estate to work with, and didn't have to account for horizontal scrolling at all). Nevertheless, I wonder if you could start from that position and work from there...

Define 4 divs:

  • NW: this one doesn't scroll at all, ever. It's the "product name" cell in your example
  • NE: this one scrolls horizontally only. It's the top/header row in your example
  • SW: this one scrolls vertically only. It's the left-side column in your example
  • SE: this one scrolls both directions. It's the primary data grid in your example

With 4 DIVs, you'd be dealing with 4 distinct tables, so we'll need to keep their cell widths and cell heights in sync. Ideally we could do this at render-time, if we can make them fixed values. Otherwise, we might be able to write some client-side jquery/JS to iterate the cells in the SE table when the page first loads (or is resized), and force the size of the other tables to match them.

With 4 DIVs, we also need to synchronize scrolling: when SE scrolls horizonally, NE must scroll to the same position. When SE scrolls vertically, SW must scroll to the same position. I suspect there must be some client-side scrolling events we can hook, to detect when SE is scrolled. Within those events, we should be able to force NE and/or SW to be scrolled the same way.

Sorry this is such a vague/abstract response. The nitty-gritty of implementing something like this will take more time than I could comfortably steal away from my main work. But this is something that's been rattling around in my brain, so figured I share it with you. I hope it gets you at least a little closer to a solution. Cheers!

how to call an ASP.NET c# method using javascript

7 votes

Does anyone know how to call a server-side c# method using javascript? What i need to do is to stop imports if Cancel is chosen or to continue importing if ok is chosen. I am using visual studio 2010 and c# as my programming lanaguage

This is my code:

private void AlertWithConfirmation()            
{                 
    Response.Write(
        "<script type=\"text/javascript\">" +     
            "if (window.confirm('Import is currently in progress. Do you want to continue with importation? If yes choose OK, If no choose CANCEL')) {" +     
                "window.alert('Imports have been cancelled!');" +     
            "} else {" +   
                "window.alert('Imports are still in progress');" +     
            "}" +      
        "</script>");   
}

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:-

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true. This will tell ScriptManager that I am going to call Page Methods from client side.

Now Next step is to Create a Server Side function. Here is the function which I created, this function validates user's input:-

[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }

    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password canonot be less than 5 chars";
    }

    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things. First this method should be 'public static'. Second there should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:-

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods. My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

What's the meaning of Web Page life-cycle?

7 votes

I'm new to C# and ASP.NET. I hear a lot about application and/or web page life-cycle. I want to know what's the meaning of this?

THe page lifecycle is the sequence of events that are invoked in an ASP.NET Page Request.

This is documented in great detail here.

split huge 40000 page pdf into single pages, itextsharp, outofmemoryexception

6 votes

I am getting huge PDF files with lots of data. The current PDF is 350 MB and has about 40000 pages. It would of course have been nice to get smaller PDFs, but this is what I have to work with now :-(

I can open it in acrobat reader with some delay when loading but after that acrobat reader is quick.

Now I need to split the huge file into single pages, then try to read some recipient data from the pdf pages, and then send the one or two pages that each recipient should get to each particular recipient.

Here is my very small code so far using itextsharp:

var inFileName = @"huge350MB40000pages.pdf";
PdfReader reader = new PdfReader(inFileName);
var nbrPages = reader.NumberOfPages;
reader.Close();

What happens is it comes to the second line "new PdfReader" then stays there for perhaps 10 minutes, the process gets to about 1.7 GB in size, and then I get an OutOfMemoryException.

I think the "new PdfReader" attempts to read the entire PDF into memory.

Is there some other/better way to do this? For example, can I somehow read only a part of a PDF file into memory instead of all of it at once? Could it work better using some other library than itextsharp?

From what I have read, it looks like when instantiating the PdfReader that you should use the constructor that takes in a RandomAccessFileOrArray object. Disclaimer: I have not tried this out myself.

iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(@"C:\PDFFile.pdf"), null);

How can I highlight only certain areas of an image?

6 votes

I've got an image of a human skeleton with approx 60 areas I want to highlight and make clickable. Those are in a circle and numbered from 1-60.

The whole idea is I want to click on the nubmers (on the image) and highlight that part of the image.

I've used JQuery to hover over the numbers/area and highlight (hover over with mouse) and when the user clicks on the number I'm getting the clicked number and processing on the server side code. (.NET C#)

But I want the place where I click should remain the colour... Hovering over the number and changing the colour works fine... But I want when it's click the colour should change on the image / persisted...

Below are the samples which changes the colour when you hover over with your mouse, but when you click the colour is not changing.

http://davidlynch.org/js/maphilight/docs/

http://davidlynch.org/js/maphilight/docs/demo_simple.html

any ideas how to highlight the some areas on the image?

sample code below:

 <img class="map" src="Images/Figure_Human_Image1.png" alt="" usemap="#Skeleton17"  / >
 <map name="Skeleton17" >
 <area title="1" alt="1" href="#" shape="circle" coords="13,174,7" / >
 <area title="2" alt="2" href="#" shape="circle" coords="27,159,7" / >

How to PERMANENT highlight on the image

The answers about swapping out images will work. That said, by doing this in images, you end up using more bandwidth than you really need to use for this. One of two things will happen: either people will download a bunch of images that they never load, or they will have to wait to download the new image each time they click. For users with a high speed connection, that's not going to be an issue, but there is definitely room for users on slow connections (or perhaps mobile devices) to experience this as a negative.

Better would be to only have one version of the image, which is what it looks like on the first load. The trick is to make the numbers on the image transparent. Then you can just have the user's browser change the background color when they click. And as a bonus, if you ever want to add other colors to indicate other things, that's simple too! And you can have any combination of numbers highlighted.

After some experimentation, I found that the style attribute on the <area> can't be used to set background colors, so you would need something else to enforce the colors. I suggest a <div> positioned in the same place as each circle via something like: <div id='div1' style='position:relative; top:-400px; left:5px; height:30px; width:30px; z-index:-1'>&nbsp;</div> where you would adjust the top/left values to place it where you need it. The z-index:-1 is important to make it show up behind the image. To experiment with the placing of these divs, you may want to go ahead and set the background-color to something so that you can see them.

Once you have a transparent image and have all of the divs placed, you'd just need a bit of jQuery to activate it. Something like this:

$('area').click(function(){
    var number = $(this).attr('title');
    $('#div'+number).css('background-color', 'red');
})

.net .ToTitleCase not working on all upper case string

6 votes
   Public Function TitleCase(ByVal strIn As String)
          Dim result As String = ""
          Dim culture As New CultureInfo("en", False)
          Dim tInfo As TextInfo = culture.TextInfo()
          result = tInfo.ToTitleCase(strIn)
          Return result
     End Function

If I input "TEST" into the function above. The output is "TEST". Ideally it would output "Test"

I also tried the code snippets from this post to no avail: Use of ToTitleCase

Thanks in advance!

If memory serves, ToTitleCase() never seemed to work for all capitalized strings. It basically requires you to convert the string to lowercase prior to processing.

From the MSDN:

Generally, title casing converts the first character of a word to uppercase and the rest of the characters to lowercase. However, this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym.

Workaround Usage (in C#):

string yourString = "TEST";

TextInfo formatter = new CultureInfo("en-US", false).TextInfo;    
formatter.ToTitleCase(yourString.ToLower());

.net object explorer control

6 votes

Does anyone know of an object explorer control for .net winforms (or webforms)?
By "object explorer" I mean something like the visual studio object explorer that I can use it in my own program.

I found these links on the net:
1. http://www.codeproject.com/KB/trace/oe.aspx - It is pretty old and I don't know if relevant today.
2. http://www.pcreview.co.uk/forums/can-embed-vs-nets-object-explorer-program-t1342274.html - nobody answers him..

I used this code in order to build an object tree: http://www.codeguru.com/csharp/csharp/cs_syntax/reflection/article.php/c5885

Is a webmethod in codebehind as secure as the page it is on?

6 votes

This is kind of confusing me. I would assume the webmethod would follow the same authorization rules set in the web.config as the page it is on. Will it execute the normal page lifecycle first? In my case there is extra logic in a basepage that checks further permissions. Will this logic be executed before the webmetod is called to prevent access from users not permitted to access that page?

A webmethod must be static and it does not follow the normal ASP.NET lifecycle.

In a webmethod, you can't access the session or the controls on the page.

Since it won't go through all the events, I don't think your PreInit will be called so you won't be able to restrict access through that.

ASP.NET MVC - Approach for global error handling?

5 votes

I was wondering what the best implementation for a global error (doesn't have to be errors, can also be success messages) handler would be? Let me break it down for you with an example:

  1. User tries to delete a record
  2. Deletion fails and an error is logged
  3. User redirects to another page
  4. Display error message for user (using a HtmlHelper or something, don't want it to be a specific error page)

I'm just curious what you guys think. I've been considering TempData, ViewData and Session but they all have their pros and cons.

TIA!

UPDATE:

I'll show an example what I exactly mean, maybe I wasn't clear enough. This is an example of a method that adds a message when user deletes a record. If user succeeds, user redirects to another page

public ActionResult DeleteRecord(Record recordToDelete)
{
    // If user succeeds deleting the record
    if (_service.DeleteRecord(recordToDelete) 
    {
        // Add success message
        MessageHandler.AddMessage(Status.SUCCESS, "A message to user");

        // And redirect to list view
        return RedirectToAction("RecordsList");
    }
    else 
    {
        // Else return records details view
        return View("RecordDetails", recordToDelete);
    }
}

And in the view "RecordsList", it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.

<%= Html.RenderAllMessages %>

This can be achieved in many ways, I'm just curious what you guys would do.

UPDATE 2:

I have created a custom error (message) handler. You can see the code if you scroll down.

I'm confused by these steps:

  • Deletion fails and an error is logged
  • User redirects to another page

Why would you redirect the User when an error occurs? That doesnt make any sense, unless im misunderstanding something.

Generally, i follow these guidelines:

  • Error with form submission (e.g HTTP POST): check ModelState.IsValid and return the same View and render the error out with @Html.ValidationSummary()
  • Error with AJAX call: return JsonResult (like @Tomas says), and use basic client-side scripting to inspect the JSON and show the result
  • Error with domain/business: throw custom exceptions and let the controller catch them and add to ModelState as above

Calling a .NET Function that requires a .NET type from Classic ASP

4 votes

Please Help me.I am trying to over come this paoblem from last 2 days But i am not able to overcome.

I was able to set up the environment so that I can call .NET method (via COM) from a classic ASP page.

Everything actually works as intended until when I have to call a .NET method that requires a .NET type.

So I have a method named SetTable Like Below

I have a function like this in .Net

Public Sub SetTable(ByVal _City As City, ByVal _Country As Country)
          'doing some thing
End Sub

and i have asp code like this:

dim CountryUtil, City, Country
set CountryUtil= Server.CreateObject("mydll.CountryUtil")
set City= Server.CreateObject("mydll.City")
set Country = Server.CreateObject("mydll.Country")
city.id= 123
city.property = "so and so"

Country.id= 123
Country.property = "so and so"

CountryUtil.SetTable(City, Country)

' I get this error here:

'Microsoft VBScript runtime error '800a0005' 'Invalid procedure call or argument: 'SetTable'

Thanks in advance.

in vbscript you only have variants so Country and City are just objects of type variant not of type Country or City.

you will have to change the .net method SetTable (or write a new one) which accepts "variants" (object) and then cast those objects to your .net City and Country objects.

Calling a javascript function from a modal window in vb.net

4 votes

I want to calling a javascript function from a asp.net modal window using vb. The javascript function is to close the same modal window.

The function I want call is: function CloseModalWindow(winName)

I tried

Page.ClientScript.RegisterStartupScript  

but that does not work. How can I do that from vb.net code behind?

You're actually on the exact right track.

You should find that you are able to call the described method by using something like this...

ClientScript.RegisterStartupScript(Me.GetType, Guid.NewGuid().ToString(), "window.parent.CloseModalWindow('WindowName');", True)