Amazon Ad

Tuesday, 13 June 2017

How to read any json from API in C# Dictionary class object?

Hi Guys,

I was working on a project and I found a really difficult thing to read values of any json object.

Below is the code for the same, this code can extract any json object

Dictionary<string, string> jdata = new Dictionary<string, string>();
            JsonTextReader reader = new JsonTextReader(new StringReader(response.Content));
            string p = "", v = "";
            while (reader.Read())
            {
               //Here this 2 represents the nested level of your json.
              //ex. {"validated":{"token":"xxxxxx","level":"x"}}
                if (reader.Depth == 2)
                {
                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        p = reader.Value.ToString();
                    }
                    if (reader.TokenType == JsonToken.String)
                    {
                        v = reader.Value.ToString();
                    }
                    if (p!="" && v != "")
                    {
                        jdata.Add(p, v);
                        p = "";
                        v = "";
                    }
                }

            }

Hope it help you guys

Tuesday, 2 May 2017

How to upload a file with parameters to an external API

Hi Guys,

Today I am going to tell you how to upload a file with parameters to an external API. It is quite useful to send information like profile details of a user to an API. To achieve

this there are two ways which I found to implement the same. The first way is using "RestSharp" which is a library used in C# to call API. This is really simple and allows async

calls which is quite prevalant these days. The second way is to create a utility class and then call the post method to send the details with file stream.

  Below are the ways

1. Using RestClient

//First Way Using Nuget Package https://www.nuget.org/packages/RestSharp
//RestRequest for adding parameters
RestRequest request = new RestRequest("http://www.test.com/profiledata.aspx", Method.POST);
request.AddParameter("details", msgTextBox.Text);
request.AddFile("profilepic", Server.MapPath("Myfiles/")+"test.jpg");

//calling server with restClient
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
     if (response.StatusCode == HttpStatusCode.OK)
     {
          //POST successful
  
     }
     else
     {
          //error ocured during POST
     }
});


2. Using Utility Class

a. Create  a utility class as below
    public static class Upload
    {
        private const string FileFieldNameDefault = "fileContent";

        public static WebResponse PostFile
            (Uri requestUri, NameValueCollection postData, Stream fileData, string fileName,
             string fileContentType, string fileFieldName, CookieContainer cookies,
             NameValueCollection headers)
        {
            ServicePointManager.Expect100Continue = false;

            if (requestUri.Scheme == "https")
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => true;
            }

            var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);

            webRequest.Method = "POST";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);

            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            string ctype;

            if (string.IsNullOrEmpty(fileContentType))
                fileContentType = TryGetContentType(fileName, out ctype)
                                    ? ctype
                                    : "application/octet-stream";

            fileFieldName = string.IsNullOrEmpty(fileFieldName) ? FileFieldNameDefault : fileFieldName;

            if (headers != null)
                foreach (string key in headers.AllKeys)
                {
                    var values = headers.GetValues(key);
                    if (values != null)
                        foreach (var value in values)
                            webRequest.Headers.Add(key, value);
                }

            if (cookies != null)
                webRequest.CookieContainer = cookies;

            var sbHeader = new StringBuilder();

            if (fileData != null)
            {
                var fileNameValue = string.Empty;

                if (string.IsNullOrEmpty(fileName) == false)
                    fileNameValue = string.Format(CultureInfo.InvariantCulture, "filename=\"{0}\"", Path.GetFileName(fileName));

                sbHeader
                    .AppendFormat("--{0}", boundary)
                    .AppendLine()
                    .AppendFormat("Content-Disposition: form-data; name=\"{0}\"; {1}", fileFieldName, fileNameValue)
                    .AppendLine()
                    .AppendFormat("Content-Type: {0}", fileContentType)
                    .AppendLine()
                    .AppendLine();
            }

            var sbFooter = new StringBuilder();
            sbFooter.AppendLine();

            if (postData != null)
                foreach (var key in postData.AllKeys)
                {
                    var values = postData.GetValues(key);
                    if (values != null)
                        foreach (var value in values)
                            sbFooter
                                .AppendFormat("--{0}", boundary)
                                .AppendLine()
                                .AppendFormat("Content-Disposition: form-data; name=\"{0}\"", key)
                                .AppendLine()
                                .AppendLine()
                                .Append(value)
                                .AppendLine();
                }

            sbFooter.AppendFormat("--{0}--\r\n", boundary);

            byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
            byte[] footer = Encoding.UTF8.GetBytes(sbFooter.ToString());
            long contentLength = header.Length + (fileData != null ? fileData.Length : 0) + footer.Length;

            webRequest.ContentLength = contentLength;

            using (var requestStream = webRequest.GetRequestStream())
            {
                requestStream.Write(header, 0, header.Length);

                if (fileData != null)
                {
                    var buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fileData.Read(buffer, 0, buffer.Length)) != 0)
                        requestStream.Write(buffer, 0, bytesRead);
                }

                requestStream.Write(footer, 0, footer.Length);

                return webRequest.GetResponse();
            }
        }

        public static WebResponse PostFile
            (Uri requestUri, NameValueCollection postData, string fileName,
             string fileContentType, string fileFieldName, CookieContainer cookies,
             NameValueCollection headers)
        {
            using (var fileData = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                return PostFile(requestUri, postData, fileData,
                                fileName, fileContentType, fileFieldName, cookies,
                                headers);
        }

        private static bool TryGetContentType(string fileName, out string contentType)
        {
            try
            {
                RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type");

                if (key != null)
                {
                    foreach (string keyName in from keyName in key.GetSubKeyNames()
                                               let subKey = key.OpenSubKey(keyName)
                                               where subKey != null
                                               let subKeyValue = (string)subKey.GetValue("Extension")
                                               where string.IsNullOrEmpty(subKeyValue) == false
                                               where string.Compare(Path.GetExtension(fileName), subKeyValue, StringComparison.OrdinalIgnoreCase) == 0
                                               select keyName)
                    {
                        contentType = keyName;
                        return true;
                    }
                }
            }
            catch
            {
                // fail silently
                // TODO: rethrow registry access denied errors
            }
            contentType = string.Empty;
            return false;
        }
    }

b. call the api using this example

//Thanks to http://stackoverflow.com/questions/7382786/uploading-a-file-using-application-x-www-form-urlencoded

            //Get the file name and save it in a stream
            string filename = Server.MapPath("~/ProfileFile/sampleCSV.csv");
            FileStream fileData = new FileStream(filename, FileMode.Open, FileAccess.Read);

            //Add the form values in the collection
            NameValueCollection frmValues = new NameValueCollection();
            frmValues.Add("method", "myUpload");
            frmValues.Add("userid", "xxxxxxxxx");
            frmValues.Add("password", "xxxxxxxx");
            frmValues.Add("xlsFile", filename);

            //Get the path of the target url
            Uri u=new Uri("http://www.test.com/GatewayAPI/rest");

            //Get the name value collection of headers
            //NameValueCollection headers = base.Request.Headers;
            NameValueCollection headers = null;

            //Post the data
            Upload.PostFile(u, frmValues, fileData, filename, "text/csv", "xlsFile", null, headers);


Thanks and Enjoy!!

Tuesday, 15 November 2016

How to create dynamic menus in MVC partial view?

Hi,

I was wonder how to create dynamic views in MVC partial view.

1. Create your table with name Menu

MenuId int
MenuName varchar(150)
MenuLink varchar(250)
ParentId int

Create a procedure

-- =============================================
-- Author:        <Ritesh Tandon>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================

Create PROCEDURE [dbo].[pGetUserMenus]
    -- Add the parameters for the stored procedure here
    @RoleId int=3
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    WITH Tree_CTE(MenuId, MenuName,MenuLink, ParentId,ParentName,IsActive,EntryBy,level)
AS
(
    SELECT MenuId,MenuName,MenuLink,ParentId,
    (select MenuName from MenuMaster where MenuId=MenuMaster.ParentId) as ParentName
    ,IsActive,EntryBy,rank() over (partition by ParentId order by MenuId)+1 as level
    FROM MenuMaster WHERE ParentID is null
    UNION ALL
    SELECT ChildNode.MenuId,ChildNode.MenuName,ChildNode.MenuLink,ChildNode.ParentId,
    (select MenuName from MenuMaster where MenuId=ChildNode.ParentId) as ParentName
    ,ChildNode.IsActive,ChildNode.EntryBy,Tree_CTE.level
    FROM MenuMaster AS ChildNode
    INNER JOIN Tree_CTE
    ON ChildNode.ParentID = Tree_CTE.MenuId
)
SELECT MenuId,MenuName,MenuLink,ParentId,ParentName,IsActive,EntryBy,level
FROM Tree_CTE
where MenuId in (select MenuId from RolesMenu where RoleId=@RoleId)
    and Isactive=1
order by level,ParentId


END
2. In your controller

public ActionResult _MainMenu()
        {
            return PartialView("_Menu", db.pGetUserMenus(0));
        }


3. In your partial view

@model IEnumerable<Menu>
<div class="hor-menu  ">
    <ul class="nav navbar-nav">
        @{
        int temp_pid=-1;   
               
        foreach (var item in Model)
        {
                if(item.ParentId == 0)
                {
                    @((item.ParentId==0)?Html.Raw("</li>"):Html.Raw(""))
                    @((item.ParentId==0 && temp_pid>0)?Html.Raw("</ul>"):Html.Raw(""))
           
                    @((item.ParentId==0)?Html.Raw("<li class='menu-dropdown classic-menu-dropdown '>"):Html.Raw(""))
                    <a href="javascript:;">
                        <i class="icon-note"></i>@item.MenuName
                    </a>
                }

                if (item.ParentId != 0)
                {
                   
                    @((temp_pid!=0 && temp_pid!=-1 && item.ParentId==0)?Html.Raw("</ul>"):Html.Raw(""))
                    @((temp_pid==0 && temp_pid!=-1 && item.ParentId!=0)?Html.Raw("<ul class='dropdown-menu pull-left'>"):Html.Raw(""))
                   
                        <li class=" ">
                            <a href="@item.MenuLink" class="nav-link">@item.MenuName</a>
                        </li>
                }
               
                temp_pid = item.ParentId;
        }
        }
    </ul>

Enjoy!!

Tuesday, 5 July 2016

How to add questions in between youtube videos

I was given a task to embed questions in between youtube videos. The questions should appear after a particular timeframe i.e like after 10 seconds and after 30 seconds. I found a javascript file which takes care of the same. Create a div tag in your html page, the id attribute of the div tag should be "player". There is also a div which has a popup with id "myModal" which is used to invoke the popup. You can use any jquery or javascript popup for the same. In this case I have used inbu

Here is the complete code of the file

<script src="https://www.youtube.com/iframe_api"></script>
<script>
      var player,videoid;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '415px',
          width: '780px',
          videoId: 'YOUR_YOUTUBE_VIDEO_ID',
      playerVars: { 'autoplay': 0, 'controls': 1,'autohide':1,'wmode':'opaque' },
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
      }

      var done = false,isQ1displayed=false,isQ2displayed=false;
      function onPlayerStateChange(event) {
          setInterval(function () {
              var current_time = player.getCurrentTime();
              console.log(current_time);
              if(Math.floor(current_time)==10 && isQ1displayed==false)
              {
          $("#myModalLabel").html("Q. Question 1?");   
          pauseVideo();
          isQ1displayed=true;
          done=true;
              }
          else if(Math.floor(current_time)==30 && isQ2displayed==false)
              {
          $("#myModalLabel").html("Q. Question 2?");
          pauseVideo();
          isQ2displayed=true;
          done=true;
              }
          }, 1);
      }
     
      function hidePopup(){
    $('#myModal').modal('hide');
    done=false;
    playVideo();
      }
     
      function showPopup(){
    $('input[type=radio]').each(function() { this.checked = false; });
    $('#myModal').modal({
    backdrop:'static',
    keyboard:false
    });
      }
     
      function pauseVideo() {
          player.pauseVideo();
      showPopup();
      }

      function playVideo() {
          player.playVideo();
      }

      function stopVideo() {
        player.stopVideo();
      }
</script>

Thanks
Ritesh Tandon

Saturday, 30 April 2016

How to generate dynamic URL from javascript.

Dear all,

I was given a task to generate dynamic url using javascript, After going through all the aspects I decided to work with history object available in javascript. Almost every modern browser today supports modern techniques used in html5. There are basically two methods, Apart from external plugins for url rewriting we can use these inbuilt javascript functions.

1. PushState as the name suggests pushes the history object in the history, just like stack push. It adds the object in the history object which is taken automatically by the browser. The first object is taken as the current object. For Instance,

window.history.pushState(null, response.pageTitle, '/developer/consturction/House');

Here, the statObj is an object which is the object taking the object value. Next parameter is page title and last parameter is urlPath is path which is displayed on the browser.
This is used in most of the cases when the url is to be created dynamically based on user action on the browser without page post back or reload. In the above example, When executed the URL of the browser will become, http(s)://yourdomain/developer/construction/House.

2 ReplaceState as the name suggests, it replaces the exising object with a new object. For example,

window.history.replaceState(stateObj,response.pageTitle,urlPath);

Here the parameters are the same except for the functionality.

Thanks
Ritesh

Friday, 8 April 2016

Authorize your WEB API to send data only to your website only

Hi,

I was wondering how we could implement security in web API, I wanted to send JSON data only to my desired website(s). Therefore, I decided to  create a custom Authorize Attribute in C# which will authorize any request and will help in implementing security for WEB API.

First we will create a class like below

public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        private string _responseReason = "";
        public bool ByPassAuthorization { get; set; }

        List<string> allowedWebsites = new List<string>();

        public ApiAuthorizeAttribute()
        {
            //List of authorized websites
            allowedWebsites.Add("localhost");
            allowedWebsites.Add("dev.test.com");
            allowedWebsites.Add("staging.test.com");          
            allowedWebsites.Add("new-test.test.com");
            allowedWebsites.Add("test.com");
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            if (!string.IsNullOrEmpty(_responseReason))
                actionContext.Response.ReasonPhrase = _responseReason;
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
           
            //checking against our custom table goes here
            if (!this.IsValidRequest(actionContext))
            {
                this.HandleUnauthorizedRequest(actionContext);
                _responseReason = "Access Denied";
                return false;
            }

            return true;
            //return base.IsAuthorized(actionContext);
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //logic that will run before even authorizing the customer / user. if this logic fails
            // then the user checking against our custom database table will not processed.
            // you can skip this if you don't have such requirements and directly call
            base.OnAuthorization(actionContext);
          
        }

        public bool IsValidRequest(HttpActionContext actionContext)
        {

            //Check if a valid api page is requested
            /*var apiAttributes = GetApiAuthorizeAttributes(actionContext.ActionDescriptor);
            if (apiAttributes != null && apiAttributes.Any())
                return true;
            return false;*/
            string url = HttpContext.Current.Request.UrlReferrer.Host;
            bool isAllowed=allowedWebsites.Contains(url);
            return isAllowed;
        }
    }

Secondly, We have to implement it see how its done below
 
        [HttpGet]
        [ApiAuthorizeAttribute]
        [ActionName("GetData")]
        public List<DataMaster> GetData()
        {
             //your code goes here..
        }

------------------

In case of webforms we have to use global.asax file to achieve the same result. Create a function in global.asax for ex.

protected bool CheckRequest()
        {
            List<string> allowedWebsites = new List<string>();
            allowedWebsites.Add("test");
            allowedWebsites.Add("localhost");

            if (Request.Url != null)
            {
                string requestfrom = Request.Url.GetLeftPart(UriPartial.Authority);
                requestfrom = requestfrom.Substring(requestfrom.IndexOf('/') + 2);
                requestfrom = requestfrom.Substring(0,requestfrom.IndexOf(':'));

                bool isAllowed = allowedWebsites.Contains(requestfrom);
                return isAllowed;
            }
            else
            {
                return true;
            }
        }

Then in  Application_BeginRequest event in global .asax do this:

 protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (!CheckRequest())
            {
                Response.Write("<center><h1>A suspicious activity has been detected, Your IP has been recorded for further investigation.</h1></center>");
                Response.End();
            }
       }

Thats it!!
 

Wednesday, 23 December 2015

How to get printer serial number in c#

Dear All,

I was facing an issue to get Printer serial number, Here is how I was able to solve it using C#.

You can see the serial number of the model by going into "Device Manager" and then select the device and click on "Properties".
A dialog with name USB Printing Support Properties will appear, Click on the "Details" section and you will see lot of different properties of the device.
Look for the property "Device Instance Path" in case of printer. Here you will find a value like "USB\VID_XXXX&PID_XXXX\XXXXXXXXX" here "X" represents your device related numbers.

The problem was how to get these details from C#, I searched on google and found a link where I got an idea to create this utility.

Special Thanks to "Django Anonymous" for
http://stackoverflow.com/questions/20416888/to-get-provider-from-managementobjectsearcher-win32-pnpentity

The above link has a different question, But somehow I thought to use the details to build my own utility. However, I was not able to get the device name associated with the device serial number and my comboboxlist produces only serial number not the device name. I am working on it, Hopefully will give you a solution of the same.

Here is my own code in c#

    public class Device
    {
        public string DeviceName { get; set; }
        public string SerialNumber { get; set; }
    }

 public class ComboboxItem
    {
        public string Text { get; set; }
        public object Value { get; set; }

        public override string ToString()
        {
            return Text;
        }
    }

public List<Device> GetDeviceList()
{
    List<Device> devicelist = new List<Device>();
using (ManagementObjectSearcher searchernew = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption Like '%print%'"))
                {
                    foreach (ManagementObject mgmt in searchernew.Get()){
                        foreach (PropertyData property in mgmt.Properties){
                            if (property.Name == "DeviceID" && property.Value.ToString().Contains("USB\\VID_")){
                                string val = property.Value.ToString();
                                if (val.IndexOf('\\') != -1){
                                    val = val.Substring(val.LastIndexOf('\\') + 1);
                                    devicelist.Add(new Device() { SerialNumber = val, DeviceName = val });
                                }
                            }
                        }
                    }
                }
return devicelist;
}

private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                List<Device> lst = GetDeviceList();
                foreach (Device a in lst)
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = a.DeviceName;
                    item.Value = a.SerialNumber;
                    cmbPrinter.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
}


Thanks

Friday, 18 September 2015

How to upload file from jquery ajax

Dear All,

Today I am going to tell you how to upload a file from jquery ajax. First of all you need is a jquery reference and a .cs file as I am doing it in ASP.net.

Step 1 : Create a form, Here I have created a form and included a file upload html <input type="file" id="fileUpload"> and simple button with name "btnUploadFile".

Step 2: Write the javascript code to upload the file

<script type="text/javascript">
            $(document).ready(function () {
                $('#btnUploadFile').on('click', function () {
                    var files = $("#fileUpload").get(0).files;

                    var data = new FormData();
                    data.append('data', files[0]);

                    // Make Ajax request with the contentType = false, and processData = false
                    var ajaxRequest = $.ajax({
                        type: "POST",
                        url: "SendFile.aspx/uploadfile",
                        contentType: false,
                        processData: false,
                        data: data,
                        success: function (data) {
                            alert('File uploaded Successfully');
                        },
                        error: function (xhr, ajaxoptions, thrownerror) {
                            alert(xhr.status);
                            alert(thrownerror);
                        },
                        asyn:false
                        //data: data
                    });
                   
                    ajaxRequest.done(function (xhr, textStatus) {
                        // Do other operation
                    });
                });
            });
</script>

Monday, 1 June 2015

Call SOAP Web Service From MS SQL

Hi Guys,

I was given a task to call a SOAP web service from MS SQL. There few steps which are required before writing the T-SQL for invoking web service.


Step 1:

Give rights to invoke OA(Object Access) for SOAP. Below is how to do it

sp_configure 'show advanced options', 1
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1
GO
RECONFIGURE;
GO
sp_configure 'show advanced options', 1
GO
RECONFIGURE;
GO

Step 2:

TSQL stored procedure which calls the web service. I Assume that you have a web service with WebMethod "GetProgram" with one Parameter "Code". I am also assuming that its a POST method. Below is the strored procedure:

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Ritesh Tandon>
-- Create date: <01-Jun-2015>
-- Description:    <Invoke Web Service From SQL Stored Procedure>
-- =============================================
Alter PROCEDURE pCallWebServiceGet
    -- Add the parameters for the stored procedure here
    @ServicePath varchar(500)='',
    @RequestBody varchar(1000)='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <GetProgram xmlns="http://tempuri.org/">
      <Code>1513100000</Code>
    </GetProgram>
   </soapenv:Body>
</soapenv:Envelope>'
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Declare @Object as Int;
    Declare @ResponseText as Varchar(8000);
    Declare @RequestLength as int

    set @RequestLength=Len(@RequestBody)

    --Code Snippet
    Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
    Exec sp_OAMethod @Object, 'open', NULL, 'POST','http://www.yourwebsite.com/service.asmx?op=GetProgram','false'
    EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type', 'text/xml;charset=UTF-8'
    --EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'SOAPAction', 'POST'
    --EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Length', @RequestLength
    Exec sp_OAMethod @Object, 'send', NULL, @RequestBody
    Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

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.

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:...