Rectangle 27 2

I tried running Kinopiko's example, except I increased the number of iterations by a factor of 100.

#include <stdio.h>

int main ()
{
    int i;
    for (i = 0; i < 1000000; i++) {
        printf ("%d\n", i);
    }
    return 0;
}

Then I took 10 stackshots (under VC, but you can use pstack). Here are the stackshots:

9 copies of this stack:
NTDLL! 7c90e514()
KERNEL32! 7c81cbfe()
KERNEL32! 7c81cc75()
KERNEL32! 7c81cc89()
_write() line 168 + 57 bytes
_flush() line 162 + 23 bytes
_ftbuf() line 171 + 9 bytes
printf() line 62 + 14 bytes
main() line 7 + 14 bytes
mainCRTStartup() line 206 + 25 bytes
KERNEL32! 7c817077()

1 copy of this stack:
KERNEL32! 7c81cb96()
KERNEL32! 7c81cc75()
KERNEL32! 7c81cc89()
_write() line 168 + 57 bytes
_flush() line 162 + 23 bytes
_ftbuf() line 171 + 9 bytes
printf() line 62 + 14 bytes
main() line 7 + 14 bytes
mainCRTStartup() line 206 + 25 bytes
KERNEL32! 7c817077()
mainCRTStartup() line 206 + 25 bytes Cost ~100% of the time
main() line 7 + 14 bytes             Cost ~100% of the time
printf() line 62 + 14 bytes          Cost ~100% of the time
_ftbuf() line 171 + 9 bytes          Cost ~100% of the time
_flush() line 162 + 23 bytes         Cost ~100% of the time
_write() line 168 + 57 bytes         Cost ~100% of the time

In a nutshell, the program spends ~100% of it's time flushing to disk (or console) the output buffer as part of the printf on line 7.

(What I mean by "Cost of a line" is - it is the fraction of total time spent at the request of that line, and that's roughly the fraction of samples that contain it. If that line could be made to take no time, such as by removing it, skipping over it, or passing its work off to an infinitely fast coprocessor, that time fraction is how much the total time would shrink. So if the execution of any of these lines of code could be avoided, time would shrink by somewhere in the range of 95% to 100%. If you were to ask "What about recursion?", the answer is It Makes No Difference.)

Now, maybe you want to know something else, like how much time is spent in the loop, for example. To find that out, remove the printf because it's hogging all the time. Maybe you want to know what % of time is spent purely in CPU time, not in system calls. To get that, just throw away any stackshots that don't end in your code.

The point I'm trying to make is if you're looking for things you can fix to make the code run faster, the data gprof gives you, even if you understand it, is almost useless. By comparison, if there is some of your code that is causing more wall-clock time to be spent than you would like, stackshots will pinpoint it.

linux - How to modify a C program so that gprof can profile it? - Stac...

c linux profiling profiler gprof
Rectangle 27 10

IIS 6.0 and previous versions :

ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.

This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.

Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.

The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests

What's a SCRIPT MAP ?

Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed

A good example can be seen here

IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.

IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )

NON ASP.NET Modules / native IIS modules
ASP.NET modules

This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.

  • You can build new managed modules (IHttpModule) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.
IHttpHandler

asp.net - What is the difference between 'classic' and 'integrated' pi...

asp.net asp.net-mvc iis iis-7 integrated-pipeline-mode
Rectangle 27 9

IIS 6.0 and previous versions :

ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.

This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.

Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.

The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests

What's a SCRIPT MAP ?

Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed

A good example can be seen here

IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.

IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )

NON ASP.NET Modules / native IIS modules
ASP.NET modules

This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.

  • You can build new managed modules (IHttpModule) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.
IHttpHandler

asp.net - What is the difference between 'classic' and 'integrated' pi...

asp.net asp.net-mvc iis iis-7 integrated-pipeline-mode
Rectangle 27 212

Here's a generic version of what we've been using on Stack Overflow for the past year:

/// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
    /// <summary>
    /// A unique name for this Throttle.
    /// </summary>
    /// <remarks>
    /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
    /// </remarks>
    public string Name { get; set; }

    /// <summary>
    /// The number of seconds clients must wait before executing this decorated route again.
    /// </summary>
    public int Seconds { get; set; }

    /// <summary>
    /// A text message that will be sent to the client upon throttling.  You can include the token {n} to
    /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
    /// </summary>
    public string Message { get; set; }

    public override void OnActionExecuting(ActionExecutingContext c)
    {
        var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
        var allowExecute = false;

        if (HttpRuntime.Cache[key] == null)
        {
            HttpRuntime.Cache.Add(key,
                true, // is this the smallest data we can have?
                null, // no dependencies
                DateTime.Now.AddSeconds(Seconds), // absolute expiration
                Cache.NoSlidingExpiration,
                CacheItemPriority.Low,
                null); // no callback

            allowExecute = true;
        }

        if (!allowExecute)
        {
            if (String.IsNullOrEmpty(Message))
                Message = "You may only perform this action every {n} seconds.";

            c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
            // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
        }
    }
}
[Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
    return Content("TestThrottle executed");
}

The ASP.NET Cache works like a champ here - by using it, you get automatic clean-up of your throttle entries. And with our growing traffic, we're not seeing that this is an issue on the server.

Feel free to give feedback on this method; when we make Stack Overflow better, you get your Ewok fix even faster :)

quick question - you're using the c.HttpContext.Request.UserHostAddress value as part of the key. Is that value possible empty or null or all the same value? (ie, if u're using a load balancer and it's the IP of that machine .. not the real clients) Like, do proxy's or load balancers (ie an BIG IP F5) put the same data in there and you need to check for X-Forwarded-For also or something?

@Pure.Krome - yes, it could be. When retrieving the client IP, we use a helper function that checks both the REMOTE_ADDR and HTTP_X_FORWARDED_FOR server variables and sanitizes appropriately.

@BrettRobi, I'm pretty sure they have server affinity based on the users IP address. So they will likely still be hitting the same server.

For those of you who care and have read this far down in the comment stream...we ended up writting our own redirects that clear out the throttle cache key before redirecting. This way all redirects pass through the code to remove the key and none of them trigger the Throttle attribute.

Best way to implement request throttling in ASP.NET MVC? - Stack Overf...

asp.net-mvc throttling
Rectangle 27 211

Here's a generic version of what we've been using on Stack Overflow for the past year:

/// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
    /// <summary>
    /// A unique name for this Throttle.
    /// </summary>
    /// <remarks>
    /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
    /// </remarks>
    public string Name { get; set; }

    /// <summary>
    /// The number of seconds clients must wait before executing this decorated route again.
    /// </summary>
    public int Seconds { get; set; }

    /// <summary>
    /// A text message that will be sent to the client upon throttling.  You can include the token {n} to
    /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
    /// </summary>
    public string Message { get; set; }

    public override void OnActionExecuting(ActionExecutingContext c)
    {
        var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
        var allowExecute = false;

        if (HttpRuntime.Cache[key] == null)
        {
            HttpRuntime.Cache.Add(key,
                true, // is this the smallest data we can have?
                null, // no dependencies
                DateTime.Now.AddSeconds(Seconds), // absolute expiration
                Cache.NoSlidingExpiration,
                CacheItemPriority.Low,
                null); // no callback

            allowExecute = true;
        }

        if (!allowExecute)
        {
            if (String.IsNullOrEmpty(Message))
                Message = "You may only perform this action every {n} seconds.";

            c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
            // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
        }
    }
}
[Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
    return Content("TestThrottle executed");
}

The ASP.NET Cache works like a champ here - by using it, you get automatic clean-up of your throttle entries. And with our growing traffic, we're not seeing that this is an issue on the server.

Feel free to give feedback on this method; when we make Stack Overflow better, you get your Ewok fix even faster :)

quick question - you're using the c.HttpContext.Request.UserHostAddress value as part of the key. Is that value possible empty or null or all the same value? (ie, if u're using a load balancer and it's the IP of that machine .. not the real clients) Like, do proxy's or load balancers (ie an BIG IP F5) put the same data in there and you need to check for X-Forwarded-For also or something?

@Pure.Krome - yes, it could be. When retrieving the client IP, we use a helper function that checks both the REMOTE_ADDR and HTTP_X_FORWARDED_FOR server variables and sanitizes appropriately.

@BrettRobi, I'm pretty sure they have server affinity based on the users IP address. So they will likely still be hitting the same server.

For those of you who care and have read this far down in the comment stream...we ended up writting our own redirects that clear out the throttle cache key before redirecting. This way all redirects pass through the code to remove the key and none of them trigger the Throttle attribute.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Best way to implement request throttling in ASP.NET MVC? - Stack Overf...

asp.net-mvc throttling
Rectangle 27 2

The fundamental transformation you need to do from a proxy request to an HTTP server request is to change the first line:

GET http://www.gmail.com/ HTTP/1.1
GET / HTTP/1.1

The full URL is required when the browser sends the request to the proxy, so that the proxy can make the further connection to the real server. However, an HTTP request to the server must not contain the protocol and hostname parts on the GET line.

However, this may not be the only thing you need to do. An HTTP proxy is a fairly complex application, due to things like different protocol version numbers and connection options on the browser-proxy connection versus the proxy-server connection.

RFC 2616 contains a considerable amount of information regarding the correct behaviour of HTTP proxy applications.

SO it should be something like this: GET / HTTP/1.1 Accept: text/html, application/xhtml+xml, / Accept-Language: en-US User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Accept-Encoding: gzip, deflate Proxy-Connection: Keep-Alive Host: www.gmail.com

I guess so, I can't see where your line breaks are in the comment. But you'll also want to act upon that Proxy-Connection header, as that is sent by the browser to the proxy and is not intended to be passed on to the server. Again, read RFC 2616 for full details.

I am able to connect to the server, but the problem is that proxy server is not reading entire response from the server. Connection is being reset by remote server while proxy is receiving data. Is the problem in reading data with this code while((n = read(rfd, buff, MAXLINE)) > 0) { write(connfd, buff, MAXLINE); printf("%s",buff); bzero(buff,MAXLINE); }

Rebuild request header from HTTP proxy server to Remote Server in C - ...

c http proxy get
Rectangle 27 59

Use a TextWriter

I've found the proper way to return XML to a client in ASP.NET. I think if I point out the wrong ways, it will make the right way more understandable.

Response.Write(doc.InnerXml);
Response.ContentType = "text/xml"; //Must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
doc.Save(Response.Output); //Save to the text-writer
      //using the encoding of the text-writer
      //(which comes from response.contentEncoding)
Response.OutputStream
Response.Output

Both are streams, but Output is a TextWriter. When an XmlDocument saves itself to a TextWriter, it will use the encoding specified by that TextWriter. The XmlDocument will automatically change the xml declaration node to match the encoding used by the TextWriter. e.g. in this case the XML declaration node:

would become

This is because the TextWriter has been set to UTF-8. (More on this in a moment). As the TextWriter is fed character data, it will encode it with the byte sequences appropriate for its set encoding.

In this example the document is incorrectly saved to the OutputStream, which performs no encoding change, and may not match the response's content-encoding or the XML declaration node's specified encoding.

The XML document is correctly saved to a TextWriter object, ensuring the encoding is properly handled.

The encoding given to the client in the header:

Response.ContentEncoding = ...

must match the XML document's encoding:

must match the actual encoding present in the byte sequences sent to the client. To make all three of these things agree, set the single line:

Response.ContentEncoding = System.Text.Encoding.UTF8;

When the encoding is set on the Response object, it sets the same encoding on the TextWriter. The encoding set of the TextWriter causes the XmlDocument to change the xml declaration:

<?xml version="1.0" encoding="UTF-8"?>

when the document is Saved:

doc.Save(someTextWriter);

You do not want to save the document to a binary stream, or write a string:

Here the XML is incorrectly saved to a binary stream. The final byte encoding sequence won't match the XML declaration, or the web-server response's content-encoding.

Here the XML is incorrectly converted to a string, which does not have an encoding. The XML declaration node is not updated to reflect the encoding of the response, and the response is not properly encoded to match the response's encoding. Also, storing the XML in an intermediate string wastes memory.

You don't want to save the XML to a string, or stuff the XML into a string and response.Write a string, because that:

- doesn't follow the encoding specified
- doesn't set the XML declaration node to match
- wastes memory
doc.Save(Response.Output);
doc.Save(Response.OutputStream);
Response.Write(doc.ToString());

Do not use 'Response.Write(doc.InnerXml);`

The Response's ContentType must be set to "text/xml". If not, the client will not know you are sending it XML.

Response.Clear(); //Optional: if we've sent anything before
Response.ContentType = "text/xml"; //Must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
doc.Save(Response.Output); //Save to the text-writer
    //using the encoding of the text-writer
    //(which comes from response.contentEncoding)
Response.End(); //Optional: will end processing

Rob Kennedy had the good point that I failed to include the start-to-finish example.

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Xml;
using System.IO;
using System.Data.Common;

//Why a "Handler" and not a full ASP.NET form?
//Because many people online critisized my original solution
//that involved the aspx (and cutting out all the HTML in the front file),
//noting the overhead of a full viewstate build-up/tear-down and processing,
//when it's not a web-form at all. (It's a pure processing.)

public class Handler : IHttpHandler
{
   public void ProcessRequest(HttpContext context)
   {
      //GetXmlToShow will look for parameters from the context
      XmlDocument doc = GetXmlToShow(context);

      //Don't forget to set a valid xml type.
      //If you leave the default "text/html", the browser will refuse to display it correctly
      context.Response.ContentType = "text/xml";

      //We'd like UTF-8.
      context.Response.ContentEncoding = System.Text.Encoding.UTF8;
      //context.Response.ContentEncoding = System.Text.Encoding.UnicodeEncoding; //But no reason you couldn't use UTF-16:
      //context.Response.ContentEncoding = System.Text.Encoding.UTF32; //Or UTF-32
      //context.Response.ContentEncoding = new System.Text.Encoding(500); //Or EBCDIC (500 is the code page for IBM EBCDIC International)
      //context.Response.ContentEncoding = System.Text.Encoding.ASCII; //Or ASCII
      //context.Response.ContentEncoding = new System.Text.Encoding(28591); //Or ISO8859-1
      //context.Response.ContentEncoding = new System.Text.Encoding(1252); //Or Windows-1252 (a version of ISO8859-1, but with 18 useful characters where they were empty spaces)

      //Tell the client don't cache it (it's too volatile)
      //Commenting out NoCache allows the browser to cache the results (so they can view the XML source)
      //But leaves the possiblity that the browser might not request a fresh copy
      //context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

      //And now we tell the browser that it expires immediately, and the cached copy you have should be refreshed
      context.Response.Expires = -1;

      context.Response.Cache.SetAllowResponseInBrowserHistory(true); //"works around an Internet&nbsp;Explorer bug"

      doc.Save(context.Response.Output); //doc saves itself to the textwriter, using the encoding of the text-writer (which comes from response.contentEncoding)

      #region Notes
      /*
       * 1. Use Response.Output, and NOT Response.OutputStream.
       *  Both are streams, but Output is a TextWriter.
       *  When an XmlDocument saves itself to a TextWriter, it will use the encoding
       *  specified by the TextWriter. The XmlDocument will automatically change any
       *  XML declaration node, i.e.:
       *     <?xml version="1.0" encoding="ISO-8859-1"?>
       *  to match the encoding used by the Response.Output's encoding setting
       * 2. The Response.Output TextWriter's encoding settings comes from the
       *  Response.ContentEncoding value.
       * 3. Use doc.Save, not Response.Write(doc.ToString()) or Response.Write(doc.InnerXml)
       * 3. You DON'T want to save the XML to a string, or stuff the XML into a string
       *  and response.Write that, because that
       *   - doesn't follow the encoding specified
       *   - wastes memory
       *
       * To sum up: by Saving to a TextWriter: the XML Declaration node, the XML contents,
       * and the HTML Response content-encoding will all match.
       */
      #endregion Notes
   }

   private XmlDocument GetXmlToShow(HttpContext context)
   {
      //Use context.Request to get the account number they want to return
      //GET /GetPatronInformation.ashx?accountNumber=619

      //Or since this is sample code, pull XML out of your rear:
      XmlDocument doc = new XmlDocument();
      doc.LoadXml("<Patron><Name>Rob Kennedy</Name></Patron>");

      return doc;
   }

   public bool IsReusable { get { return false; } }
}

The question demands that answers must discuss which string encoding to use, but this answer only mentions UTF-8. Are other encodings allowed? The impression I get from this answer is that once we're using doc.Save(Response.Output), we can set Response.ContentEncoding to anything we want, and the system will ensure that the HTTP response header, the XML header, and the XML contents all agree. Is that correct?

This answer says the content type must be text/xml. Isn't it more nuanced than that, so that application/xml or image/svg+xml might be OK, too? In other words, doesn't the choice of content type depend on the content, or are you really saying that all XML returned via ASP.Net must use a single content type?

@RobKennedy You should not be using an aspx to return XML to the user-agent. By using an ASPX file you you forcing IIS to build up the whole WebForm infrastructure. As for the remainder of the .ashx file contents, i'll add that to the answer now.

@RobKennedy You don't have to use text/xml, but you must use something. Otherwise it stays at the default text/html, which any browser worth it's salt will not display correctly when it encounters content that isn't any discernible html. Yes, you could also return application/xml. The point was, make sure your ContentType matches the actual content.

How to return XML in ASP.NET? - Stack Overflow

asp.net xml
Rectangle 27 31

You can also use this ImageResult class to return an image.

No need for a handler just create a route such as:

and return an ImageResult for the request.

public class ImageResult : ActionResult
    {
        public string SourceFilename { get; set; }
        public MemoryStream SourceStream { get; set; }
        public string ContentType { get; set; }
        public ImageResult(string sourceFilename)
        {
            SourceFilename = sourceFilename;
            ContentType = FileTypeHelper.GetContentType(SourceFilename);
        }
        public ImageResult(MemoryStream sourceStream, string contentType)
        {
            SourceStream = sourceStream;
            ContentType = contentType;
        }
        public override void ExecuteResult(ControllerContext context)
        {   
            var res = context.HttpContext.Response;
            res.Clear();
            res.Cache.SetCacheability(HttpCacheability.NoCache);
            res.ContentType = ContentType;

            if (SourceStream != null)
            {
                SourceStream.WriteTo(res.OutputStream);

            }
            else
            {
               res.TransmitFile(SourceFilename);
            }

        }


    }

To use this do the following in a controller and add a route for it:

public ImageResult GetImage(int imageId)
{
   // Database fetch of image details
   var imageInfo = repository.Get<ImageInfo>(imageId);
   return new ImageResult(imageInfo.FullFilename);
}

Have added the FileType helper class too:

public static class FileTypeHelper
{
    public static string GetContentType(string SourceFileName)
    {
        var extension = Path.GetExtension(SourceFileName).ToLower();
         switch (extension)
        {
            case ".ai": return "application/postscript";
            case ".aif": return "audio/x-aiff";
            case ".aifc": return "audio/x-aiff";
            case ".aiff": return "audio/x-aiff";
            case ".asc": return "text/plain";
            case ".au": return "audio/basic";
            case ".avi": return "video/x-msvideo";
            case ".bcpio": return "application/x-bcpio";
            case ".bin": return "application/octet-stream";
            case ".c": return "text/plain";
            case ".cc": return "text/plain";
            case ".ccad": return "application/clariscad";
            case ".cdf": return "application/x-netcdf";
            case ".class": return "application/octet-stream";
            case ".cpio": return "application/x-cpio";
            case ".cpp": return "text/plain";
            case ".cpt": return "application/mac-compactpro";
            case ".cs": return "text/plain";
            case ".csh": return "application/x-csh";
            case ".css": return "text/css";
            case ".dcr": return "application/x-director";
            case ".dir": return "application/x-director";
            case ".dms": return "application/octet-stream";
            case ".doc": return "application/msword";
            case ".drw": return "application/drafting";
            case ".dvi": return "application/x-dvi";
            case ".dwg": return "application/acad";
            case ".dxf": return "application/dxf";
            case ".dxr": return "application/x-director";
            case ".eps": return "application/postscript";
            case ".etx": return "text/x-setext";
            case ".exe": return "application/octet-stream";
            case ".ez": return "application/andrew-inset";
            case ".f": return "text/plain";
            case ".f90": return "text/plain";
            case ".fli": return "video/x-fli";
            case ".flv": return "video/x-flv";
            case ".gif": return "image/gif";
            case ".gtar": return "application/x-gtar";
            case ".gz": return "application/x-gzip";
            case ".h": return "text/plain";
            case ".hdf": return "application/x-hdf";
            case ".hh": return "text/plain";
            case ".hqx": return "application/mac-binhex40";
            case ".htm": return "text/html";
            case ".html": return "text/html";
            case ".ice": return "x-conference/x-cooltalk";
            case ".ief": return "image/ief";
            case ".iges": return "model/iges";
            case ".igs": return "model/iges";
            case ".ips": return "application/x-ipscript";
            case ".ipx": return "application/x-ipix";
            case ".jpe": return "image/jpeg";
            case ".jpeg": return "image/jpeg";
            case ".jpg": return "image/jpeg";
            case ".js": return "application/x-javascript";
            case ".kar": return "audio/midi";
            case ".latex": return "application/x-latex";
            case ".lha": return "application/octet-stream";
            case ".lsp": return "application/x-lisp";
            case ".lzh": return "application/octet-stream";
            case ".m": return "text/plain";
            case ".man": return "application/x-troff-man";
            case ".me": return "application/x-troff-me";
            case ".mesh": return "model/mesh";
            case ".mid": return "audio/midi";
            case ".midi": return "audio/midi";
            case ".mime": return "www/mime";
            case ".mov": return "video/quicktime";
            case ".movie": return "video/x-sgi-movie";
            case ".mp2": return "audio/mpeg";
            case ".mp3": return "audio/mpeg";
            case ".mpe": return "video/mpeg";
            case ".mpeg": return "video/mpeg";
            case ".mpg": return "video/mpeg";
            case ".mpga": return "audio/mpeg";
            case ".ms": return "application/x-troff-ms";
            case ".msh": return "model/mesh";
            case ".nc": return "application/x-netcdf";
            case ".oda": return "application/oda";
            case ".pbm": return "image/x-portable-bitmap";
            case ".pdb": return "chemical/x-pdb";
            case ".pdf": return "application/pdf";
            case ".pgm": return "image/x-portable-graymap";
            case ".pgn": return "application/x-chess-pgn";
            case ".png": return "image/png";
            case ".pnm": return "image/x-portable-anymap";
            case ".pot": return "application/mspowerpoint";
            case ".ppm": return "image/x-portable-pixmap";
            case ".pps": return "application/mspowerpoint";
            case ".ppt": return "application/mspowerpoint";
            case ".ppz": return "application/mspowerpoint";
            case ".pre": return "application/x-freelance";
            case ".prt": return "application/pro_eng";
            case ".ps": return "application/postscript";
            case ".qt": return "video/quicktime";
            case ".ra": return "audio/x-realaudio";
            case ".ram": return "audio/x-pn-realaudio";
            case ".ras": return "image/cmu-raster";
            case ".rgb": return "image/x-rgb";
            case ".rm": return "audio/x-pn-realaudio";
            case ".roff": return "application/x-troff";
            case ".rpm": return "audio/x-pn-realaudio-plugin";
            case ".rtf": return "text/rtf";
            case ".rtx": return "text/richtext";
            case ".scm": return "application/x-lotusscreencam";
            case ".set": return "application/set";
            case ".sgm": return "text/sgml";
            case ".sgml": return "text/sgml";
            case ".sh": return "application/x-sh";
            case ".shar": return "application/x-shar";
            case ".silo": return "model/mesh";
            case ".sit": return "application/x-stuffit";
            case ".skd": return "application/x-koan";
            case ".skm": return "application/x-koan";
            case ".skp": return "application/x-koan";
            case ".skt": return "application/x-koan";
            case ".smi": return "application/smil";
            case ".smil": return "application/smil";
            case ".snd": return "audio/basic";
            case ".sol": return "application/solids";
            case ".spl": return "application/x-futuresplash";
            case ".src": return "application/x-wais-source";
            case ".step": return "application/STEP";
            case ".stl": return "application/SLA";
            case ".stp": return "application/STEP";
            case ".sv4cpio": return "application/x-sv4cpio";
            case ".sv4crc": return "application/x-sv4crc";
            case ".swf": return "application/x-shockwave-flash";
            case ".t": return "application/x-troff";
            case ".tar": return "application/x-tar";
            case ".tcl": return "application/x-tcl";
            case ".tex": return "application/x-tex";
            case ".tif": return "image/tiff";
            case ".tiff": return "image/tiff";
            case ".tr": return "application/x-troff";
            case ".tsi": return "audio/TSP-audio";
            case ".tsp": return "application/dsptype";
            case ".tsv": return "text/tab-separated-values";
            case ".txt": return "text/plain";
            case ".unv": return "application/i-deas";
            case ".ustar": return "application/x-ustar";
            case ".vcd": return "application/x-cdlink";
            case ".vda": return "application/vda";
            case ".vrml": return "model/vrml";
            case ".wav": return "audio/x-wav";
            case ".wrl": return "model/vrml";
            case ".xbm": return "image/x-xbitmap";
            case ".xlc": return "application/vnd.ms-excel";
            case ".xll": return "application/vnd.ms-excel";
            case ".xlm": return "application/vnd.ms-excel";
            case ".xls": return "application/vnd.ms-excel";
            case ".xlw": return "application/vnd.ms-excel";
            case ".xml": return "text/xml";
            case ".xpm": return "image/x-xpixmap";
            case ".xwd": return "image/x-xwindowdump";
            case ".xyz": return "chemical/x-pdb";
            case ".zip": return "application/zip";
            default: return string.Format("application/{0}", extension);
        }
    }
}

generic handler is 7.23 times faster than using MVC approach.

@Adeel, do you have any samples for the generic handler? Not sure what you mean.

What is the FileTypeHelper? If you don't want to share...that's cool.

.net - How to use Generic Handlers (ASHX) in ASP.NET MVC? - Stack Over...

.net asp.net asp.net-mvc httphandler ashx
Rectangle 27 3

You would start by making sure the Delete action could only be reached by a POST request, using the HttpPostAttribute:

[HttpPost]
public ActionResult Delete(int? resumeId)
{
    var r = _context.Resumes.Where(c => c.ResumeId == resumeId);
    _context.Resumes.RemoveRange(r);
    _context.SaveChanges();
    return RedirectToAction("ResumeCenter");
}

Once you add that attribute, any attempts to issue a GET request to that action will result in a 404 (Not Found) response.

@Html.Partial("_SmallButtonPartial",
   new SmallButtonViewModel
   {
       Action = "Delete",
       ButtonType = "btn-danger",
       Glyph = "trash",
       Text = "Delete button",
       ResumeId = Model.ResumeId,
   })

with something like:

@using(Html.BeginForm("delete", "your controller name", FormMethod.Post, new { @class="delete-form" }))
{
    <input type="hidden" name="ResumeId" value="@Model.ResumeId" />
    <button type="submit" class="btn btn-danger">
        <span class="glyphicon glyphicon-trash"></span>
        Delete
    </button>
}

You can have as many forms on a page as you like, as long as they are not nested - this generates a form on each row. I added a class here (delete-form) that you could use to hook into a jQuery event, if you wanted to handle this via AJAX instead of allowing the form to submit.

Any other actions, like "view" or "edit", would still just be GET requests, which you can leave as anchors, or use forms with the method set to GET (the end result is the same).

So, I should have HTTPPost for delete only, Edit and Details are fine with GET?

If you can tell me in one or two lines, Why I should always have delete httppost. I never understood it conceptually.

The idea behind "we should never have a "GET" Request for Deleting and Editing" is that GET requests should be idempotent, which (put more simply) means nothing should change as a result of making the request. Your Edit and Details are just requests to load either a read-only view (for Details) or to load a form for making changes (for Edit). The Edit view itself would still POST it's form.

The idea is that I should be able to GET the same resource one time or 1000 times, and the result is the same and nothing changed on the server as a result (ignoring things like logging - the resource itself should not change). When you delete something, you are most certainly changing a resource, and calling the same action again will have different results.

Understood. :) So when ever I my action is going to make any change in the resource I should make it as HttpPost

c# - How to make edit and delete POST Request in same page in my ASP.N...

c# asp.net asp.net-mvc razor asp.net-mvc-5
Rectangle 27 7

MVC 5 and 6 has the option of generating lower case URL's for your routes. My route config is shown below:

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        // Imprive SEO by stopping duplicate URL's due to case or trailing slashes.
        routes.AppendTrailingSlash = true;
        routes.LowercaseUrls = true;

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }
}

With this code, you should no longer need the canonicalize the URL's as this is done for you. One problem that can occur if you are using HTTP and HTTPS URL's and want a canonical URL for this. In this case, it's pretty easy to use the above approaches and replace HTTP with HTTPS or vice versa.

Another problem is external websites that link to your site may omit the trailing slash or add upper-case characters and for this you should perform a 301 permanent redirect to the correct URL with the trailing slash. For full usage and source code, refer to my blog post and the RedirectToCanonicalUrlAttribute filter:

/// <summary>
/// To improve Search Engine Optimization SEO, there should only be a single URL for each resource. Case 
/// differences and/or URL's with/without trailing slashes are treated as different URL's by search engines. This 
/// filter redirects all non-canonical URL's based on the settings specified to their canonical equivalent. 
/// Note: Non-canonical URL's are not generated by this site template, it is usually external sites which are 
/// linking to your site but have changed the URL case or added/removed trailing slashes.
/// (See Google's comments at http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html
/// and Bing's at http://blogs.bing.com/webmaster/2012/01/26/moving-content-think-301-not-relcanonical).
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class RedirectToCanonicalUrlAttribute : FilterAttribute, IAuthorizationFilter
{
    private readonly bool appendTrailingSlash;
    private readonly bool lowercaseUrls;

    #region Constructors

    /// <summary>
    /// Initializes a new instance of the <see cref="RedirectToCanonicalUrlAttribute" /> class.
    /// </summary>
    /// <param name="appendTrailingSlash">If set to <c>true</c> append trailing slashes, otherwise strip trailing 
    /// slashes.</param>
    /// <param name="lowercaseUrls">If set to <c>true</c> lower-case all URL's.</param>
    public RedirectToCanonicalUrlAttribute(
        bool appendTrailingSlash, 
        bool lowercaseUrls)
    {
        this.appendTrailingSlash = appendTrailingSlash;
        this.lowercaseUrls = lowercaseUrls;
    } 

    #endregion

    #region Public Methods

    /// <summary>
    /// Determines whether the HTTP request contains a non-canonical URL using <see cref="TryGetCanonicalUrl"/>, 
    /// if it doesn't calls the <see cref="HandleNonCanonicalRequest"/> method.
    /// </summary>
    /// <param name="filterContext">An object that encapsulates information that is required in order to use the 
    /// <see cref="RedirectToCanonicalUrlAttribute"/> attribute.</param>
    /// <exception cref="ArgumentNullException">The <paramref name="filterContext"/> parameter is <c>null</c>.</exception>
    public virtual void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.Ordinal))
        {
            string canonicalUrl;
            if (!this.TryGetCanonicalUrl(filterContext, out canonicalUrl))
            {
                this.HandleNonCanonicalRequest(filterContext, canonicalUrl);
            }
        }
    }

    #endregion

    #region Protected Methods

    /// <summary>
    /// Determines whether the specified URl is canonical and if it is not, outputs the canonical URL.
    /// </summary>
    /// <param name="filterContext">An object that encapsulates information that is required in order to use the 
    /// <see cref="RedirectToCanonicalUrlAttribute" /> attribute.</param>
    /// <param name="canonicalUrl">The canonical URL.</param>
    /// <returns><c>true</c> if the URL is canonical, otherwise <c>false</c>.</returns>
    protected virtual bool TryGetCanonicalUrl(AuthorizationContext filterContext, out string canonicalUrl)
    {
        bool isCanonical = true;

        canonicalUrl = filterContext.HttpContext.Request.Url.ToString();
        int queryIndex = canonicalUrl.IndexOf(QueryCharacter);

        if (queryIndex == -1)
        {
            bool hasTrailingSlash = canonicalUrl[canonicalUrl.Length - 1] == SlashCharacter;

            if (this.appendTrailingSlash)
            {
                // Append a trailing slash to the end of the URL.
                if (!hasTrailingSlash)
                {
                    canonicalUrl += SlashCharacter;
                    isCanonical = false;
                }
            }
            else
            {
                // Trim a trailing slash from the end of the URL.
                if (hasTrailingSlash)
                {
                    canonicalUrl = canonicalUrl.TrimEnd(SlashCharacter);
                    isCanonical = false;
                }
            }
        }
        else
        {
            bool hasTrailingSlash = canonicalUrl[queryIndex - 1] == SlashCharacter;

            if (this.appendTrailingSlash)
            {
                // Append a trailing slash to the end of the URL but before the query string.
                if (!hasTrailingSlash)
                {
                    canonicalUrl = canonicalUrl.Insert(queryIndex, SlashCharacter.ToString());
                    isCanonical = false;
                }
            }
            else
            {
                // Trim a trailing slash to the end of the URL but before the query string.
                if (hasTrailingSlash)
                {
                    canonicalUrl = canonicalUrl.Remove(queryIndex - 1, 1);
                    isCanonical = false;
                }
            }
        }

        if (this.lowercaseUrls)
        {
            foreach (char character in canonicalUrl)
            {
                if (char.IsUpper(character))
                {
                    canonicalUrl = canonicalUrl.ToLower();
                    isCanonical = false;
                    break;
                }
            }
        }

        return isCanonical;
    }

    /// <summary>
    /// Handles HTTP requests for URL's that are not canonical. Performs a 301 Permanent Redirect to the canonical URL.
    /// </summary>
    /// <param name="filterContext">An object that encapsulates information that is required in order to use the 
    /// <see cref="RedirectToCanonicalUrlAttribute" /> attribute.</param>
    /// <param name="canonicalUrl">The canonical URL.</param>
    protected virtual void HandleNonCanonicalRequest(AuthorizationContext filterContext, string canonicalUrl)
    {
        filterContext.Result = new RedirectResult(canonicalUrl, true);
    }

    #endregion
}

Usage example to ensure all requests are 301 redirected to the correct canonical URL:

filters.Add(new RedirectToCanonicalUrlAttribute(
    RouteTable.Routes.AppendTrailingSlash, 
    RouteTable.Routes.LowercaseUrls));

Why use an authorization filter when you should be using an action filter? Bacon isn't gammon for a reason.

IAuthorizationFilter is the correct choice. See this answer. The filter gets executed earlier in the request pipeline. Ideally if we are going to redirect a user, we should do it as early as possible.

That doesn't say anything about when you should use authorization filters instead of action filters. I think on this occasion we should agree to disagree.

Fair enough. The RequireHttpsAttribute is also using the IAuthorizationFilter to perform a redirect. It's performance vs naming, it's up to the devs what they prefer.

.net - How to correctly canonicalize a URL in an ASP.NET MVC applicati...

.net asp.net-mvc-2 url-routing canonical-link
Rectangle 27 3

This may not be useful to you, but I had a similar requirement, but used a SerializableDynamicObject

I changed the name of the dictionary to "Fields" and then this serializes with Json.Net to produce json which looks like:

{"Fields":{"Property1":"Value1", "Property2":"Value2" etc. where Property1 and Property2 are Dynamically added properties - i.e. Dictionary Keys

It would be perfect if I could get rid of the extra "Fields" property which encapsulates the rest, but I've worked around that limitation.

Answer moved from this question on request

c# - How to flatten an ExpandoObject returned via JsonResult in asp.ne...

c# javascript asp.net-mvc json expandoobject
Rectangle 27 2

Your POST request is a form data request, which is usually used post the data of an HTML form. It uses a special encoding for data. That's not what the YouTube API expects. It expects a simple POST request with an XML document.

Instead of the ASIFormDataRequest class, you should use the ASIHTTPRequest class. Your code should more or less look like this:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:strConnection]];
[request setRequestMethod:@"POST"];
[request setPostValue:@"2" forKey:@"GData-Version"];
[request setPostValue:@"application/atom+xml" forKey:@"Content-Type"];
[request setPostValue:YOUTUBE_DEVELOPER_KEY    forKey:@"X-GData-Key"];
[request setPostValue:[[delegate userInfo   ]accessTokenYoutube]  forKey:@"Authorization"];

NSString *body = [NSString stringWithFormat:@"<?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom'><id>%@</id></entry>",strVideoID];
[request appendPostData:[body dataUsingEncoding:NSUTF8StringEncoding]];

[request setDelegate:self];
[request setDidFinishSelector:@selector(didAddVideoToFavoriteFinish:)];
[request setDidFailSelector:@selector(didAddVideoToFavoriteFail:)];\
[request setDidReceiveDataSelector:@selector(didAddVideoToFavoriteSelect:)];
[request startAsynchronous];

[request release];

do we have a setPostValue method in ASIHTTPRequest? How this is worked for u? @Codo

ios - How to send a Http post request in objective c? - Stack Overflow

objective-c ios youtube-api asihttprequest
Rectangle 27 2

We can do it by creating a helper class of Swift in Objective-C project.

Install pods in your project with

platform :ios, '8.0'
use_frameworks!

target 'CryptoTest' do
    pod 'CryptoSwift'
end

Add a helper swift file with bridging header

For that go to the Settings > Packaging > Defines Module = True

Now import the CryptoSwift in The Helper File

//
//  CryptoHelper.swift
//  CryptoTest

import UIKit
import CryptoSwift

class CryptoHelper: NSObject {
    func cryptTest(){
        /* Hash enum usage */
        let input:[UInt8] = [49, 50, 51]

        let output = input.md5()
        // alternatively: let output = CryptoSwift.Hash.md5(input).calculate()

        print(output.toHexString())
    }
}
#import "ViewController.h"
#import "CryptoTest-Swift.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    CryptoHelper *testCrypt = [[CryptoHelper alloc]init];
    [testCrypt cryptTest];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
#import "CryptoTest-Swift.h"
#import "YourProjectModuleName-Swift.h"

ios - How to send CommonCrypto POST request using AES Crypto in Object...

ios objective-c web-services commoncrypto
Rectangle 27 2

I'd recommend reading Preventing Open Redirection Attacks (C#) which talks about using the IsLocalUrl() method from the ASP.NET MVC 3 UrlHelper class:

public bool IsLocalUrl(string url) {
  return System.Web.WebPages.RequestExtensions.IsUrlLocalToHost(
    RequestContext.HttpContext.Request, url);
}

IsUrlLocalToHost() method from the System.Web.WebPages RequestExtensions class:

public static bool IsUrlLocalToHost(this HttpRequestBase request, string url)
{
  return !url.IsEmpty() &&
      ((url[0] == '/' && (url.Length == 1 ||
       (url[1] != '/' && url[1] != '\\'))) ||   // "/" or "/foo" but not "//" or "/\"
       (url.Length > 1 &&
        url[0] == '~' && url[1] == '/'));   // "~/" or "~/foo"
}

javascript - How to encode value to put in iframe src attribute to pre...

javascript asp.net asp.net-mvc iframe xss
Rectangle 27 7

Since Google takes you to this post when searching for C# Web API Referrer here's the deal: Web API uses a different type of Request from normal MVC Request called HttpRequestMessage which does not include UrlReferrer. Since a normal Web API request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object, a better way is to use Headers.

HttpRequestMessage
UrlReferrer()
public static string UrlReferrer(this HttpRequestMessage request)
{
    return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}
Referrer Header
API Request
// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);

And now the Web API Request includes the referrer data which you can access like this from your Web API:

Request.UrlReferrer();

c# - Getting the HTTP Referrer in ASP.NET - Stack Overflow

c# asp.net http http-headers http-referer
Rectangle 27 7

Since Google takes you to this post when searching for C# Web API Referrer here's the deal: Web API uses a different type of Request from normal MVC Request called HttpRequestMessage which does not include UrlReferrer. Since a normal Web API request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object, a better way is to use Headers.

HttpRequestMessage
UrlReferrer()
public static string UrlReferrer(this HttpRequestMessage request)
{
    return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}
Referrer Header
API Request
// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);

And now the Web API Request includes the referrer data which you can access like this from your Web API:

Request.UrlReferrer();

c# - Getting the HTTP Referrer in ASP.NET - Stack Overflow

c# asp.net http http-headers http-referer
Rectangle 27 1

If all you need is to send secure request to a web server just use https. Using https encrypts the entire transfer and even any query parameters. You can not do better.

If you need more security use RNCryptor which is available in several languages for several platforms. It is well secure, well vetted and under current development/maintenance. It provides all the details such as a random iv, message authentication, key extension and versioning for strong security.

ios - How to send CommonCrypto POST request using AES Crypto in Object...

ios objective-c web-services commoncrypto
Rectangle 27 1

  • Don't Repeat Yourself (which can be more difficult with WebForms)

I've found client side functionality falls into a couple of categories:

  • Form validations, which are often extensions of Business Rules that should be managed in back end code
  • Usability enhancements, such as drop down menus, automatically capitalizing text when moving focus away from a text field, etc.
  • User interaction management, which is likely driven by business rules that are not easily done on the back end.

(Note: The code below probably has a few bugs in it, but it should give you the main idea)

This has been the area causing the most pain for me. I'm currently experimenting using FluentValidation with WebForms, and it's actually going pretty well. My best piece of advice regarding validations: Don't use the <asp:Foo /> validators! This is the reason that people complain about WebForms being a copy-and-paste framework. It doesn't have to be that way. Before a quick code example, don't use Data[Set|Table|Row]s either! You get all of the data, but none of the behavior. Use an ORM like Entity Framework or NHibernate, and have all of your ASP pages deal with entity classes, because then you can use something like FluentValidation:

namespace Project.Models.Entities
{
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime? ModifiedAt { get; set; }
    }
}
using FluentValidation;
using Project.Models.Entities;

namespace Project.Models.Validators
{

    public class PostValidator : AbstractValidator<Post>
    {
        public PostValidator()
        {
            RuleFor(p => p.Title)
                .NotEmpty()
                .Length(1, 200);

            RuleFor(p => p.Body)
                .NotEmpty();
        }
    }
}

Once you have your basic entities and validators, use them in your code behind:

namespace Project.UserControls
{
    public class PostControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                PostValidator validator = new PostValidator();
                Post entity = new Post()
                {
                    // Map form fields to entity properties
                    Id = Convert.ToInt32(PostId.Value),
                    Title = PostTitle.Text.Trim(),
                    Body = PostBody.Text.Trim()
                };
                ValidationResult results = validator.Validate(entity);

                if (results.IsValid)
                {
                    // Save to the database and continue to the next page
                }
                else
                {
                    BulletedList summary = (BulletedList)FindControl("ErrorSummary");

                    // Display errors to the user
                    foreach (var failure in results.Errors)
                    {
                        Label errorMessage = FindControl(failure.PropertyName + "Error") as Label;

                        if (errorMessage == null)
                        {
                            summary.Items.Add(new ListItem(failure.ErrorMessage));
                        }
                        else
                        {
                            errorMessage.Text = failure.ErrorMessage;
                        }
                    }
                }
            }
            else
            {
                // Display form
            }
        }

        ...
    }
}
<asp:BulletedList ID="ErrorSummary" runat="server" CssClass="Error-Summary" />

<p>
    <asp:Label ID="PostTitleLabel" AssociatedControlID="PostTitle" runat="server">* Title:</asp:Label>
    <asp:TextBox ID="PostTitle" runat="server" />
    <asp:Label ID="PostTitleError" runat="server" CssClass="Error" />
</p>

<p>
    <asp:Label ID="PostBodyLabel" AssociatedControlID="PostBody" runat="server">* Body:</asp:Label>
    <asp:TextBox ID="PostBody" runat="server" TextMode="MultiLine" />
    <asp:Label ID="PostBodyError" runat="server" CssClass="Error" />
</p>

<asp:HiddenField ID="PostId" runat="server" />

Now that we have a solid foundation in C#, you can add HTML attributes to each of the form fields and use jQuery Validate to trigger some of the front end validations. You can programatically loop through the FluentValidation rules:

PostValidator validator = new PostValidator();

foreach (var rule in validator.AsEnumerable())
{
    propertyRule = rule as FluentValidation.Internal.PropertyRule;

    if (propertyRule == null)
        continue;

    WebControl control = (WebControl)FindControl("Post" + propertyRule.PropertyName);

    foreach (var x in rule.Validators)
    {
        if (x is FluentValidation.Validators.NotEmptyValidator)
        {
            control.Attributes["required"] = "required";
        }
        else if (x is FluentValidation.Validators.MaximumLengthValidator)
        {
            var a = (FluentValidation.Validators.MaximumLengthValidator)x;

            control.Attributes["size"] = a.Max.ToString();
            control.Attributes["minlength"] = a.Min.ToString();
            control.Attributes["maxlength"] = a.Max.ToString();
        }

        ...
    }
}

Any validation that requires data from more than one field should not be handled on the client. Do this in C#. Trying to cobble this together in HTML and JavaScript on an ASP page becomes cumbersome and is not enough of a benefit to justify the added overhead and maintenance issues.

These JavaScript snippets assist users, and do little to implement business rules. On an application I work on, whenever the user moves focus away from a text box, each word should be capitalized so "foo bar" becomes "Foo Bar". JavaScript and event delegation to the rescue:

$(document).on("focusout", "input[type=text][data-capitalize-disabled^=true]", function(event) {
    event.target.value = event.target.value.replace(/(^|\s+)[a-z]/g, function(match, $1) {
        return $1.toUpperCase();
    });
});
PostTitle.Attributes["data-capitalize-disabled"] = "true";
<asp:TextBox ... data-capitalize-disabled="true" />

If you can manage this in the ASP file, now you've completely decoupled the front end and back end code!

This is the 800 Pound Gorilla of front end development. I like to use a "widget pattern" here, where you write a JavaScript class to encompass the behavior and use HTML attributes and class names as hooks for JavaScript to do its thing.

function FooWidget(element) {
    this.$element = $(element);
    this.fillOptions = this.fillOptions.bind(this);
    this.$element.on("click", "[data-action=fillOptions]", this.fillOptions);
}

FooWidget.prototype = {
    constructor: FooWidget,

    fillOptions: function(event) {
        // make ajax request:

        var select = this.$element.find("select:first")[0],
            option = null;

        option = document.createElement("option");
        option.value = "...";
        option.text = "...";
        select.appendChild(option);

        ...
    },

    focus: function() {
        this.$element.find(":input:first").focus();
    }
};

And in your ASP file:

<asp:Panel ID="FooPanel" runat="server">
    <button type="button" data-action="fillOptions">Fill Options</button>
    <asp:DropDownList ID="OptionsDropdown" runat="server" />
</asp:Panel>

<script type="text/javascript">
    var foo = new FooWidget("<%# FooPanel.ClientId %>");
</script>

Again, the object here is to keep JavaScript and HTML tied together, and not put any JavaScript in C#.

c# - How to avoid writing messy JavaScript in an ASP.NET code-behind? ...

c# javascript asp.net webforms code-behind
Rectangle 27 0

The fundamental transformation you need to do from a proxy request to an HTTP server request is to change the first line:

GET http://www.gmail.com/ HTTP/1.1
GET / HTTP/1.1

The full URL is required when the browser sends the request to the proxy, so that the proxy can make the further connection to the real server. However, an HTTP request to the server must not contain the protocol and hostname parts on the GET line.

However, this may not be the only thing you need to do. An HTTP proxy is a fairly complex application, due to things like different protocol version numbers and connection options on the browser-proxy connection versus the proxy-server connection.

RFC 2616 contains a considerable amount of information regarding the correct behaviour of HTTP proxy applications.

SO it should be something like this: GET / HTTP/1.1 Accept: text/html, application/xhtml+xml, / Accept-Language: en-US User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Accept-Encoding: gzip, deflate Proxy-Connection: Keep-Alive Host: www.gmail.com

I guess so, I can't see where your line breaks are in the comment. But you'll also want to act upon that Proxy-Connection header, as that is sent by the browser to the proxy and is not intended to be passed on to the server. Again, read RFC 2616 for full details.

I am able to connect to the server, but the problem is that proxy server is not reading entire response from the server. Connection is being reset by remote server while proxy is receiving data. Is the problem in reading data with this code while((n = read(rfd, buff, MAXLINE)) > 0) { write(connfd, buff, MAXLINE); printf("%s",buff); bzero(buff,MAXLINE); }

Rebuild request header from HTTP proxy server to Remote Server in C - ...

c http proxy get
Rectangle 27 0

var codes = {}
codes[1] = {}
codes[1]['title'] = "client-info Request headers received from client. Value is one of:"
codes[1]['I'] = "If Modified Since (IMS)"
codes[1]['C'] = "cookie"
codes[1]['E'] = "error in request"
codes[1]['S'] = "simple request (not conditional)"
codes[1]['N'] = "no-cache"
codes[2] = {}
codes[2]['title'] = "cache-lookup Result of Traffic Server cache lookup for URL. Value is one of:"
codes[2]['A'] = "in cache, not acceptable (a cache \"MISS\")"
codes[2]['H'] = "in cache, fresh (a cache \"HIT\")"
codes[2]['S'] = "in cache, stale (a cache \"MISS\")"
codes[2]['R'] = "in cache, fresh Ram hit (a cache \"HIT\")"
codes[2]['M'] = "miss (a cache \"MISS\")"
codes[2][' '] = "no cache lookup performed"
codes[3] = {}
codes[3]['title'] = "server-info Response information received from origin server. Value is one of:"
codes[3]['E'] = "error in response"
codes[3][' '] = "no server connection needed"
codes[3]['S'] = "served"
codes[3]['N'] = "not-modified"
codes[4] = {}
codes[4]['title'] = "cache-fill Result of document write to cache. Value is one of:"
codes[4]['U'] = "updated old cache copy"
codes[4]['D'] = "cached copy deleted"
codes[4]['W'] = "written into cache (new copy)"
codes[4][' '] = "no cache write performed"
codes[5] = {}
codes[5]['title'] = "proxy-info Proxy operation result. Value is one of:"
codes[5]['R'] = "origin server revalidated"
codes[5][' '] = "unknown?"
codes[5]['S'] = "served"
codes[5]['N'] = "not-modified"
codes[6] = {}
codes[6]['title'] = "error-codes Value is one of:"
codes[6]['A'] = "authorization failure"
codes[6]['H'] = "header syntax unacceptable"
codes[6]['C'] = "connection to server failed"
codes[6]['T'] = "connection timed out"
codes[6]['S'] = "server related error"
codes[6]['D'] = "dns failure"
codes[6]['N'] = "no error"
codes[6]['F'] = "request forbidden"
codes[7] = {}
codes[7]['title'] = "tunnel-info Proxy-only service operation. Value is one of:"
codes[7][' '] = "no tunneling"
codes[7]['U'] = "tunneling because of url (url suggests dynamic content)"
codes[7]['M'] = "tunneling due to a method (e.g. CONNECT)"
codes[7]['O'] = "tunneling because cache is turned off"
codes[7]['F'] = "tunneling due to a header field (such as presence of If-Range header)"
codes[8] = {}
codes[8]['title'] = "cache-type and cache-lookup cache result values (2 characters)"
codes[8]['I'] = "icp"
codes[8][' '] = "cache miss or no cache lookup"
codes[8]['C'] = "cache"
codes[9] = {}
codes[9]['title'] = "cache-lookup-result character value is one of:"
codes[9][' '] = "no cache lookup"
codes[9]['S'] = "cache hit, but expired"
codes[9]['U'] = "cache hit, but client forces revalidate (e.g. Pragma: no-cache)"
codes[9]['D'] = "cache hit, but method forces revalidated (e.g. ftp, not anonymous)"
codes[9]['I'] = "conditional miss (client sent conditional, fresh in cache, returned 412)"
codes[9]['H'] = "cache hit"
codes[9]['M'] = "cache miss (url not in cache)"
codes[9]['C'] = "cache hit, but config forces revalidate"
codes[9]['N'] = "conditional hit (client sent conditional, doc fresh in cache, returned 304)"
codes[10] = {}
codes[10]['title'] = "icp-conn-info ICP status"
codes[10][' '] = "no icp"
codes[10]['S'] = "connection opened successfully"
codes[10]['F'] = "connection open failed"
codes[11] = {}
codes[11]['title'] = "parent-proxy parent proxy connection status"
codes[11][' '] = "no parent proxy"
codes[11]['S'] = "connection opened successfully"
codes[11]['F'] = "connection open failed"
codes[12] = {}
codes[12]['title'] = "server-conn-info origin server connection status"
codes[12][' '] = "no server connection"
codes[12]['S'] = "connection opened successfully"
codes[12]['F'] = "connection open failed"

function showVia(form, value) {
    var text = value? value : form.via.value;
    if (value) {
        document.getElementById("via").value = value;
    }
    var via = document.getElementById("viaoutput")
    var output = "";
    var txtonly = text.match(/([a-zA-Z: ]+)/);
    text = txtonly[1];
    if (text.length == 5) {
        text = text + " "
    }
    if (text.length == 24) {
        var arr = text.match(/([a-zA-Z ]+):([a-zA-Z ]+)/);
        output = output + "<h3>Proxy request results:</h3>";
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Request headers received from client:</div> <font color="#003399">' + codes[1][arr[1][1]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Result of Traffic Server cache lookup for URL:</div> <font color="#003399">' + codes[2][arr[1][3]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Response information received from origin server:</div> <font color="#003399">' + codes[3][arr[1][5]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Result of document write-to-cache:</div> <font color="#003399">' + codes[4][arr[1][7]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Proxy operation result:</div> <font color="#003399">' + codes[5][arr[1][9]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Error codes (if any):</div> <font color="#003399">' + codes[6][arr[1][11]] + '</font><br/>';

        output = output + "<h3>Operational results:</h3>";
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Tunnel info:</div> <font color="#003399">' + codes[7][arr[2][1]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Cache-type and cache-lookup cache result values:</div> <font color="#003399">' + codes[8][arr[2][3]] + " / " + codes[9][arr[2][4]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">ICP status:</div> <font color="#003399">' + codes[10][arr[2][6]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Parent proxy connection status:</div> <font color="#003399">' + codes[11][arr[2][8]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Origin server connection status:</div> <font color="#003399">' + codes[12][arr[2][10]] + '</font><br/>';

    } else if (text.length == 6) {
        output = output + "<h3>Proxy request results:</h3>";
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Result of Traffic Server cache lookup for URL:</div> <font color="#003399">' + codes[2][text[1]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Response information received from origin server:</div> <font color="#003399">' + codes[3][text[3]] + '</font><br/>';
        output = output + '<div style="width: 450px; font-weight: bold; float: left;">Result of document write-to-cache:</div> <font color="#003399">' + codes[4][text[5]] + '</font><br/>';


    } else {
        output = "Invalid VIA data, must be 24 or 6 characters long.";
    }
    via.innerHTML = output;
    if (form) {
        window.location.hash = escape(text);
    }
    return false;
}

function checkQuery() {
    var url = location.href;
    if (url.indexOf("#") > 0) {
        var qs = url.substring(url.indexOf("#")+1).replace("%20", " ").replace("+", " ");
        if (qs && qs.length > 5) {
            showVia(false, qs);
        }
    }
}

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.

apache traffic server interpret via header,how to decode this code by ...

apache traffic