sábado, 17 de noviembre de 2018

Complete Example for Error Handlers Aspx

Complete Example for Error Handlers

Original Microsoft Page: https://msdn.microsoft.com/es-mx/library/bb397417.aspx
This code example includes elements for both page-level and application-level exception handling.

Code Example Files

The example consists of the following files:
  • Web.config
  • Global.asax
  • Default.aspx
  • ExceptionUtility (to be put in the App_Code folder)
  • GenericErrorPage.aspx
  • HttpErrorPage.aspx
  • Http404ErrorPage.aspx
  • DefaultRedirectErrorPage.aspx

Web.config

The following example shows the Web.config file. The customErrors section specifies how to handle errors that occur with file types that are mapped to ASP.NET, such as .aspx, .asmx, and .ashx files. (In IIS 6.0 and in IIS 7.0 in classic mode, static content files such as .html and .jpg files are not mapped to ASP.NET.)
The settings in the example customErrors section cause any unhandled HTTP 404 (file not found) errors to be directed to the Http404ErrorPage.aspx file. These HTTP 404 errors would occur if a request were made for an .aspx file, .asmx file, and so on and if the requested file did not exist. All other unhandled errors in ASP.NET files are directed to the DefaultRedirectErrorPage.aspx file.
If static content files are not handled by ASP.NET, a request for a nonexistent .html or .jpg file does not cause a redirect to the Http404ErrorPage.aspx file. If you want ASP.NET to handle requests for all file types, you can configure IIS to map file-name extensions to ASP.NET.
Note Note
In the example, the mode attribute is set to "On" so that you can error messages when you run the example in Visual Studio. In a production environment, this setting would normally be "RemoteOnly". ASP.NET then renders error pages to external users. If a request is made on the server computer (localhost), ASP.NET renders a page with detailed error information.
Internal Error

Global.asax

The following example shows the Global.asax file
Security note Security Note
Never set the mode attribute in the customErrors element to "Off" in the Web.config file if you have not created an Application_Error handler in the Global.asax file. If the mode is set to "Off," potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.

void Application_Error(object sender, EventArgs e)
{
  // Code that runs when an unhandled error occurs

  // Get the exception object.
  Exception exc = Server.GetLastError();

  // Handle HTTP errors
  if (exc.GetType() == typeof(HttpException))
  {
    // The Complete Error Handling Example generates
    // some errors using URLs with "NoCatch" in them;
    // ignore these here to simulate what would happen
    // if a global.asax handler were not implemented.
      if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
      return;

    //Redirect HTTP errors to HttpError page
    Server.Transfer("HttpErrorPage.aspx");
  }

  // For other kinds of errors give the user some information
  // but stay on the default page
  Response.Write("

Global Page Error

\n"
); Response.Write( "" + exc.Message + "
\n"); Response.Write("Return to the " + "Default Page\n"); // Log the exception and notify system operators ExceptionUtility.LogException(exc, "DefaultPage"); ExceptionUtility.NotifySystemOps(exc); // Clear the error from the server Server.ClearError(); }

ExceptionUtility

The following example shows the ExceptionUtility file. Error logs might be directed to the computer's ErrorLog file, or, if the computer is part of a Web farm, the error log might be recorded in a globally available text file, or even a database. You might also need to immediately notify system administrators of a problem.
The ExceptionUtility class in the example has two static methods: one to log the exception, and one to notify system administrators. How those methods are implemented in your code depends on the needs of your organization. For this example, you must grant write permissions to the ASP.NET worker process account (by default, this is NETWORK SERVICE) for the App_Data folder to enable the application to write to the error log.

using System;
using System.IO;
using System.Web;

// Create our own utility for exceptions 
public sealed class ExceptionUtility
{
    // All methods are static, so this can be private 
    private ExceptionUtility()
    { }

    // Log an Exception 
    public static void LogException(Exception exc, string source)
    {
        // Include enterprise logic for logging exceptions 
        // Get the absolute path to the log file 
        string logFile = "App_Data/ErrorLog.txt";
        logFile = HttpContext.Current.Server.MapPath(logFile);

        // Open the log file for append and write the log
        StreamWriter sw = new StreamWriter(logFile, true);
        sw.WriteLine("********** {0} **********", DateTime.Now);
        if (exc.InnerException != null)
        {
            sw.Write("Inner Exception Type: ");
            sw.WriteLine(exc.InnerException.GetType().ToString());
            sw.Write("Inner Exception: ");
            sw.WriteLine(exc.InnerException.Message);
            sw.Write("Inner Source: ");
            sw.WriteLine(exc.InnerException.Source);
            if (exc.InnerException.StackTrace != null)
            {
                sw.WriteLine("Inner Stack Trace: ");
                sw.WriteLine(exc.InnerException.StackTrace);
            }
        }
        sw.Write("Exception Type: ");
        sw.WriteLine(exc.GetType().ToString());
        sw.WriteLine("Exception: " + exc.Message);
        sw.WriteLine("Source: " + source);
        sw.WriteLine("Stack Trace: ");
        if (exc.StackTrace != null)
        {
            sw.WriteLine(exc.StackTrace);
            sw.WriteLine();
        }
        sw.Close();
    }

    // Notify System Operators about an exception 
    public static void NotifySystemOps(Exception exc)
    {
        // Include code for notifying IT system operators
    }
}

Default.aspx

The following example shows the Default.aspx page. This file provides several buttons, each of which raises a different exception. The Page_Errorhandler on the page displays an error page and logs some of these errors. Unhandled errors are passed to the Application_Error handler in the Global.asax file. The Application_Error handler displays an error page and logs some of the remaining errors. Any errors that are still not handled are directed to the page indicated by the customErrors section of Web.config file.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> Exception Handler Page
"form1"
runat="server">

Default Page

Click this button to create an InvalidOperationException.
Page_Error will catch this and redirect to GenericErrorPage.aspx.
"Submit1"
runat="server" CommandArgument="1" OnClick="Submit_Click" Text="Button 1" /> Click this button to create an ArgumentOutOfRangeException.
Page_Error will catch this and handle the error.
"Submit2"
runat="server" CommandArgument="2" OnClick="Submit_Click" Text="Button 2" /> Click this button to create a generic Exception.
Application_Error will catch this and handle the error.
"Submit3"
runat="server" CommandArgument="3" OnClick="Submit_Click" Text="Button 3" /> Click this button to create an HTTP 404 (not found) error.
Application_Error will catch this and redirect to HttpErrorPage.aspx.
"Submit4"
runat="server" CommandArgument="4" OnClick="Submit_Click" Text="Button 4" /> Click this button to create an HTTP 404 (not found) error.
Application_Error will catch this but will not take any action on it, and ASP.NET will redirect to Http404ErrorPage.aspx. The original exception object will not be available.
"Submit5"
runat="server" CommandArgument="5" OnClick="Submit_Click" Text="Button 5" /> Click this button to create an HTTP 400 (invalid url) error.
Application_Error will catch this but will not take any action on it, and ASP.NET will redirect to DefaultRedirectErrorPage.aspx. The original exception object will not be available.
"Button1"
runat="server" CommandArgument="6" OnClick="Submit_Click" Text="Button 6" />

GenericErrorPage.aspx

The following example shows the GenericErrorPage.aspx page. This page creates a safe message that it displays to remote users. For local users (typically developers and testers of the application), the page displays a complete exception report. The Page_Error handler redirects InvalidOperationException errors to this page.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> Generic Error Page
"form1"
runat="server">

Generic Error Page

"InnerErrorPanel"
runat="server" Visible="false"> Inner Error Message:
"innerMessage"
runat="server" Font-Bold="true" Font-Size="Large" />
        "innerTrace"
runat="server" /> Error Message:
"exMessage"
runat="server" Font-Bold="true" Font-Size="Large" />
      "exTrace"
runat="server" Visible="false" />
Return to the 'Default.aspx'> Default Page

HttpErrorPage.aspx

The following example shows the HttpErrorPage.aspx page. This page also creates a safe message that depends on the value of the error code, which it displays to remote users. For local users, the page displays a complete exception report. The Application_Error handler redirects HttpException errors to this page.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> Http Error Page
"form1"
runat="server">

Http Error Page

"InnerErrorPanel"
runat="server" Visible="false"> "innerMessage" runat="server" Font-Bold="true" Font-Size="Large" />
        "innerTrace"
runat="server" /> Error Message:
"exMessage" runat="server" Font-Bold="true" Font-Size="Large" />
      "exTrace"
runat="server" Visible="false" />
Return to the 'Default.aspx'>Default Page

Http404ErrorPage.aspx

The following example shows the Http404ErrorPage.aspx page. ASP.NET redirects unhandled HTTP 404 (file not found) errors to this page. The page displays the same message to remote and local users.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> HTTP 404 Error Page
"form1"
runat="server">

HTTP 404 Error Page

Standard error message suitable for file not found errors. The original exception object is not available, but the original requested URL is in the query string.

Return to the 'Default.aspx'
> Default Page

DefaultRedirectErrorPage.aspx

The following example shows the DefaultRedirectErrorPage.aspx page. ASP.NET redirects any unhandled errors except HTTP 404 errors to this page. The page displays the same message to remote and local users.
<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> DefaultRedirect Error Page
"form1"
runat="server">

DefaultRedirect Error Page

Standard error message suitable for all unhandled errors. The original exception object is not available.

Return to the 'Default.aspx'
> Default Page



External Error not ASPX

The following example shows the DefaultRedirectErrorPage.aspx page. ASP.NET redirects any unhandled errors except HTTP 404 errors to this page. The page displays the same message to remote and local users.

    
     errorMode="Custom" defaultResponseMode="ExecuteURL" existingResponse="Replace" >
       />
       statusCode="404" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx"/>
       statusCode="400" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx"/>
       statusCode="403" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx" />      
       statusCode="500" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx" />
    







sábado, 27 de octubre de 2018

hilite.me change code to html

hilite.me converts your code snippets into pretty-printed HTML format, easily embeddable into blog posts, emails and websites.
Just copy the source code to the left pane, select the language and the color scheme, and click "Highlight!". The HTML from the right pane can now be pasted to your blog or email, no external CSS or Javascript files are required.

http://hilite.me/

Reset Image Orientation using EXIF in C#

Let's say you took the photos using smart phones or regular cameras in different orientation and in different angles (rotate the camera to 90°, 270° degrees, etc). And now you copy the photos to system and observe that, the photo orientation is incorrect.

When you upload these photos to other sites to set profile picture or  album picture or timeline photo, etc., you will see that photos were uploaded with incorrect orientation.

So, sometimes we need to re-orient the photos as per the orientation recorded by cameras. The orientation information is stored in EXIF meta data of each photo. 

The following C# code will correct the orientation, if you capture the photos from any device, in any angles..

Microsoft RotateFlipType Enumeration https://docs.microsoft.com/en-us/windows/desktop/api/gdiplusimaging/ne-gdiplusimaging-rotatefliptype

original Link https://www.dotnet4techies.com/2014/09/reset-image-orientation-using-exif-in-c.html

 string sImage = @"E:\srinivas\DSC01.jpg";
    Image img = Image.FromFile(sImage);
 
    foreach (var prop in img.PropertyItems)
    {
        if (prop.Id == 0x0112) //value of EXIF
        {
            int orientationValue = img.GetPropertyItem(prop.Id).Value[0];
            RotateFlipType rotateFlipType = GetOrientationToFlipType(orientationValue);
            img.RotateFlip(rotateFlipType);
            img.Save(@"E:\srinivas\DSC01_modified.jpg");
            break;
        }
    }
 
private static RotateFlipType GetOrientationToFlipType(int orientationValue)
{
    RotateFlipType rotateFlipType = RotateFlipType.RotateNoneFlipNone;
 
    switch (orientationValue)
    {
        case 1:
            rotateFlipType = RotateFlipType.RotateNoneFlipNone;
            break;
        case 2:
            rotateFlipType = RotateFlipType.RotateNoneFlipX;
            break;
        case 3:
            rotateFlipType = RotateFlipType.Rotate180FlipNone;
            break;
        case 4:
            rotateFlipType = RotateFlipType.Rotate180FlipX;
            break;
        case 5:
            rotateFlipType = RotateFlipType.Rotate90FlipX;
            break;
        case 6:
            rotateFlipType = RotateFlipType.Rotate90FlipNone;
            break;
        case 7:
            rotateFlipType = RotateFlipType.Rotate270FlipX;
            break;
        case 8:
            rotateFlipType = RotateFlipType.Rotate270FlipNone;
            break;
        default:
            rotateFlipType = RotateFlipType.RotateNoneFlipNone;
            break;
    }
 
    return rotateFlipType;
}

Generate Postback with isPostback C# ASPX

page.aspx


<script type="text/javascript">
$(function () {
     //javascript or jQuery event
     $("#MyButton").click(function() {
          <%=PostBackString %> //this will insert our postback code at runtime
     });
});
</script>

page.aspx.cs


protected string PostBackString;
protected void Page_Load(object sender, EventArgs e)
{
     //this gets the postback code that we will use on our aspx page
     PostBackString = Page.ClientScript.GetPostBackEventReference(this, "MyEventArgumentName");
     if (IsPostBack) 
     {
          //Check if the postback was caused by our event
          if (Request["__EVENTARGUMENT"] == "MyEventArgumentName")
          {
               //Do something
          }
     }
}

domingo, 29 de julio de 2018

Add (Insert) Items to ASP.Net ListBox using JavaScript and jQuery

In this article I will explain how to add (insert) Item (values) to ASP.Net ListBox using JavaScript and jQuery. The value from the TextBox will be added to the ASP.Net ListBox control using JavaScript and jQuery.
 
Add (Insert) Items to ASP.Net ListBox using JavaScript
The following HTML Markup consists of an ASP.Net ListBox control, a TextBox and a Button.
When the Button is clicked, the AddValues JavaScript function is executed. Inside this function, first the value from the TextBox is fetched and then a HTML OPTION element is created.
The TextBox value is set to the InnerHtml and Value property of the OPTION element. Finally the OPTION element is appended to the ASP.Net ListBox control.
<asp:ListBox ID="ListBox1" runat="server" Width="150" Height="60"></asp:ListBox>
<br />
<hr />
<asp:TextBox ID="txtValue" runat="server" />
<asp:Button ID="btnAdd" Text="Add" runat="server" OnClientClick="return AddValues()" />
<script type="text/javascript">
function AddValues() {
    var txtValue = document.getElementById("<%=txtValue.ClientID %>");
    var listBox = document.getElementById("<%= ListBox1.ClientID%>");
    var option = document.createElement("OPTION");
    option.innerHTML = txtValue.value;
    option.value = txtValue.value;
    listBox.appendChild(option);
    txtValue.value = "";
    return false;
}
</script>
 
 
Add (Insert) Items to ASP.Net ListBox using jQuery
The following HTML Markup consists of an ASP.Net ListBox control, a TextBox and a Button.
When the Button is clicked, the jQuery click event handler is executed. Inside this event handler, first the value from the TextBox is fetched and then a HTML OPTION element is created.
The TextBox value is set to the InnerHtml and Value property of the OPTION element. Finally the OPTION element is appended to the ASP.Net ListBox control.
<asp:ListBox ID="ListBox1" runat="server" Width="150" Height="60" SelectionMode = "Multiple"></asp:ListBox>
<br />
<hr />
<asp:TextBox ID="txtValue" runat="server" />
<asp:Button ID="btnAdd" Text="Add" runat="server" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("[id*=btnAdd]").bind("click"function () {
        var value = $("[id*=txtValue]").val();
        var listBox = $("[id*=ListBox1]");
        var option = $(").val(value).html(value);
        listBox.append(option);
        $("[id*=txtValue]").val("");
        return false;
    });
});
</script>
 
 
Screenshot
Add (Insert) Items to ASP.Net ListBox using JavaScript and jQuery
 
 
Fetching the ASP.Net ListBox items on Server Side (Code Behind)
The items added to the ASP.Net ListBox using JavaScript and jQuery are not added in ViewState and hence will not be available in the ListBox Items collection.
Thus we will need to make use of Request.Form collection and fetch the values in the following way.
C#
protected void Submit(object sender, EventArgs e)
{
    string values = Request.Form[ListBox1.UniqueID];
}
 
VB.Net
Protected Sub Submit(sender As Object, e As System.EventArgs)
    Dim values As String = Request.Form(ListBox1.UniqueID)
End Sub
 
The following screenshot displays the ListBox selected values posted to the server.
Add (Insert) Items to ASP.Net ListBox using JavaScript and jQuery