Asp.Net

HTTP Error 405.0 – Method Not Allowed error while trying to make a DELETE request to a .ashx

Here’s the final web.config section. The thing I needed to add I was missing was changing the staticFileHandler from using “all verbs” to all of them spelled out.

 <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="StorageRoot" value="C:\temp\"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="2147480000" executionTimeout="3600"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
   
  </system.web>
  <system.webServer>
   
    <modules>
      <remove name="WebDAVModule" />
    </modules>
    <handlers accessPolicy="Read, Write, Execute, Script">
      <remove name="StaticFile" />
      <remove name="SimpleHandlerFactory-ISAPI-2.0" />
      <remove name="WebDAV" />
      <remove name="SimpleHandlerFactory-Integrated-4.0" />
      <remove name="SimpleHandlerFactory-Integrated" />
      <add name="SimpleHandlerFactory-Integrated" path="*.ashx" verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.UI.SimpleHandlerFactory" resourceType="Unspecified" requireAccess="Write" preCondition="integratedMode" />
      <add name="SimpleHandlerFactory-Integrated-4.0" path="*.ashx" verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.UI.SimpleHandlerFactory" resourceType="Unspecified" requireAccess="Write" preCondition="integratedMode,runtimeVersionv4.0" />
      <add name="SimpleHandlerFactory-ISAPI-2.0" path="*.ashx" verb="GET,HEAD,POST,DEBUG,PUT,DELETE" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
      <add name="StaticFile" path="*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" />
    </handlers>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147480000"/>
      </requestFiltering>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" users="*" verbs="GET,HEAD,POST,PUT,DELETE,DEBUG" />
      </authorization>
    </security>
    <tracing>
      <traceFailedRequests>
        <remove path="*" />
        <add path="*">
          <traceAreas>
            <add provider="ASP" verbosity="Verbose" />
            <add provider="ASPNET" areas="Infrastructure,Module,Page,AppServices" verbosity="Verbose" />
            <add provider="ISAPI Extension" verbosity="Verbose" />
            <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI" verbosity="Verbose" />
          </traceAreas>
          <failureDefinitions statusCodes="405" />
        </add>
      </traceFailedRequests>
    </tracing>
  </system.webServer>
</configuration>

Page not found 404 error in IIS 7 when uploading big file size

I struggled with one issue for hours, before realizing that IIS7 was the culprit. Even though maxrequestlength was set to 1GB in httpclientrequest (web.config) and executiontimeout was set to 600 seconds, for a larger file it would keep failing. Firebug was throwing a “404 not found” error for the handler.ashx!

IS has a security feature called requestFiltering, which is to prevent denial of service attacks. It sets the file size to 30MB maximum by default.
To change it, add the following to youor system.webServer section of web.config


   <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147480000"/>
      </requestFiltering>
</security>	     
             

Here maxAllowedContentLength is set to 2 GB approx.

The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020) – IIS 7 – Internet Information Service

In IIS7 I was trying to start my Default Web Site and was getting the following error screen.

IIS - Skype - Error_thumb[8]

A quick Google search turned up the following Microsoft Support Topic. Ok. Lets take a look at netstat and see what might be causing problems. Open a command prompt ([Windows Key + R] and enter cmd) and enter the command. After running netstat -ano, I noticed that there was indeed another process (with a process id of 796) accessing port 80. (You can enter netstat /? to see what the –ano flags are doing.)

netstat_thumb[12]

The offending process that is using port 80 has a process id of 796. Now, how to find out what that process 796 is?
Using the tasklist command will show a list of all processes running in windows. You can use the /fi flags to filter the results. In this case I’m using a filter that will only show processes with a PID that equals 796. tasklist /fi “PID eq 796”

Tasklist Filter Command_thumb[2]

The process with process id is Skype. Makes sense that it would be using port 80. I promptly closed down Skype and was then able to start my Default Web Site in IIS Manager. Hope this helps someone.

Telerik RadList Box Checkbox Items check all or uncheck all

Aspx page: I bound the lstLocations dynamically. So it look like as below.

Capture

<telerik:RadListBox ID=”lstLocations” runat=”server” CheckBoxes=”true” Width=”520px”
Height=”130px”>
</telerik:RadListBox>

// Select All checkbox buttons
<asp:CheckBox CssClass=”CBFull” ID=”chkSelectAll” runat=”server” Text=”Select All”
onclick=”javascript:return ToggleAllLocations(this);” />
// Add below function in javascript function



function ToggleAllLocations(checkBox) {
             //ctl00_ContentPlaceHolder1_RadDockLocFilter_C_lstLocations is a client id of radlistbox                   
            var listbox = $find("ctl00_ContentPlaceHolder1_RadDockLocFilter_C_lstLocations");

            var j = listbox.get_checkedItems().length;

            if (!document.getElementById(checkBox.id).checked) {
                for (var i = 0; i < j; i++) {
                    listbox.get_checkedItems()[0].uncheck();
                }
            }
            else {
                for (var i = 0; i < listbox.get_items().get_count(); i++) {
                    var item = listbox.getItem(i);
                    listbox.trackChanges();

                    item.set_checked(true);

                    listbox.commitChanges();

                }                                           
            }
            return true;
        }


The command “xcopy /Q /Y exited with code 4 error on build project .net

When you build the project visuals studio gives the error as below.

Error 2 The command “xcopy /Q /Y E:\My Projects\test\*.*
E:\My Projects\bin\” exited with code 4.

Go to project Properties > Build Events

In Post-build event section you may find something like this: xcopy “$(ProjectDir)Library\dsoframer.ocx” “$(TargetDir)” /Y /E /D1

Remove this line. Save All. Build the Project again.

Error resolved. 🙂

How to read RSS feed using Jquery

Click here download latest plugin

Getting Started
First include the jQuery and zRSSFeed libraries.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery.zrssfeed.min.js" type="text/javascript"></script>

Add a DIV tag where you wish the feed to display and give it an ID. There is no need to specify a class, this will be added.

<div id="test"></div>

Now add the script to call the zRSSFeed plugin with the RSS URL and any options. Our example gets 5 feeds from the Reuters site.

<script type="text/javascript">
$(document).ready(function () {
  $('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {
    limit: 5
  });
});
</script>

More option you can get by click here

LinkedIn authentication integration

For LinkedIn Authentication I have utilized LinkedIn Rest API which use oAuth 1.0 to authorize users and begin making REST API calls using any programming language. Complete understanding tutorials are placed at https://developer.linkedin.com/documents/oauth-overview

Following are the steps to implement LinkedIn Authentication in ASP.Net

Step 1 Installations

Install Hammock Library from CodePlex.com, Hammock is a REST library for .Net that greatly simplifies consuming Restful services.
Configure NuGet (optional to ease referencing code plex libraries directly in Visual Studio project). You can also get the NuGet from http://nuget.codeplex.com/

Step 2 Create LinkedIn Application in LinkedIn developer platform

Go to https://www.linkedin.com/secure/developer
Sign in with your LinkedIn credentials.
Click on Add New Application and fill in the form.
Once your application is created note the API Key and Secret Key that we will use to implement LinkedIn authentication in our application.

Step 3 Create ASP.Net Application

Open Visual Studio and create a new Web Application project.
Add references to Hammock library either by manually referencing from folder or just referencing through NuGet in Visual Studio Directly as shown below.

public
void RequestTokenAndAuthorize()

{

var credentials = new Hammock.Authentication.OAuth.OAuthCredentials

{

CallbackUrl = “http://localhost/LinkedInAuthWebSite/Callback.aspx”,

ConsumerKey = “API Key”,

ConsumerSecret = “Secret Key”,

Type = Hammock.Authentication.OAuth.OAuthType.RequestToken

};

var client = new Hammock.RestClient

{

Authority = “https://api.linkedin.com/uas/oauth”, Credentials = credentials };

var request = new Hammock.RestRequest { Path = “requestToken” };

Hammock.RestResponse response = client.Request(request);

String[] strResponseAttributes = response.Content.Split(‘&’);

string token = strResponseAttributes[0].Substring(strResponseAttributes[0].LastIndexOf(‘=’) + 1);

string authToken = strResponseAttributes[1].Substring(strResponseAttributes[1].LastIndexOf(‘=’) + 1);

Session[“Token”] = token;

Session[“TokenSecret”] = authToken;

Response.Redirect(“https://www.linkedin.com/uas/oauth/authorize?oauth_token=” + token);

}

CallBack URL will be called when the authorization is successfully done by LinkedIn.

Now Create a CallBack page where the callback takes place when the authorization is done after successful login. In my case I have created a Callback.aspx.
In the Callback page place following code in the Page_Load method.

protected
void Page_Load(object sender, EventArgs e)

{

String verifier = Request.QueryString[“oauth_verifier”].ToString();

Session[“Verifier”] = verifier;

var credentials = new Hammock.Authentication.OAuth.OAuthCredentials

{

ConsumerKey = “API Key”,

ConsumerSecret = “Secret Key”,

Token = Session[“Token”].ToString(),

TokenSecret = Session[“TokenSecret”].ToString(),

Verifier = verifier,

Type = Hammock.Authentication.OAuth.OAuthType.AccessToken,

ParameterHandling = Hammock.Authentication.OAuth.OAuthParameterHandling.HttpAuthorizationHeader,

SignatureMethod = Hammock.Authentication.OAuth.OAuthSignatureMethod.HmacSha1,

Version = “1.0″

};

var client = new
RestClient { Authority = “https://api.linkedin.com/uas/oauth”, Credentials = credentials, Method = WebMethod.Post };

var request = new
RestRequest { Path = “accessToken” };

RestResponse response = client.Request(request);

String[] strResponseAttributes = response.Content.Split(‘&’);

string token = strResponseAttributes[0].Substring(strResponseAttributes[0].LastIndexOf(‘=’) + 1);

string authToken = strResponseAttributes[1].Substring(strResponseAttributes[1].LastIndexOf(‘=’) + 1);

Session[“AccessToken”] = token;

Session[“AccessSecretToken”] = authToken;

GetUserProfile();

}

GetUserProfile method is used to get the Logged in User First Name and Last name to display on Callback page.

public
void GetUserProfile()

{

var request = new
RestRequest

{

Path = “~”

};

var credentials = new Hammock.Authentication.OAuth.OAuthCredentials

{

Type = Hammock.Authentication.OAuth.OAuthType.AccessToken,

SignatureMethod = Hammock.Authentication.OAuth.OAuthSignatureMethod.HmacSha1,

ParameterHandling = Hammock.Authentication.OAuth.OAuthParameterHandling.HttpAuthorizationHeader,

ConsumerKey = “API Key”,

ConsumerSecret = “Secret Key”,

Token = Session[“AccessToken”].ToString(),

TokenSecret = Session[“AccessSecretToken”].ToString(),

Verifier = Session[“Verifier”].ToString()

};

var client = new
RestClient()

{

Authority = “http://api.linkedin.com/v1/people”, Credentials = credentials, Method = WebMethod.Get

};

var MyInfo = client.Request(request);

String content = MyInfo.Content.ToString();

var person = from c in
XElement.Parse(content).Elements()

select c;

String fullName=String.Empty;

foreach (var element in person)

{

if((element.Name == “first-name”) || (element.Name==“last-name”))

fullName += element.Value.ToString();

}

lblName.Text = fullName;

}

Step 4 Run the Application

Download source code: here

How to send the build to already provisioned remote person’s iPhone

If you’ve been through the distribution process of an Ad Hoc application, you can appreciate the challenges of getting a build installed on someone’s device. From the differences of working with users on Windows versus Mac machines, to explaining how to import an Ad Hoc provisioning file and the associated build into iTunes, this process is anything but a walk in the park.
In this post I’ll take you through the steps of deploying Ad Hoc builds over-the-air, where users simply point the Safari web-browser (on their iPhone) to a link and tap to install the provisioning file and associated application.
Provisioning Profile
To begin, create a provisioning profile like you would for any other Ad Hoc build. In the image below you’ll notice I created a profile named AdHocOTAProfile and associated this with the app id AdHocOTA.

Once the profile is created, download onto your location machine and drag/drop the file onto the Xcode icon, this will install the provisioning file into the following folder: ~/Library/MobileDevice/Provisioning Profiles. The image below is a screenshot of the profile path on my machine – notice the provisioning file name is no longer the nice readable name that was written to your file system when you downloaded the file, this is to be expected.


From within Xcode, you can now associate this provisioning profile with your build. In the Target settings, select the Build tab, in the Code Signing section choose the new Provisioning Profile you created:

Xcode Build and Archive
Once you have a working project within Xcode (with the Code Signing identity set as mentioned above), make sure that you set the build type to Device.


From the Build menu in Xcode, choose Build and Archive (if this option is not highlighted, make sure you’ve selected Device in the build settings.

Once the build is complete, the Organizer window will appear – make sure the Archived Applications section is selected on the left panel.


In the figure above, I’ve updated the Name of the app to AdHoc OTA Test, this is optional, as well as any comments you would like to include.
Click on the Share button, and a new dialog will appear similar to that shown below:

From the Identity dropdown, select the Provisioning Profile created earlier:

Now choose Distribute for Enterprise – fill in the URL to the location where you plan to host the application. Note that you must include the fullpath to the application, including the name of the .ipa file that you plan to use:

At this point, don’t worry about the image files, I believe those are applicable only if you are doing an OTA deployment through an Enterprise developer account (internal app distribution for corporations). Update: Seems there may be a little more to how the images are used beyond Enterprise deployments, see the comments section for more information.
Once you select Ok, you will be prompted for a filename to save the build, verify that you use the same name as you specified in the URL:

At this point ipa and plist files will be created for you, the provisioning file will be embedded within the ipa.
OTA HTML File
With the build complete, we know need to create a very simple webpage that will allow users to find the application on a web-server.
The html below is as about as bare-bones as we can get, it’s nothing more than a link to the file, with a specific href for itms-services which Safari will recognize and initiate the download/install process when clicked.


<HTML>
<title>OTA Test App </title>
<body>
< a href=”//?action=download-manifest&url=http://3SixtySoftware.com/OTAtest/AdHocOTATest.plist” > Tap Here to Install the Application </a>
</body>
</HTML>

Important: – Replace the path shown above with the path to where you will upload the ipa and plist files that Xcode created.
Save the html file with the extension .html
Upload To Web-Server
We’re getting close – at this point we are ready to upload the ipa, plist and html files. The figure below shows the directory listing on the web-server where I uploaded the files:

Install the iPhone Application OTA
To download the application via OTA, start your web-browser and point it to the link where the html file lives. Once loaded you should see a screen similar to the figure below:

Tap on the link and a dialog will appear asking if you would like to install the Ad Hoc application:

If all works as expected, at this point you can send a link to the html file to anyone you included in the provisioning file and they can install the application OTA.

You download sample “Hello” project html, plist and ipa file: here

Reference link: Link 1, Link 2, Link 3