Best asp.net questions in June 2012

What is the difference between an Azure Web Site and an Azure Web Role

9 votes

What are the material differences between the new Azure Web Sites and the traditional Azure Web Roles for an ASP.NET MVC application? What reason would I choose a "web site" over a "web role" or vice versa?

Let's assume that I would need equal capacity in either case (e.g. 2 small instances). The prices seem comparable other than the fact that there is a 33% temporary discount for web sites while they are in their preview period.

Are there things that I can do with a "web site" that are difficulty or impossible with a web role? For example, does it become easy to put multiple web sites in a single set of VMs using "web sites"? Do I lose anything with a "web site" vs a "web role"? Ability to fine tune IIS? Ability to use the Cache service locally?

Web Roles give you several features beyond Web Sites:

  • Ability to run elevated startup scripts to install apps, modify registry settings, install performance counters, fine-tune IIS, etc.
  • Ability to split an app up into tiers (maybe Web Role for front end, Worker Role for backend processing) and scale independently
  • Ability to RDP into your VM for debugging purposes.
  • Network isolation

Web Sites have advantages over Web Roles though:

  • Near-instant deployment
  • git + ftp support
  • Ability to roll out one of numerous CMS's (like WordPress, Joomla, etc.)
  • Use of SQL Database or MySQL

Here's a screengrab I just took from the gallery selection form: enter image description here

I think Web Sites are a great way to get up and running quickly, where you can move from shared to reserved resources. Once you outgrow this, you can then move up to Web Roles and expand as you need.

How different async programming is from Threads?

9 votes

I've been reading some async articles here: http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45 and the author says :

When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the async method call and the await.

So what I am trying to understand is, how does it become async if we don't use any Threads for concurrent execution? What does it mean "you're not always using a thread."?

Let me first explain what I know regarding working with threads (A quick example, of course Threads can be used in different situations other than UI and Worker methodology here)

  1. You have UI Thread to take input, give output.
  2. You can handle things in UI Thread but it makes the UI unresponsive.
  3. So lets say we have a stream-related operation and we need to download some sort of data.
  4. And we also allow users to do other things while it is being downloaded.
  5. We create a new worker thread which downloads the file and changes the progress bar.
  6. Once it is done, there is nothing to do so thread is killed.
  7. We continue from UI thread.

We can either wait for the worker thread in UI thread depending on the situation but before that while the file is being downloaded, we can do other things with UI thread and then wait for the worker thread.

Isn't the same for async programming? If not, what's the difference? I read that async programming uses ThreadPool to pull threads from though.

Threads are not necessary for asynchronous programming.

"Asynchronous" means that the API doesn't block the calling thread. It does not mean that there is another thread that is blocking.

First, consider your UI example, this time using actual asynchronous APIs:

  1. You have UI Thread to take input, give output.
  2. You can handle things in UI Thread but it makes the UI unresponsive.
  3. So lets say we have a stream-related operation and we need to download some sort of data.
  4. And we also allow users to do other things while it is being downloaded.
  5. We use asynchronous APIs to download the file. No worker thread is necessary.
  6. The asynchronous operation reports its progress back to the UI thread (which updates the progress bar), and it also reports its completion to the UI thread (which can respond to it like any other event).

This shows how there can be only one thread involved (the UI thread), yet also have asynchronous operations going on. You can start up multiple asynchronous operations and yet only have one thread involved in those operations - no threads are blocked on them.

async/await provides a very nice syntax for starting an asynchronous operation and then returning, and having the rest of the method continue when that operation completes.

ASP.NET is similar, except it doesn't have a main/UI thread. Instead, it has a "request context" for every incomplete request. ASP.NET threads come from a thread pool, and they enter the "request context" when they work on a request; when they're done, they exit their "request context" and return to the thread pool.

ASP.NET keeps track of incomplete asynchronous operations for each request, so when a thread returns to the thread pool, it checks to see if there are any asynchronous operations in progress for that request; if there are none, then the request is complete.

So, when you await an incomplete asynchronous operation in ASP.NET, the thread will increment that counter and return. ASP.NET knows the request isn't complete because the counter is non-zero, so it doesn't finish the response. The thread returns to the thread pool, and at that point: there are no threads working on that request.

When the asynchronous operation completes, it schedules the remainder of the async method to the request context. ASP.NET grabs one of its handler threads (which may or may not be the same thread that executed the earlier part of the async method), the counter is decremented, and the thread executes the async method.

ASP.NET vNext is slightly different; there's more support for asynchronous handlers throughout the framework. But the general concept is the same.

For more information:

How to display the Asynchronous results which one is first in asp.netweb application?

9 votes

I have to send three asynch requests in three class files, 3 requests response times are different, first one is 2sec and second one is 7sec and third one is 4sec , now i have to display first response in browser with in 2sec and after 2sec display the third response and finally display the second response , but now my results all responses display at a time after completed three responses, please give me any suggestion, it is very urgent, please.....

my code is

public delegate string AsyncMethodCaller(string name);
        public delegate string AsyncMethodCallertest(string name);
        public delegate string NatilusAsyn(string name);

button click event

     AsyncMethodCaller caller = new AsyncMethodCaller(ps.PennStarService);
        IAsyncResult result = caller.BeginInvoke(txtFirst.Text, null, null);
    NatilusAsyn caller123 = new NatilusAsyn(cs.PennStarService);
        IAsyncResult result123 = caller123 .BeginInvoke(txtthird.Text, null, null);
        AsyncMethodCallertest cltest = new AsyncMethodCallertest(ps.testHi);
        IAsyncResult tetsresult = cltest.BeginInvoke(txtSecond.Text, null, null);
        lblFirst.Text = caller.EndInvoke(result);           
        lblSecond.Text = cltest.EndInvoke(tetsresult);
     lblthird.Text = caller123.EndInvoke(result123); 

thank u hemanth

I think the root of the problem is to understand what happens with an ASP.Net request.

Each page has its life-cycle which includes a pipeline of events, for more information check this answer. Each request is handled by a worker thread from the AppDomain of the current application. The response won't be sent to the user until the page pipeline is completed.

About threads:

The number of simultaneous available threads can be configured in the machine.config. The key point to understand is that these number of threads are fixed, which means that when the max number of simultaneous threads has been reached, subsequent requests will be placed in a queue, the number of requests that can be placed in the queue are only limited by the memory of the server.

When a worker thread calls a long time-consuming operation, you are blocking that thread, until the operation finishes, which means again, if there are several concurrent users, potentially all available threads could be blocked, forcing new requests to be placed in a queue and in the worst case, causing a 503 error - Service Unavailable.

The way to prevent this is by calling these kind of methods in background threads. Similar to your code, but the behavior is not what you are expecting in this case, your code is waiting for the threads to end in order to finish the page request that's the reason you are receiving the result at the same time (at the end of the request).

For more details about executing asp.net pages asynchronously, refer to this excellent article

Now in order to get the results you need:

(This is a full working example, in this example, I am using Rx - Reactive Programming to run long time-consuming methods in a new thread, you can change this to use another framework if you like, I prefer using Rx because I feel more comfortable with the API)

Using PageMethods

Code behind

    [WebMethod]
    public static string Execute1()
    {
        JavaScriptSerializer j = new JavaScriptSerializer();
        string r = string.Empty;
        var o = Observable.Start(() =>
            {
                Thread.Sleep(2000);
                r = "My Name1: " + DateTime.Now.ToString() + " Background thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
            }, Scheduler.NewThread);
        o.First();
        r += " Main thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        r = j.Serialize(new { res = r });
        return r;
    }

    [WebMethod]
    public static string Execute2()
    {
        JavaScriptSerializer j = new JavaScriptSerializer();
        string r = string.Empty;
        var o = Observable.Start(() =>
        {
            Thread.Sleep(7000);
            r = "My Name2: " + DateTime.Now.ToString() + " Background thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        }, Scheduler.NewThread);
        o.First();
        r += " Main thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        r = j.Serialize(new { res = r });
        return r;
    }

    [WebMethod]
    public static string Execute3()
    {
        JavaScriptSerializer j = new JavaScriptSerializer();
        string r = string.Empty;
        var o = Observable.Start(() =>
        {
            Thread.Sleep(4000);
            r = "My Name3: " + DateTime.Now.ToString() + " Background thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        }, Scheduler.NewThread);
        o.First();
        r += " Main thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        r = j.Serialize(new { res = r });
        return r;
    }

ASPX

....
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
....
<asp:ScriptManager runat="server" />
<input type="button" id="callAsync" name="callAsync" value="Call Async" />
<div id="first"></div>
<script type="text/javascript">
    function onsuccess1(msg) {
        var result = Sys.Serialization.JavaScriptSerializer.deserialize(msg.d);
        var h = $("#first").html();
        $("#first").html( h + "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Result: " + result.res);
    }
    function onerror1(xhr) {
        alert(xhr.responseText);
    }
    function callMyMethod(url, mydata, onsuccess, onerror) {
        var h = $("#first").html();
        $("#first").html(h + "<br/>&nbsp;&nbsp;Calling Method: " + new Date());
        return $.ajax({
            cache: false,
            type: "POST",
            async: true,
            url: url,
            data: mydata, 
            contentType: "application/json",
            dataType: "json",
            success: function (msg) {
                onsuccess(msg);
            },
            error: function (xhr) {
                onerror(xhr);
            }
        });
    }
    $(document).ready(function () {
        $("#callAsync").click(function () {
            var h = $("#first").html();
            $("#first").html(h + "<br/>New call: " + new Date());
            callMyMethod("DynamicControls.aspx/Execute1", "{}", function (data) { onsuccess1(data); }, function (data) { onerror1(data); });
            callMyMethod("DynamicControls.aspx/Execute2", "{}", function (data) { onsuccess1(data); }, function (data) { onerror1(data); });
            callMyMethod("DynamicControls.aspx/Execute3", "{}", function (data) { onsuccess1(data); }, function (data) { onerror1(data); });
        });
    });
</script>

Output

This code generates the following:

New call: Fri Jun 22 02:11:17 CDT 2012
  Calling Method: Fri Jun 22 02:11:17 CDT 2012
  Calling Method: Fri Jun 22 02:11:17 CDT 2012
  Calling Method: Fri Jun 22 02:11:17 CDT 2012
    Result: My Name1: 6/22/2012 2:11:19 AM Background thread: 38 Main thread: 48
    Result: My Name2: 6/22/2012 2:11:26 AM Background thread: 50 Main thread: 48
    Result: My Name3: 6/22/2012 2:11:30 AM Background thread: 52 Main thread: 48

As you can see the code is not optimized, the main thread is being locked, the max number of seconds we set up are 7 but in this case, from the time the server code was called (02:11:17) until the last response received (2:11:30) 13 seconds elapsed. This is because ASP.Net by default locks the current Session object locking the main thread. Since we are not using the session in this example, we can configure the page like this:

<%@ Page EnableSessionState="False"

And the new output is:

New call: Fri Jun 22 02:13:43 CDT 2012
  Calling Method: Fri Jun 22 02:13:43 CDT 2012
  Calling Method: Fri Jun 22 02:13:43 CDT 2012
  Calling Method: Fri Jun 22 02:13:43 CDT 2012
    Result: My Name1: 6/22/2012 2:13:45 AM Background thread: 52 Main thread: 26
    Result: My Name3: 6/22/2012 2:13:47 AM Background thread: 38 Main thread: 49
    Result: My Name2: 6/22/2012 2:13:50 AM Background thread: 50 Main thread: 51

Now, only 7 seconds elapsed from the first server method call to the last response received without locking the main thread =)

Edit 1

If my understanding is correct, you need to pass some parameters to the methods and return datasets to fill labels and textboxes.

To pass parameters to the PageMethods, this is a way to do it:

Install these Nuget Package:

Command class. This class will represent the parameters you want to send to the server method in the post action

public class ProcessXmlFilesCommand
{
    public string XmlFilePath { get; set; }

    public ProcessXmlFilesCommand()
    {
    }
}

Instead of returning a DataSet, I think it would be easier and more manageable to return an IEnumerable, something like this:

    [WebMethod]
    public static IEnumerable<MyResult> ProcessXmlFiles(ProcessXmlFilesCommand command)
    {
        List<MyResult> results = new List<MyResult>();
        var o = Observable.Start(() =>
        {
            // here do something useful, process your xml files for example
            // use the properties of the parameter command
            results.Add(new MyResult { SomethingInteresting = DateTime.Now.ToString(), FilePath = command.XmlFilePath + "Processed" });
            results.Add(new MyResult { SomethingInteresting = DateTime.Now.ToString(), FilePath = command.XmlFilePath + "Processed" });
            results.Add(new MyResult { SomethingInteresting = DateTime.Now.ToString(), FilePath = command.XmlFilePath + "Processed" });
            Thread.Sleep(2000);
        }, Scheduler.NewThread);
        o.First();
        return results.AsEnumerable();
    }

The MyResult class represents the data you want to send back to the user

public class MyResult
{
    public string SomethingInteresting { get; set; }
    public string FilePath { get; set; }
}

In your ASPX page

<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="Scripts/json2.min.js"></script>


    <script type="text/javascript">
        function processFiles() {
            var filePath = $("#filePath").val();
            var command = new processFilesCommand(filePath);
            var jsonCommand = JSON.stringify(command);

            $.ajax({
                cache: false,
                type: "POST",
                async: true,
                url: "CustomThreads.aspx/ProcessXmlFiles",
                data: "{'command':" + jsonCommand + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    onFileProcessedSuccess(msg);
                },
                error: function (exc) {
                    onFileProcessedError(exc);
                }
            });
        }
        function onFileProcessedSuccess(msg) {
            var response = msg.d;
            $.each(response, function (index, myResponse) {
                $("#<%:this.myLabel.ClientID %>").append(myResponse.SomethingInteresting + "<br/>");
            });
        }
        function onFileProcessedError(exc) {
            alert("Error: " + exc.responseText);
        }
        function processFilesCommand(filePath) {
            this.XmlFilePath = filePath;
        }
        $(document).ready(function () {
            $("#processFile").click(processFiles);
        });
    </script>

<input type="text" name="filePath" id="filePath" />
<input type="button" name="processFile" id="processFile" value="Process File" />

<br /><asp:Label ID="myLabel" runat="server" />

Edit 2

This is a simplified way

<%@ Page EnableSessionState="False" Language="C#" AutoEventWireup="true" CodeBehind="CustomThreadsSimple.aspx.cs" Inherits="WebApplication1.CustomThreadsSimple" %>
....
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
....
    <script type="text/javascript">
        function makeCall(url, data) {
            $("#<%:this.lblMessage.ClientID %>").append("<br/>Initializing call: " + new Date());
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8;",
                async: true,
                cache: false,
                data: "{name:'" + data + "'}",
                success: function (msg) {
                    $("#<%:this.lblMessage.ClientID %>").append("<br/>&nbsp;&nbsp;&nbsp;&nbsp;" + msg.d);
                },
                error: function (exc) {
                    alert(exc.responseText);
                }
            });
        }
        $(function () {
            $("#startProcess").click(function () {
                makeCall("CustomThreadsSimple.aspx/Execute1", $("#<%: this.txtData1.ClientID %>").val());
                makeCall("CustomThreadsSimple.aspx/Execute2", $("#<%: this.txtData2.ClientID %>").val());
                makeCall("CustomThreadsSimple.aspx/Execute3", $("#<%: this.txtData3.ClientID %>").val());
            });
        });
    </script>
    <asp:TextBox runat="server" ID="txtData1" />
    <asp:TextBox runat="server" ID="txtData2" />
    <asp:TextBox runat="server" ID="txtData3" />
    <input type="button" name="startProcess" id="startProcess" value="Start execution" />
    <asp:Label ID="lblMessage" runat="server" />

Code behind

public partial class CustomThreadsSimple : System.Web.UI.Page
{
    [WebMethod]
    public static string Execute1(string name)
    {
        string res = string.Empty;
        Func<string, string> asyncMethod = x =>
        {
            Thread.Sleep(2000);
            return "Res1: " + x +" " + DateTime.Now.ToString() + " Background thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        };

        IAsyncResult asyncRes = asyncMethod.BeginInvoke(name, null, null);
        res = asyncMethod.EndInvoke(asyncRes);
        res += " Main thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        return res;
    }

    [WebMethod]
    public static string Execute2(string name)
    {
        string res = string.Empty;
        Func<string, string> asyncMethod = x =>
        {
            Thread.Sleep(7000);
            return "Res2: " + x + " " + DateTime.Now.ToString() + " Background thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        };

        IAsyncResult asyncRes = asyncMethod.BeginInvoke(name, null, null);
        res = asyncMethod.EndInvoke(asyncRes);
        res += " Main thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        return res;
    }

    [WebMethod]
    public static string Execute3(string name)
    {
        string res = string.Empty;
        Func<string, string> asyncMethod = x =>
        {
            Thread.Sleep(4000);
            return "Res3: " + x + " " + DateTime.Now.ToString() + " Background thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        };

        IAsyncResult asyncRes = asyncMethod.BeginInvoke(name, null, null);
        res = asyncMethod.EndInvoke(asyncRes);
        res += " Main thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
        return res;
    }
}

Output

enter image description here

How can I unsubscribe to this .NET event?

9 votes

I wish to programatically unsubscribe to an event, which as been wired up.

I wish to know how I can unsubscribe to the EndRequest event.

I'm not to sure how to do this, considering i'm using inline code. (is that the correct technical term?)

I know i can use the some.Event -= MethodName to unsubscribe .. but I don't have a method name, here.

The reason I'm using the inline code is because I wish to reference a variable defined outside of the event (which I required .. but feels smelly... i feel like I need to pass it in).

Any suggestions?

Code time..

public void Init(HttpApplication httpApplication)
{
    httpApplication.EndRequest += (sender, e) =>
    {
        if (some logic) 
            HandleCustomErrors(httpApplication, sender, e,
                              (HttpStatusCode)httpApplication.Response.StatusCode);
    };

    httpApplication.Error += (sender, e) => 
            HandleCustomErrors(httpApplication, sender, e);
}

private static void HandleCustomErrors(HttpApplication httpApplication, 
                                       object sender, EventArgs e, 
                                       HttpStatusCode httpStatusCode =
                                           HttpStatusCode.InternalServerError)
{ ... }

This is just some sample code I have, for me to handle errors in a ASP.NET application.

NOTE: Please don't turn this into a discussion about ASP.NET error handling. I'm just playing around with events and using these events for some sample R&D / learning.

It's not possible to unsubscribe that anonymous delegate. You would need to store it in a variable and unsubscribe it later:

EndRequestEventHandler handler = (sender, e) =>
{
    if (some logic) 
        HandleCustomErrors(httpApplication, sender, e,
                          (HttpStatusCode)httpApplication.Response.StatusCode);
};

httpApplication.EndRequest += handler;
// do stuff
httpApplication.EndRequest -= handler;

asp.net asmx web service returning xml instead of json

8 votes

Why does this simple web service refuse to return JSON to the client?

Here is my client code:

        var params = { };
        $.ajax({
            url: "/Services/SessionServices.asmx/HelloWorld",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            timeout: 10000,
            data: JSON.stringify(params),
            success: function (response) {
                console.log(response);
            }
        });

And the service:

namespace myproject.frontend.Services
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class SessionServices : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

web.config:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

And the response:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

No matter what I do, the response always comes back as XML. How do I get the web service to return Json?

EDIT:

Here is the Fiddler HTTP trace:

REQUEST
-------
POST http://myproject.local/Services/SessionServices.asmx/HelloWorld HTTP/1.1
Host: myproject.local
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://myproject.local/Pages/Test.aspx
Content-Length: 2
Cookie: ASP.NET_SessionId=5tvpx1ph1uiie2o1c5wzx0bz
Pragma: no-cache
Cache-Control: no-cache

{}

RESPONSE
-------
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 19 Jun 2012 16:33:40 GMT
Content-Length: 96

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

I have lost count of how many articles I have read now trying to fix this. The instructions are either incomplete or do not solve my issue for some reason. Some of the more relevant ones include (all without success):

ASP.NET web service erroneously returns XML instead of JSON

asmx web service returning xml instead of json in .net 4.0

http://williamsportwebdeveloper.com/cgi/wp/?p=494

http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/

http://forums.asp.net/t/1054378.aspx

http://jqueryplugins.info/2012/02/asp-net-web-service-returning-xml-instead-of-json/

Plus several other general articles.

Any help greatly appreciated.

Finally figured it out.

The app code is correct as posted. The problem is with the configuration. The correct web.config is:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.webServer>
        <handlers>
            <add name="ScriptHandlerFactory"
                 verb="*" path="*.asmx"
                 type="type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                 resourceType="Unspecified" />
        </handlers>
    </system.webServer>
</configuration>

According to the docs, registering the handler should be unnecessary from .NET 4 upwards as it has been moved to the machine.config. For whatever reason, this isn't working for me. But adding the registration to the web.config for my app resolved the problem.

A lot of the articles on this problem instruct to add the handler to the <system.web> section. This does NOT work and causes a whole load of other problems. I tried adding the handler to both sections and this generates a set of other migration errors which completely misdirected my troubleshooting.

In case it helps anyone else, if I had ther same problem again, here is the checklist I would review:

  1. Did you specify type: "POST" in the ajax request?
  2. Did you specify contentType: "application/json; charset=utf-8" in the ajax request?
  3. Did you specify dataType: "json"in the ajax request?
  4. Does your .asmx web service include the [ScriptService]` attribute?
  5. Does your web method include the [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute? (My code works even without this attribute, but a lot of articles say that it is required)
  6. Have you added the ScriptHandlerFactory to the web.config file in <system.webServer><handlers>?
  7. Have you removed all handlers from the the web.config file in in <system.web><httpHandlers>?

Hope this helps anyone with the same problem. and thanks to posters for suggestions.

is there an asp.net fiddle?

7 votes

Similar to jsfiddle, is there an asp.net fiddle website for us to share asp.net code fiddles? It'll greatly help asp.net developers. the current way to post asp.net code on SO is not so reader friendly. I hope there's something out there to make this easier. If there isn't anything like that (as i did some search but can't find one). Is this even something technically possible to be developed since c# is not a late binding language.

You could use something like compilr.com, It requires an account to create projects but people can view it anonymously. It's pretty neat.

Example: http://compilr.com/cravecode/test-share/main.cs

UPDATE

I'd also checkout coderun.com/ide

SQL query for asp.net grid pagination

7 votes

I am using iBatis and SQLServer,

What is the best way for using offset and limit for pagging queries?

Maybe I add the column ROW_NUMBER() OVER (ORDER BY Id) AS RowNum, but this will only prevent data access for simple queries. There is some cases that I use union of selects. How to optmize these queries?

I don't know anything about ibatis, but I guess you could do this in SQL.

If I understand you correctly, you want to get paginate the results of a select statement or union of a few select statements.

I'd do it the following way. This could be a stored procedure for example, and there should probably be some sanity checking in there the check the values of offset and limit are greater than 0. If you do end up doing something like this, make sure you replace * with your column names too!

Here is an example with a union:

DECLARE @offset INT;
DECLARE @limit INT;

WITH cte
     AS (SELECT t.*,
                Row_number() OVER (ORDER BY Id) AS RowNum
         FROM   (SELECT *
                 FROM   Table1
                 UNION
                 SELECT *
                 FROM   Table2) t)
SELECT *
FROM   cte
WHERE  RowNum BETWEEN @offset AND @offset + @limit

Essentially what I've done is derived a new table from the union of two queries, as you said could happen in your case. I'm then adding a column with the row number to the result of that in a CTE, then only selecting the rows specified in @Offset and @limit + @offset to get back only the rows you've asked for.

E.g. Setting @offset = 50 and @limit = 50, you'd get back results 50-100 (as ordered by the criteria specified in the Row_number over clause.

(I hope this was the sort of thing you were looking for!)

Edit: This will only work in SQL Server 2005 onwards - you haven't mentioned which version you're using!

iTextSharp to print a gridview

7 votes

I use iTextSharp to print a grid view but I face some problems:

  1. No arabic characters appears at all.

  2. The direction is LTR and I wany it RTL instead.

  3. Some columns in the gridview are templatefields (label, imagebutton,...), and I can't handle this case. I won't show all of them (like delete button , ...)

The code :

 protected void ExportToPDF(GridView gvReport, bool LandScape)
        {
            int noOfColumns = 0, noOfRows = 0;
            DataTable tbl = null;

            if (gvReport.AutoGenerateColumns)
            {
                tbl = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
                noOfColumns = tbl.Columns.Count;
                noOfRows = tbl.Rows.Count;
            }
            else
            {
                noOfColumns = gvReport.Columns.Count;
                noOfRows = gvReport.Rows.Count;
            }

            float HeaderTextSize = 8;
            float ReportNameSize = 10;
            float ReportTextSize = 8;
            float ApplicationNameSize = 7;

            // Creates a PDF document

            Document document = null;
            if (LandScape == true)
            {
                // Sets the document to A4 size and rotates it so that the     orientation of the page is Landscape.
                document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
            }
            else
            {
                document = new Document(PageSize.A4, 0, 0, 15, 5);
            }

            // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
            iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

            // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
            mainTable.HeaderRows = 4;

            // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
            iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

            // Creates a phrase to hold the application name at the left hand side of the header.
            Phrase phApplicationName = new Phrase("Contact List", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.TIMES_ROMAN));

            // Creates a PdfPCell which accepts a phrase as a parameter.
            PdfPCell clApplicationName = new PdfPCell(phApplicationName);
            // Sets the border of the cell to zero.
            clApplicationName.Border = PdfPCell.NO_BORDER;
            // Sets the Horizontal Alignment of the PdfPCell to left.
            clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

            // Creates a phrase to show the current date at the right hand side of the header.
            Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

            // Creates a PdfPCell which accepts the date phrase as a parameter.
            PdfPCell clDate = new PdfPCell(phDate);
            // Sets the Horizontal Alignment of the PdfPCell to right.
            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
            // Sets the border of the cell to zero.
            clDate.Border = PdfPCell.NO_BORDER;

            // Adds the cell which holds the application name to the headerTable.
            headerTable.AddCell(clApplicationName);
            // Adds the cell which holds the date to the headerTable.
            headerTable.AddCell(clDate);
            // Sets the border of the headerTable to zero.
            headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

            // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
            PdfPCell cellHeader = new PdfPCell(headerTable);
            cellHeader.Border = PdfPCell.NO_BORDER;
            // Sets the column span of the header cell to noOfColumns.
            cellHeader.Colspan = noOfColumns;
            // Adds the above header cell to the table.
            mainTable.AddCell(cellHeader);

            // Creates a phrase which holds the file name.
            Phrase phHeader = new Phrase("Contact List", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
            PdfPCell clHeader = new PdfPCell(phHeader);
            clHeader.Colspan = noOfColumns;
            clHeader.Border = PdfPCell.NO_BORDER;
            clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            mainTable.AddCell(clHeader);

            // Creates a phrase for a new line.
            Phrase phSpace = new Phrase("\n");
            PdfPCell clSpace = new PdfPCell(phSpace);
            clSpace.Border = PdfPCell.NO_BORDER;
            clSpace.Colspan = noOfColumns;
            mainTable.AddCell(clSpace);

            // Sets the gridview column names as table headers.
            for (int i = 0; i < noOfColumns; i++)
            {
                Phrase ph = null;

                if (gvReport.AutoGenerateColumns)
                {
                    ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                }
                else
                {
                    ph = new Phrase(gvReport.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                }

                mainTable.AddCell(ph);
            }

            // Reads the gridview rows and adds them to the mainTable
            for (int rowNo = 0; rowNo < noOfRows; rowNo++)
            {
                for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
                {
                    if (gvReport.AutoGenerateColumns)
                    {
                        string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                        mainTable.AddCell(ph);
                    }
                    else
                    {
                        if (gvReport.Columns[columnNo] is TemplateField)
                        {
                            try
                            {
                                Label lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[1] as Label;

                                string s = lc.Text.Trim();
                                Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                                mainTable.AddCell(ph);
                            }
                            catch (NullReferenceException ee)
                            {
                                noOfColumns--;
                            }
                            catch (Exception ee)
                            {
                                noOfColumns--;
                            }
                        }
                        else
                        {
                            string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                            Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                            mainTable.AddCell(ph);
                        }
                    }
                }

                // Tells the mainTable to complete the row even if any cell is left incomplete.
                mainTable.CompleteRow();
            }

            // Gets the instance of the document created and writes it to the output stream of the Response object.
            PdfWriter.GetInstance(document, Response.OutputStream);

            // Creates a footer for the PDF document.
            HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
            pdfFooter.Alignment = Element.ALIGN_CENTER;
            pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;

            // Sets the document footer to pdfFooter.
            document.Footer = pdfFooter;
            // Opens the document.
            document.Open();
            // Adds the mainTable to the document.
            document.Add(mainTable);
            // Closes the document.
            document.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename= ContactList.pdf");
            Response.End();
        }

The original one is Here

I change this line and add try and catch to avoid the exception (problem 3) :

DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;

TO

Label lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[1] as Label;

How to fix these problems?

enter image description here

In the out put you can see that English Columns on LTR and Arabic Column on RTL. if you want to display GridView on page with RTL than you can use <div dir="rtl">Put the Grid View here</div>. GridView:

 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False">
        <Columns>
            <asp:TemplateField HeaderText="العربية" SortExpression="العربية">
                <ItemTemplate>
                    <asp:Label ID="arabic" runat="server" Text='<%# Eval("العربية")%>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <Columns>
            <asp:TemplateField HeaderText="English" SortExpression="English">
                <ItemTemplate>
                    <asp:Label ID="english" runat="server" Text='<%# Eval("English") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="deleteButton" runat="server" Text="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:HyperLink ID="open" runat="server" Text="Open" NavigateUrl="~/Default.aspx"/>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT [English], [العربية] FROM [Test]"></asp:SqlDataSource>
    <br />
    <asp:Button ID="btnExport" runat="server" OnClick="btnExport_Click" Text="Export to PDF" />

CS Code:

 protected void ExportPDF(GridView gridViewReport)
    {
        int columnNumber = 0, rowNumber = 0;
        DataTable tbl = null;

        if (gridViewReport.AutoGenerateColumns)
        {
            tbl = gridViewReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
            columnNumber = tbl.Columns.Count;
            rowNumber = tbl.Rows.Count;
        }
        else
        {
            columnNumber = gridViewReport.Columns.Count;
            rowNumber = gridViewReport.Rows.Count;
        }
        // Creates a PDF document
        Document document = null;
        document = new Document(PageSize.A4, 0, 0, 15, 5);
        PdfPTable _table = new PdfPTable(GridView1.Columns.Count);
        _table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        BaseFont baseFont = BaseFont.CreateFont("c:\\\\windows\\\\fonts\\\\tahoma.ttf", BaseFont.IDENTITY_H, true); // Font which has Arabic characters
        iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);

        // Sets the gridview column names as table headers.
        for (int i = 0; i < columnNumber; i++)
        {
            iTextSharp.text.pdf.PdfPCell ph = null;

            if (gridViewReport.AutoGenerateColumns)
            {
                ph = new PdfPCell(new Phrase(10, tbl.Columns[i].ColumnName, font));
            }
            else
            {
                ph = new PdfPCell(new Phrase(10, gridViewReport.Columns[i].HeaderText, font));
            }
            if (ph != null && gridViewReport.Columns[i].HeaderText != "")
            {
                if (Regex.IsMatch(gridViewReport.Columns[i].HeaderText, "^[a-zA-Z0-9 ]*$")) // Check if Header Text is English
                {
                    ph.RunDirection = PdfWriter.RUN_DIRECTION_LTR; // Left to Right
                    BaseColor color = new BaseColor(Color.Red);
                    ph.BackgroundColor = color;
                    _table.AddCell(ph);
                }
                else
                {
                    ph.RunDirection = PdfWriter.RUN_DIRECTION_RTL; //Right to Left
                    BaseColor color = new BaseColor(Color.Red);
                    ph.BackgroundColor = color;
                    _table.AddCell(ph);
                }
            }
            else
            {
                ph.Border = iTextSharp.text.Rectangle.NO_BORDER;
                _table.AddCell(ph);
            }
        }
        // Get the gridview rows and adds them to the _table
        for (int rowIteration = 0; rowIteration < rowNumber; rowIteration++)
        {
            for (int columnIteration = 0; columnIteration < columnNumber; columnIteration++)
            {
                if (gridViewReport.AutoGenerateColumns) //Check if AutoGenrated Colunms
                {
                    string s = gridViewReport.Rows[rowIteration].Cells[columnIteration].Text.Trim();
                    PdfPCell ph = new PdfPCell(new Phrase(10, s, font));
                    _table.AddCell(ph);
                }
                else
                {
                    if (gridViewReport.Columns[columnIteration] is TemplateField) // Check if Item Template
                    {
                        PdfPCell ph = null;
                        Label lc = gridViewReport.Rows[rowIteration].Cells[columnIteration].Controls[1] as Label; // Label
                        Button btn = gridViewReport.Rows[rowIteration].Cells[columnIteration].Controls[1] as Button;// Button
                        HyperLink hyperLink = gridViewReport.Rows[rowIteration].Cells[columnIteration].Controls[1] as HyperLink; // HyperLink

                        if (lc != null)
                        {

                            string s = lc.Text.Trim();
                            ph = new PdfPCell(new Phrase(10, s, font));
                            if (Regex.IsMatch(s, "^[a-zA-Z0-9 ]*$")) //Check if cell string is English
                            {   ph.RunDirection = PdfWriter.RUN_DIRECTION_LTR; // Left to Right
                                _table.AddCell(ph); 
                            }
                            else
                            {
                                ph.RunDirection = PdfWriter.RUN_DIRECTION_RTL; // Right to Left
                                _table.AddCell(ph);
                            }

                        }
                        else if (btn != null)
                        {
                            ph = new PdfPCell(new Phrase(10, btn.Text, font));
                            ph.Phrase.Clear(); // Clear the Cell Phrase
                            ph.Border = iTextSharp.text.Rectangle.NO_BORDER;

                            _table.AddCell(ph);
                        }
                        else if (hyperLink != null)
                        {
                            ph = new PdfPCell(new Phrase(10, hyperLink.Text, font));
                            ph.Phrase.Clear(); //Clear the Cell Phrase
                            ph.Border = iTextSharp.text.Rectangle.NO_BORDER; 
                            _table.AddCell(ph);
                        }
                        else
                        {
                            _table.AddCell("--");
                        }
                    }
                    else
                    {
                        string s = gridViewReport.Rows[rowIteration].Cells[columnIteration].Text.Trim();
                        PdfPCell ph = new PdfPCell(new Phrase(10, s, font));
                        _table.AddCell(ph);
                    }
                }
            }
            _table.CompleteRow();
        }
        PdfWriter.GetInstance(document, Response.OutputStream);
        // Opens the document.
        document.Open();
        // Adds the _table to the document.
        document.Add(_table);
        // Closes the document.
        document.Close();
        Page.Response.ContentType = "application/pdf";
        Page.Response.AddHeader("content-disposition", "attachment;filename=MyGrid.pdf");
        Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Page.Response.Write(document);
        Page.Response.End();

    }

This code might not be the perfectly coded but I hope this will help you to get your required results.

What's the best way to store a password or private key on a web host?

7 votes

I'm not referring to passwords that don't have to be used (such as passwords for other users to my site - in which case I really don't have to store them. See http://stackoverflow.com/a/1054069/939213 .) so simply storing hashes is not an option.

I'm referring to storing passwords to an SQL database and a private key that the software on the shared server has to use.

I assume there's no really secure way to do it. I just want to know what's the best in this situation.

I'm trying to keep them secure from hackers (on the same web host or not). Not from others who have permission to see the files.

It's ASP.Net codebehind that will be using them.

Windows offers the Data Protection API (DPAPI) specifically for this purpose. Look into the ProtectedData class for consuming it from .NET.

The advantage of DPAPI is that your sensitive data is encrypted based on the Windows user’s logon credential, meaning that it is secure unless your Windows account is compromised.

Multilingual web application change div text?

7 votes

I am working with asp.net web application multilingual site.

I am using following link :

http://techaxe.com/2010/09/04/creating-multilingual-website-using-asp-net/

Here we have file in my App_LocalResource folder for change text content. It's work good with label control.

<asp:Label ID="Label1" runat="server" Text="<%$Resources:AboutText%>"></asp:Label>

Here I want to change my div content as per selected language.

<div class="registration_content" runat="server">
                    <%$Resources:AboutText%> </div>

Please suggest me how I can change div content as per local resource variable.

Thanks for any suggestion..

You could use an asp:Literal tag:

<div class="registration_content" runat="server">
    <asp:Literal runat="server" Text="<%$Resources:AboutText%>" /> 
</div>

Update to RC of WebApi causing Could not load type 'System.Web.Http.Dependencies.IDependencyResolver' from assembly error

6 votes

I have recently upgraded to the RC versions of the WebApi using Nuget but am now getting the following error.

Could not load type 'System.Web.Http.Dependencies.IDependencyResolver' from assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

Using the object browser, I can see the correct reference is in there. I have tried rebuilding, cleaning and clearing the temporary internet files.

A google search turned up http://forums.asp.net/t/1810546.aspx/1?Dependency+Resolver+throws+an+error+with+Unity but this wasn't much help.

Does anyone know what is causing this?

Screenshot from Visual Studio

The answer in the end was that MVC 4 was conflicting, I assume that the dlls it put in the GAC were taking precedence, uninstalling MVC 4 fixed the problem for me.

MVC 3.0 JQUERY Partial page update

6 votes

I've a JQuery UI Date Picker. Upon selection of the date, the data on graph changes.

The issue is that when I select the date on the date picker, whole page refreshes and data gets populated.

Is there anyway, I can just update the graph which is on tag? Note, upon selection of the date, jquery posts to server and gets the new data for selected date.

I'm using $.ajax({ }); to make a call to the server. I would have thought this will do a trick but it is not the case.

Any help will be much appreciated.

Try this

$('#datepickerid').datepicker({
   onSelect: function(dateText, inst) { 
     $.ajax({ ... } );
     return false;
   }
});

Dynamically extending features of an application?

6 votes

I recently came across a way to develop pluggable application modules when using ASP.NET MVC3/4 and I loved the simplicity of the approach. Currently, I have my applications structured as follows:

enter image description here

Therefore, anyone wanting to develop an extension for my application, follows the approach from the above tutorial and creates an extension that stays in the Areas folder. I figure that when new Areas (created as new projects) are added, .pdb files are created and placed in the bin directory. My question is this:

  • How does one distribute the Areas as pluggable modules?
  • How do I change the following code so that when someone drops a new Area into the bin folder, the application automatically picks it up and creates a link? And what should the plugin author do to enable this?

In my _Layout.cshtml (global shared layout), I do the following to construct the links:

<ul>
      <li>@Html.ActionLink("Area1", "Index", "Area1", new { Area = "Area1" }, null)</li>
      <li>@Html.ActionLink("Area2", "Index", "Area2", new { Area = "Area2" }, null)</li>
      <li>@Html.ActionLink("Area3", "Index", "Area3", new { Area = "Area3" }, null)</li>
</ul>

For simplicity, assume that the area names are unique. Any suggestions on how to do this?

How does one distribute the Areas as pluggable modules?

Don't create the Areas in the hosting web app, but create separate projects, that compile to separate dll's. Copy the dll's to any web app where you want to use it. Remember to set all static files as "EmbeddedResource".

How do I change the following code so that when someone drops a new Area into the bin folder, the application automatically picks it up and creates a link? And what should the plugin author do to enable this?

You can use MvcContrib PortableAreaRegistration's "Bus" to send messages, commands from the portable area to anyone on the 'bus'. That can be the hosting web app, or in theory independent Area's can send message to each other.

Created two crude, but functional demo of this, code on github:

MVC3 version:

https://github.com/AkosLukacs/PluggablePortableAreas

MVC4 RC version:

https://github.com/AkosLukacs/PluggablePortableAreasMVC4

First, you define a message that can carry the information you need. Just a POCO that has some properties (PluggablePortableAreas.Common\RegisterAreaMessage.cs):

public class RegisterAreaMessage : IEventMessage
{
    public string LinkText { get; private set; }
    public string AreaName { get; private set; }
    public string ControllerName { get; private set; }
    public string ActionName { get; private set; }
    //...
}

Create a handler for that message type (PluggablePortableAreas.Common\RegisterAreaEventHandler.cs):

public class RegisterAreaEventHandler : MessageHandler<RegisterAreaMessage>{}

In this case, the MessageHandler just adds the received messages to a static ConcurrentBag<RegisterAreaMessage>. You can use DI, if you want to, but wanted to keep it simple.

You can send the message from the portable area like this (Areas\DemoArea1\Areas\Demo1\Demo1AreaRegistration.cs):

 //the portable area sends a message to the 'bus'
 bus.Send(new RegisterAreaMessage("Link to the Demo area", AreaName, DefaultController, DefaultAction));

The dynamically added links are displayed by iterating over the collection of messages(PluggablePortableAreas.Web\Views\Shared_Layout.cshtml):

                @foreach(var sor in PluggablePortableAreas.Common.RegisterAreaEventHandler.RegisteredAreas) {
                <li>@Html.ActionLink(sor.LinkText, sor.ActionName, sor.ControllerName, new{Area=sor.AreaName}, null)</li>
                }

One more thing to take care of: Use "fully qualified" Area names. If you don't specify the area name explicitly, MVC assumes it's the current area. No problems without areas, but the second will point to "/path_to_your_app/CurrentArea/Home" instead of "/path_to_your_app/Home".

<li>@Html.ActionLink("Home", "Index", "Home", new { Area = "" }, null)</li>
<li>@Html.ActionLink("I don't work from the portable area!", "Index", "Home")</li>

Even one more thing to note!

The development server in VS feels a bit "erratic", sometimes the portable area doesn't load. Works reliably in full IIS tho...

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

6 votes

I have found plenty of information out there about this error: 'ERROR: Could not load file or assembly '*.dll' or one of its dependencies. Access is denied.’ But i haven't found answer specific to my scenario. My site is deploy on 6 different production servers, only on one server i am facing this issue. The issue is random, but after it happens once, it continues until the site is recompile by done a small modification in web.config file(i know trick, after modification in web.config recompile the web application) and site on that server start working. Yesterday, issue was reproducing after one month period of working. We can't afford this issue on production.
Issue detail:

Server Error in '/' Application.
________________________________________
Could not load file or assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Access is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Access is denied.

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[FileLoadException: Could not load file or assembly 'MainCore.DbImpl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Access is denied.]
   ...DbImpl.Event.TTCEventController.GetEventFields(Int32 eventId) +0
   WebSuite.SportChannel.ModelImpl.TTCModelController.AddEventFieldList(XmlElement eventNode, ITTCEventController ctrl, Int32 eventId, PlayerType stupidType) in ...root\SportChannel\ModelImpl\Ttc\TTCModelController.cs:171
...ModelImpl.TTCModelController.GetLatestFourTourSchedulesXml() in ...root\SportChannel\ModelImpl\Ttc\TTCModelController.cs:283
   ...WebRoot.UserControls.HeadlinesTab.Page_Load(Object sender, EventArgs e) +491
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
   System.EventHandler.Invoke(Object sender, EventArgs e) +0
   System.Web.UI.Control.OnLoad(EventArgs e) +132
   System.Web.UI.Control.LoadRecursive() +66
   System.Web.UI.Control.LoadRecursive() +191
   System.Web.UI.Control.LoadRecursive() +191
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428

________________________________________
Version Information: Microsoft .NET Framework Version:2.0.50727.5446; ASP.NET Version:2.0.50727.5420

O finally I got the solution, as i haven't found \root folder under C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files. Google told me that their might be permission issue against current user, then i found i have Current Identity: IIS APPPOOL in malfunctioning server where as rest of server have Current Identity: NT AUTHORITY\NETWORK SERVICE. then i changed Current Identity from IIS APPPOOL to NT AUTHORITY\NETWORK SERVICE. then found after recompiling(modification in web.config recompile the web application), i have found Temporary ASP.NET Files. which now malfunctioning server start creating temp file. Hopefully next time this issue will not occur. Thanks All :)

Linq query to check for duplicate values

6 votes

In one of my pages I need to check if the entered information about a customer consists duplicate PAN NO,Email,Mobile No which may have been entered previously.Currently I am trying it using this Linq To SQL statement

    var duplicate = (from dup in dt.Data_Customer_Logs
                     where dup.cPanGirNo == panno 
                           || dup.cEmail == email 
                           || dup.nMobileNo.ToString() == mobno
    select dup).Any(); 

It is working but can anyone help me as to what is the correct method to solve my issue.Also if there are no records found what would be the result. Any suggestions are welcome.

bool duplicateExists = dt.Data_Customer_Logs.Any(x => 
                         x.cPanGirNo == panno 
                      || x.cEmail == email
                      || x.nMobileNo.ToString() == mobno);

This is a tad cleaner if you just want to know if such records exist or not. And I think it will avoid bringing back multiple records to the client side and then doing IEnumerable<T>.Any on the results.

If you need to also get back the records that match the criteria, you can use IQueryable<T>.Where:

var duplicates =  dt.Data_Customer_Logs.Where(x => 
                         x.cPanGirNo == panno 
                      || x.cEmail == email
                      || x.nMobileNo.ToString() == mobno);
if(duplicates.Any())
{
    // use duplicates...
    foreach(var dup in duplicates)
    {
        //use dup.cEmail, dup.nMobileNo, etc.

fb-like some time get disappeared with fb-share pluging?

6 votes

Here I am working with asp.net web application, I am using 2 facebook plugin in my web page.

  1. Facebook like
  2. Facebook share

For facebook share :

<a name="fb_share" type="button" share_url="*******"></a>
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript">
</script>

For facebook like :

 <script>    
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
        fjs.parentNode.insertBefore(js, fjs);
    } (document, 'script', 'facebook-jssdk'));
 </script>

<div id="fb-root"></div>            
<div class="fb-like" data-href="********" data-send="false" 
  data-layout="button_count" data-width="10" 
  data-show-faces="false" style="width:45px; height:20px;"></div>

Case 1. above code work fine when I am using single code.

Case 2 : when I am using both some time facebook like plugin disappeared from page.

Thanks in advance...

Like button and Share button may be used on one page only if you avoid usage of javascript provided with it and use direct link to share.php (which I will not provide for reasons outlined bellow).

If you'll use http://static.ak.fbcdn.net/connect.php/js/FB.Share it will break either Share or Like buttons, according to order of javascript inclusion, first one will work, second one is in trouble.

Couple of points to take into consideration:

  • Share button is deprecated please avoid using it!

    The Share button has been deprecated in favor of the Like button, and will no longer be supported.

  • Share button can be easily replaced with usage of Feed Dialog and JS-SDK, which provide more control over sharing functionality:
    FB.ui({method: 'feed', link: document.location.href});