Monday 10 April 2017

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.