Amazon Ad

Wednesday, 29 April 2015

Application_Error Not Invoked From Global.asax

Hi ,

If you have implemented Application_Error event in Global.asax and its not invoked, after all the hard work, You need to make sure to do the following

1. Sometimes in the web.config the CustomError property is set to Off. In this case set it to On.

2. Make sure your Global.asax's bin file (app_global.dll) exists and the modified date is same as your Global.asax file.

3. If you have implemented RadCompression, It will not invoke the Application_Error event until you add the following in your web.config file

<telerik.web.ui>  
    <radCompression>   
        <excludeHandlers>
            <add handlerPath="Global.asax" matchExact="true"/>
        </excludeHandlers>
    </radCompression>
</telerik.web.ui>

4. Still if you are not able to implement it, Use HttpModule to trap an error.

These are some of the common causes of not invoking the error event.

Thanks

Tuesday, 28 April 2015

405 Method not found in ASP.NET Web API and Angular.js

Hi,

I was facing a strange problem when implementing web api in asp.net with Angular.js. The web api method was absolutely fine and was working locally. But when it was published on the development server, It gave the error 405 method not found. I added the CORS in web.api, in web.config and in the controller by enabling cors (Adding the line [EnableCors("*", "*", "*")] before the controller class). But no use it was still giving me the same message with OPTIONS method not found.

Finally, I resolved it by adding the config section in my angular code where i was creating my module. Below is the code. After adding this it resolved all the issues i was facing.

Thursday, 16 April 2015

How make faster asp.net websites in ASP.NET 4.5 with EF 6

Hi Guys,

I was able to successfully create a responsive and very fast website with EF6 and ASP.NET 4.5. Here is how i was able to do it successfully.

1. Create a basepage which all the webforms inherits and add the following code in the constructor of the basepage

a. you need to install a nuget package

PM> Install-Package EFInteractiveViews

b. Then add below code in your constructor of basepage class
public BasePage()
        {
            try
            {
                using (var ctx = new LPUOnlineEntities())
                {
                    InteractiveViews.SetViewCacheFactory(ctx, new SqlServerViewCacheFactory

(ctx.Database.Connection.ConnectionString));
                }
            }
            catch (Exception ex)
            {

            }
        }


2. Enable ViewState Compression

a. Create two methods in your basepage class
protected override object LoadPageStateFromPersistenceMedium()
        {
            string viewState = Request.Form["__VSTATE"];
            byte[] bytes = Convert.FromBase64String(viewState);
            bytes = Compressor.Decompress(bytes);
            LosFormatter formatter = new LosFormatter();
            return formatter.Deserialize(Convert.ToBase64String(bytes));
        }

        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            LosFormatter formatter = new LosFormatter();
            StringWriter writer = new StringWriter();
            formatter.Serialize(writer, viewState);
            string viewStateString = writer.ToString();
            byte[] bytes = Convert.FromBase64String(viewStateString);
            bytes = Compressor.Compress(bytes);
            //ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
            ScriptManager.RegisterHiddenField(this, "__VSTATE", Convert.ToBase64String(bytes));
        }

b. A class which compresses the data

using System.IO;
using System.IO.Compression;

public static class Compressor
{

    public static byte[] Compress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        GZipStream gzip = new GZipStream(output,
                          CompressionMode.Compress, true);
        gzip.Write(data, 0, data.Length);
        gzip.Close();
        return output.ToArray();
    }

    public static byte[] Decompress(byte[] data)
    {
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream gzip = new GZipStream(input,
                          CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buff = new byte[64];
        int read = -1;
        read = gzip.Read(buff, 0, buff.Length);
        while (read > 0)
        {
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
        }
        gzip.Close();
        return output.ToArray();
    }
}

Monday, 16 February 2015

Saving object/array object in LocalStorage in ASP.NET Bootstrap

Hi Guys,

I was checking out a small code in Javascript which adds a javascript class object/JSON object in a

localstorage. The localstorage saves the array object and displays it in the bootstrap table/grid.

You need to have knowledge of JSON and object oriented programming in Javascript. However comments

have been added which can help you out.

Following is the HTML and Javascript content

<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8">
   
    <title>Enter Exam Details</title>

    <!-- include Bootstrap CSS for layout -->
    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-

combined.min.css" rel="stylesheet">
  </head>
 
  <body>
    <div class="container">
      <h1>Add your past exam details</h1>
     
      <form method="post" class="form-horizontal">
        <fieldset>
          <legend>Add Exams</legend> 
          <div class="control-group">
            <label class="control-label" for="type">Type of enquiry</label>
            <div class="controls">
              <select name="type" id="type">
                <option value="">Please select</option>
                <option value="general">General</option>
                <option value="sales">Sales</option>
                <option value="support">Support</option>
              </select>
            </div>
          </div>
     

Sunday, 15 February 2015

Entity Framework unable to retrieve metadata for

Hi Guys,

I was facing a problem while implementing a custom class in the Entity Framework. I faced the following error

"unable to retrieve metadata for XXXX.XXXX"

The error was coming due to the fact that EF context uses metadata for Generting EF tt models. Whereas a custom class is not using tt models and therefore it gave this error. However i couldn't find the solution but i managed to do it by creating a new connectionstring which was not having metadata.

Saturday, 13 December 2014

Angular JS in ASP.NET

Hi,

I was creating one simple form and code in Angular.js. It was my first day of working with Angular.js. Following is the code to start with

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Angular Forms</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <script src="Scripts/angular.js"></script>
</head>

Friday, 28 November 2014

Send Email To Any Email From Any Email

Hi Guys,

Following is the code for sending email to any user from any user. The below code is a good code and please do not misuse this.      

 MailMessage objMail = new MailMessage();
    //Replace email_of_the_user with the email whom you want to send to
            objMail.To.Add("email_of_the_user");
    //Replace email_to_be_cc'ed with the email whom you want to cc to
            objMail.CC.Add("email_to_be_cc'ed");
    //Replace Your_Email_ID with email id from whom you want the email to be sent from
            objMail.From = new MailAddress("Your_Email_ID", "Alias Name");

    //Subject of the email
            objMail.Subject = "Subject for the email";

            StringBuilder emailbody = new StringBuilder();
            emailbody.Append("Dear User,<br/><br/>");
            emailbody.Append("This is a test email <br/>");
            emailbody.Append("<br/><br/>Thanks<br/><b>Division of Infotech</b>");
            objMail.Body = emailbody.ToString();
            objMail.Priority = MailPriority.High;
            objMail.IsBodyHtml = true;
            System.Net.Mail.SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Timeout = 600000;
        //Replace EmailID with Email Id from where you want the email to be sent to
        //Replace Password with the email(email from) password
            smtp.Credentials = new System.Net.NetworkCredential("EmailID", "Password");
            smtp.EnableSsl = true;
            smtp.Send(objMail);
            objMail.Dispose();

Thanks
Ritesh

Wednesday, 26 November 2014

Find Local and Internet IP Address in C#

Hi Guys,

I was given a task to get the IP Address of a computer. Most of the times when we are working we have two IP's one assigned on the LAN network and one assigned by the internet ISP. I was given a task to find both of them. Here is how i was able to create the same.

    //For ISP (Internet Service Provider) IP Address
    public static string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(sIPAddress))
            {
                return context.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                string[] ipArray = sIPAddress.Split(new Char[] { ',' });
                return ipArray[0];
            }
        }

    //For LAN (Local Area Network) IP Address
        public string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

Thanks
Ritesh Tandon

Generate Password As Per Password Policy in C#

Hi Guys,

I was given a task to generate a password having following conditions

1. Min 10 Chracters
2. Must have one upper case letters
3. Must have one or more lower case letters
4. Must have one or more special characters
5. Must have one or more numbers.

Following is how i was able to do the same in C#

private string ActionNewPassword()
    {
        String Num = "0123456789";
        String Sp = "!@#$%&*()+{}[]^-";
        String SL = "abcdefghijklmnopqrstuvwxyz";
        String UCL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random rnd = new Random();
       
        //One or more upper case letters
        string part1 = UCL.Substring(rnd.Next(UCL.Length),1);

        //One or more numbers
        string part2 = Num.Substring(rnd.Next(Num.Length), 1);

        //Minimum 4 small case letters
        string part3 = "";
        for(int i=0;i<4;i++)
            part3 += SL.Substring(rnd.Next(SL.Length), 1);

        //Minimum 1 special character
        string part4 = Sp.Substring(rnd.Next(Sp.Length), 1);

        //Minimum 3 small numbers
        string part5 = "";
        for (int i = 0; i < 3; i++)
            part5 += SL.Substring(rnd.Next(SL.Length), 1);

        string pwd = part1 + part2+part3+part4+part5;

        //Message.InnerHtml = pwd;
       
        return pwd;
    }

Thanks
Ritesh Tandon

Generate Verification Code In MS SQL

Hi Guys,

I was given a task to generate an email verification code from MS SQL. I finally achieved with some  string functions and inbuilt Random function in MS SQL. Here is the code

    --Generate verification code
    declare @ab varchar(36)='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    declare @vercode varchar(11)=''
    declare @counter int=0
    declare @ind int=0
    WHILE @counter < 9
    BEGIN
        set @ind=(select RAND()*35)
        set @vercode=@vercode+(select SUBSTRING(@ab, @ind+1, 1))
        SET @counter = @counter + 1
    END
    print @vercode

The below code generates an alphanumeric code having 9 alphanumeric characters. You can increase or decrease the length by chaning the lenght of the @vercode variable and the while loop counter.

Thanks
Ritesh

Friday, 29 August 2014

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.BadImageFormatException: Invalid access to memory location. (Exception from HRESULT: 0x800703E6)

Dear all,

I was struggling with an error in ASP.NET. The error was coming when i implemented Ad (Active Directory) password change code in one of my forms. It some times worked but sometimes it gave the following error

 System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.BadImageFormatException: Invalid access to memory location. (Exception from HRESULT: 0x800703E6) --- End of inner exception stack trace --- at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args) at _adPassword.ChangeUserADPassword(String Username, String Password, String newPwd)

I searched a lot and then found a solution for this problem. The problem was the CPU overload on the server. The server CPU usage when moved above 75-90% this form resulted this error. I recycled the Application pool and also made some changes on the server to maintain the CPU usage below 75%. This solved the problem and now i don't face any sort of problem with this form.

Thanks
Ritesh Tandon

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...