Friday 16 September 2016

Remove from First Page from URL


    <rewrite>

      <rules>
        <rule name="MyRule" patternSyntax="Wildcard">
          <match url="homepage" />
          <action type="Rewrite" url="Login.aspx" />
        </rule>
        <rule name="FirstRedirect" stopProcessing="true">
          <match url="^(.*\/)*Login\.aspx$" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_METHOD}" negate="true" pattern="^POST$" />
          </conditions>
          <action type="Redirect" url="{R:1}" redirectType="Permanent"/>
        </rule>
     
      </rules>

    </rewrite>

Monday 29 August 2016

Http Compression in Web Config

 
 
 
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>

Error Tracking on Asp.Net Page

 
[DllImport("iphlpapi.dll", ExactSpelling = true)]
 
public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
 
protected override void OnError(EventArgs e)
{
StringBuilder ErrString = new StringBuilder();
HttpContext ctx = HttpContext.Current;
Exception exception = ctx.Server.GetLastError();
string Error_Message = exception.Message.ToString();
string Source = exception.Source.ToString();
string Error_Trace = exception.StackTrace.ToString();
string Error_Path = ctx.Request.Url.ToString();
string User_Name = User.Identity.Name;
string IP = Request.ServerVariables["REMOTE_HOST"];
string Mac_Address = Request.ServerVariables["REMOTE_HOST"];
Response.Redirect("Error.aspx");
ctx.Server.ClearError();
base.OnError(e);
}

URL Rewriting in Asp.Net 3.5 and newer to 3.5

 
 
RouteCollection.MapPageRoute method, it has 5 overloads. These are:
1. MapPageRoute(String<routeName>, String<routeUrl>, String<physicalFile>)
2. MapPageRoute(String<routeName>, String<routeUrl>, String<physicalFile>),Boolean<checkPhysicalUrlAccess>)
3. MapPageRoute(String<routeName>, String<routeUrl>, String<physicalFile>, Boolean<checkPhysicalUrlAccess>, RouteValueDictionary<defaults>)
4. MapPageRoute(String<routeName>, String<routeUrl>, String<physicalFile>, Boolean<checkPhysicalUrlAccess>, RouteValueDictionary<defaults>, RouteValueDictionary<constraints> )
5. MapPageRoute(String<routeName>, String<routeUrl>, String<physicalFile>), Boolean<checkPhysicalUrlAccess>, RouteValueDictionary<defaults>), RouteValueDictionary<constraints>, RouteValueDictionary<dataTokens>)
 
 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
namespace URLRewriting
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("My-Post", "My-Post", "~/mypost.aspx");
routes.MapPageRoute("My-Blog", "My-Blog/{Key}", "~/User/myblog.aspx");
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}

Send Data to another server by HttpWebRequest and HttpWebResponse Web API



HttpWebRequest httpreq = (HttpWebRequest)WebRequest.Create(url);
         
            try
            {
                HttpWebResponse httpres = (HttpWebResponse)httpreq.GetResponse();
                StreamReader sr = new StreamReader(httpres.GetResponseStream());
                string results = sr.ReadToEnd();
                sr.Close();
                return results;
            }
            catch
            {
                return "0";
            }

Saturday 27 August 2016


Submit Once with an ASP.NET Button Server Control With Processing



<asp:Button ID="btnSubmit" runat="server" CssClass="btn-active"  
Text="Submit Data" onclientclick="ClientSideClick(this)"   UseSubmitBehavior="False"
onclick="btnSubmit_Click" Width="120px"/>

<script type="text/javascript">
function ClientSideClick(myButton) {
// Client side validation
if (typeof (Page_ClientValidate) == 'function') {
if (Page_ClientValidate() == false)
{ return false; }
}

//make sure the button is not of type "submit" but "button"
if (myButton.getAttribute('type') == 'button') {
// disable the button
myButton.disabled = true;
myButton.className = "btn-inactive";
myButton.value = "processing...";

//display message
document.getElementById("message-div").style.display = "block";
}
return true;
}
</script>


<script type="text/javascript">
     window.onbeforeunload = function () {
         $("input[type=button], input[type=submit]").attr("disabled", "disabled");
     };
</script>

Download a file in Web Application/Window Application/Console Application





using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace downloadfile
{
    class Program
    {
        static void Main(string[] args)
        {
            string remoteUri = "https://ashishkrjaiswal.blogspot.in/image/";
            string fileName = "1.jpg", myStringWebResource = null;
            // Create a new WebClient instance.
            WebClient myWebClient = new WebClient();
            // Concatenate the domain with the Web resource filename.
            myStringWebResource = remoteUri + fileName;
            Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
            // Download the Web resource and save it into the current filesystem folder.
            myWebClient.DownloadFile(myStringWebResource, fileName);
            Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
            Console.ReadKey();
            //Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath);
        }
    }
}

Covariance In C#


What is Covariance?

Covariance is a Polymorphism extension to the arrays, delegates and generics. It provides an implicit reference conversion for arrays, delegates and generic parameter types. Covariance preserves the assignment compatibility.

Explanation of Covariance

Create a base class as an Animal.
class Animal 

        public virtual int Get2 
        { 
            set; 
            get; 
        } 
        public virtual void Get1() 
        { 
            Console.WriteLine("Animal"); 
        } 
}  
Create a child class as Dog, which inherits base class as Animal.
class Dog : Animal 

        public int num; 
        public Dog(){} 
        public Dog(int a) 
        { 
            num = a; 
        } 
        public override int Get2 
        { 
            get { return num; } 
        } 
        public override void Get1() 
        { 
            Console.WriteLine("Dog"); 
        } 
}  
Create a Program class to create an instance and to explain about Covariance.
class Program   
{   
        static void Main(string[] args)   
        {   
          
            Animal objAnimal = new Dog();   
        } 
}  
Note: objAnimal object is a valid statement in .NET framework 3.5 because the child class points to the base class object.          
Dog ob1 = new Dog(1); 
           Dog ob2 = new Dog(2); 
           Dog ob3 = new Dog(3); 
           Dog ob4 = new Dog(4); 
 
           List<Dog> list = new List<Dog>(); 
 
           list.Add(ob1); 
           list.Add(ob2); 
           list.Add(ob3); 
           list.Add(ob4); 
 
           IEnumerable<Animal> obAnimal = new List<Dog>();  
Note:  object obAnimal of IEnumerable generic interface will throw an error in .NET framework 3.5 because in this object, the list of Dog class tries to point to the list of Animal class.

This statement is correct with .NET framework 4.0 because IEnumerable interface is in .NET framework 4.0 default Covariance enabled.

That's it. Thank you. For any suggestions and code clarification, please leave a comment.

Microsoft Announces DotNET Core 1.0

Microsoft has announced the release of .NET Core 1.0 on Windows, OS X and Linux! The new release has .NET Core runtime, libraries and tools. With that Microsoft also released ASP.NET Core 1.0 and Entity Framework Core 1.0.
They have also released Visual Studio and Visual Studio Code extensions so that you can create .NET Core projects. As stated via a blog post,
"This is the biggest transformation of .NET since its inception and will define .NET for the next decade. We’ve rebuilt the foundation of .NET to be targeted at the needs of today’s world: highly distributed cloud applications, micro services and containers."
NET Core is now available on Red Hat Enterprise Linux and OpenShift via certified containers. Also, .NET Core is fully supported by Red Hat and extended via the integrated hybrid support partnership between Microsoft and Red Hat.
.NET Core is a cross-platform, open source, and modular .NET platform for creating modern web apps, microservices, libraries and console applications. The following is included in .NET Core 1.0,
  • Cross-platform
  • Easy deployment
  • Command-line tools
  • .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.
  • The .NET Core platform is open source, using MIT and Apache 2 licenses.
  • .NET Core is supported by Microsoft, per .NET Core Support
Some application models have been built on top of .NET Core to extend its functionality, i.e.:
  • ASP.NET Core
  • Xamarin.Forms
  • Windows 10 Universal Windows Platform (UWP) 
.NET Core has the following parts,
  • .NET Runtime
  • Framework Libraries
  • Set of SDK tools
  • Set of Online Compilers
The announcement also stated how .NET Core has started impacting business, this is based on the feedback given by some customers. A leading IT company in China states the importance of .NET Core when compared with their previous Java back-end architecture:
".NET Core has reduced our release cycle by 20% and cost on engineering resources by 30%.” When speaking about the throughput improvements and cost savings: “Additionally, it has made it possible to reduce the number of VMs needed in production by half.”
Install .NET Core RTM now!

Create CAPTCHA Using Google API in ASP.Net



What is reCAPTCHA?
This  is a free service from Google that helps protect websites from spam and abuse that restricts the automated input sent by a system and allows only input from a real human.
Step 1
Create a simple web application to show the use of CAPTCHA.
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
  3. Provide the web site a name such as "Googelrecaptcha" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
  5. Drag and drop one button and label and two Textboxes onto the <form> section of the Default.aspx page.
  6. Now the default.aspx page source code will look as follows.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UsingGoogleRecaptcha.Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10. UserId: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br>
  11. word:<asp:TextBox TextMode="word" ID="TextBox2" runat="server"></asp:TextBox></td>
  12.     <asp:Button ID="btnLogin" runat="server" Text="Submit" OnClick="btnLogin_Click" /><br />  
  13.     <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>  
  14.     </form>  
  15. </body>  
  16. </html>

Step 2
Download the Google reCAPTCHA library for ASP.NET.
Download the library using this link reCAPTCHA ASP.NET library DownLoad
Step 3
Add a reference for the downloaded library, Recaptcha.dll, into the web application as in the following:
  1. Right-click on the web application, then click on Add reference.
  2. After Add reference choose Browse then find the location of the downloaded library.
  3. Select Recaptcha.dll and click on OK.
  4. After adding the Recaptcha.dll reference into the web application the bin folder will look such as follows.


In the preceding image you have seen how the Recaptcha.dll reference was added.
 Step 4
Add the Recaptcha control page header to the ASP.NET Page as in the following:
  1. <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>  
Step 5
Place the Google Recaptcha control on the Default.aspx page under the form tag as:
  1. <recaptcha:RecaptchaControl  
  2.     ID="recaptcha"  
  3.     runat="server"  
  4.     PublicKey="your_public_key"  
  5.     PrivateKey="your_private_key"  
  6.     />  
Understanding the Properties of RecaptchaControl
The RecaptchaControl provides many properties as a simple control but the following are some of the common properties:
  1. PublicKey: This is a mandatory property that valiadates the user request at the client-side. This is unique key is provided by Google for the web site with respect to the web site domain.
  2. PrivateKey: This is a mandatory property that valiadates the user request at the server-side with the Google server. This is a unique secret key provided by Google for the web site with respect to the web site domain basically for communicating between our server and the Google server.
  3. ErrorMessage: This is an optional property that sets an error message when the user enters an invalid CAPTCHA.
  4. AllowMultipleInstances: This is an optional property that decides the number of CAPTCHA code generations at a time. By default, it is false. If it is set to true then two CAPTCHA codes are generated for a single request.
  5. Theme: This is used to set the background color for the CAPTCHA control.
Step 6
Generate a Private and Public key from Google.
To generate the Private and Public Key we must use the following process:
  1. You must have a Google account. 
  2. Navigate to this link Get Recaptcha API Key
  3. You will be redirected to the following page:
get reCAPTCHA
After clicking on the "Sign Up Now!" button it will redirect to the Gmail account LoginPage, after Login into the Gmail it shows the following screen.
my account
Now in the preceding Domain TextBox enter your full domain of the web site. Now we have the local host application hence we will use the domain as localhost and click on the create button.
localhost
In the preceding image you have seen that it generated a Unique Public and Private API key with the specifics of our website domain address. Now set these keys to RecaptchaControl as in the following:
  1. <recaptcha:RecaptchaControl   
  2.  ID="recaptcha" runat="server"
  3.  PublicKey="6LeV7fwSAAAAACGlvCvX_cJzhsys5Ju_rW7Oqsn-"  
  4. PrivateKey="6LeV7fwSAAAAACgQzjfZscePs-7d6kGx9A-RweGY" >  
 After doing all of the preceding process, the Default.aspx source code will look as follows:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <table style="margin-top: 40px">  
  12.         <tr>  
  13.             <td>  
  14.                 UserId  
  15.             </td>  
  16.             <td>  
  17.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  18.             </td>  
  19.         </tr>  
  20.         <tr>  
  21.             <td>  
  22.                 Word  
  23.             </td>  
  24.             <td>  
  25.                 <asp:TextBox TextMode="word" ID="TextBox2" runat="server"></asp:TextBox>  
  26.             </td>  
  27.         </tr>  
  28.         <tr>  
  29.             <td>  
  30.             </td>  
  31.             <td>  
  32.                 <recaptcha:RecaptchaControl ID="recaptcha" runat="server" PublicKey="6LeV7fwSAAAAACGlvCvX_cJzhsys5Ju_rW7Oqsn-"  
  33.                     PrivateKey="6LeV7fwSAAAAACgQzjfZscePs-7d6kGx9A-RweGY" />  
  34.             </td>  
  35.         </tr>  
  36.         <tr>  
  37.             <td>  
  38.             </td>  
  39.             <td>  
  40.                 <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />  
  41.             </td>  
  42.         </tr>  
  43.     </table>  
  44.     <br />  
  45.     <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>  
  46.     </form>  
  47. </body>  
  48. </html>  
Step 7
Now open the default.aspx.cs file and add the following code to the OnClick event of the btnLogin button to ensure that the CAPTCHA code is validated successfully:
  1. protected void btnLogin_Click(object sender, EventArgs e)  
  2.    {  
  3.        if (recaptcha.IsValid)  
  4.        {  
  5.            lblResult.Text = "Login Sucesfully at  "+DateTime.Now.ToString("dd-MM-yyyy");  
  6.            lblResult.ForeColor = Color.Green;  
  7.   
  8.        }  
  9.        else  
  10.        {  
  11.   
  12.            lblResult.Text = "The verification Code Is incorrect.";  
  13.            lblResult.ForeColor = Color.Red;  
  14.   
  15.   
  16.        }  
  17.    }  
 Now run the application. The page will look such as follows:
Now enter an invalid code and click on the Login button. It will show the following message:
Now enter the proper code and click on the Login button. It will show the following message.
Now from all the preceding examples we have learned about the Google reCaptcha implementation.
Feature of Google reCAPTCHA
  1. You can regenerate a reCAPTCHA if you don't understand one.
  2. If you don't understand the CAPTCHA or are unable to read it then you can also get audio help.
  3. It is a free service from Google, there is no need to pay any money.
  4. Better security for your application.