Set Access-Control-Allow-Origin in Web API

If you access your web api methods from another domain using JQuery Ajax or GetJSON method then there you may see an error like
XMLHttpRequest cannot load (url). No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘(url)’ is therefore not allowed access.

You can just install CORS with package manager

Install-Package Microsoft.AspNet.WebApi.Cors

Follow this link http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Or create a own simple attribute like

  • Add a new class AllowCrossSiteJsonAttribute
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                if (actionExecutedContext.Response != null)
                    actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    
                base.OnActionExecuted(actionExecutedContext);
            }
        }
    
  • For whole API Controller
    [AllowCrossSiteJson]
    public class UserAPIController : ApiController
    {
            // GET api/userapi
            public HttpResponseMessage Get()
            {
                  return uservar;
            }
    }
    
  • For a specific API Call
    public class UserAPIController : ApiController
    {
             // GET api/userapi
             [AllowCrossSiteJson]
             public HttpResponseMessage Get()
             {
                   return uservar;
             }
    }
    

that’s it.

ControlAdapter for ASP SiteMapPath

Today i faced a small issue related Breadcrumb. I’m using asp:SiteMapPath to show Breadcrumb. It works fine. But look and feel is little boring and i want it convert to bootstrap style. I tried to customize the design with diffrent templates properties, but always it shows surround a tag and bootstrap not working.
after some googling i found a solution ; add a Control Adaper for this.

Now it working fine and looks good.

First add a class for this ControlAdapter SiteMapPathControlAdapter.

 public class SiteMapPathControlAdapter : WebControlAdapter
    {
 public virtual string LinkCssClass
        { get; set; }
        protected override void RenderBeginTag(HtmlTextWriter writer)
        {
            writer.WriteLine();
            writer.WriteBeginTag("div");

            writer.WriteAttribute("class", ((System.Web.UI.WebControls.SiteMapPath)(Control)).CssClass);
            writer.Write(HtmlTextWriter.TagRightChar);
        }
        protected override void RenderEndTag(HtmlTextWriter writer)
        {
            writer.WriteEndTag("div");
            writer.WriteLine();
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Indent++;
            SiteMapPath item = (SiteMapPath)Control;
            SiteMapProvider Provider = ((System.Web.UI.WebControls.SiteMapPath)(Control)).Provider;
            SiteMapNodeCollection collection = new SiteMapNodeCollection();
            SiteMapNode node = Provider.CurrentNode;
            if (node != null)
            {

                collection.Add(node);
                while (node != Provider.CurrentNode.RootNode)
                {
                    node = node.ParentNode;
                    collection.Add(node);
                }

            }
            BuildItems(collection, true, writer);
            writer.Indent--;
            writer.WriteLine();
        }
        private void BuildItems(SiteMapNodeCollection items, bool isRoot, HtmlTextWriter writer)
        {
            if (items.Count > 0)
            {
                writer.WriteLine();

                writer.Indent++;
                for (int i = items.Count - 1; i > -1; i--)
                {
                    BuildItem(items[i], writer);
                }
                writer.Indent--;
                writer.WriteLine();
            }
        }
        private void BuildItem(SiteMapNode item, HtmlTextWriter writer)
        {
            if ((item != null) && (writer != null))
            {
                if (item.Url.Length > 0)
                {
                    writer.WriteLine();
                    writer.WriteBeginTag("a");
                    writer.WriteAttribute("href", Page.ResolveUrl(item.Url));
                    string linkCSS = (Control.Attributes["LinkCssClass"] ?? "").ToString();
                    writer.WriteAttribute("class", linkCSS);
                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Write(item.Title);
                    writer.WriteEndTag("a");
                    writer.WriteLine();

                }
            }
        }
   }

Second add a browser file to link this adapter :

<browsers>
  <browser refID="Default">
    <controlAdapters>
       <adapter controlType="System.Web.UI.WebControls.SiteMapPath" adapterType="CSharpSampleWebApps.SiteMapPathControlAdapter" />
    </controlAdapters>
  </browser>
</browsers>

and my aspx page

<div>
        <asp:SiteMapPath runat="server" ID="SiteMapPath1" CssClass="btn-group btn-breadcrumb"
            LinkCssClass="btn btn-success">
        </asp:SiteMapPath>
    </div>

Now rendering HTML like :

    <div>
        
<div class="btn-group btn-breadcrumb">

		<a href="/default.aspx" class="btn btn-success">Home</a>

		<a href="/Services.aspx" class="btn btn-success">Services</a>

		<a href="/Training.aspx" class="btn btn-success">Training</a>


</div>

    </div>

Request URL in ASP.Net

Suppose i am request a page http://localhost:57089/test/WebForm1.aspx?id=10 then what are the request property values in server side ? Many of the cases we need part of a request URL. Maybe Some times Port No or File Path or Exact file Name etc.

I just write the values in server side Request Property.

// Accessing http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write( Request.RawUrl);
// /test/WebForm1.aspx?id=10
Response.Write( Request.Url.ToString());
// http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write(Request.Url.AbsolutePath);
// /test/WebForm1.aspx
Response.Write(Request.Url.AbsoluteUri);
// http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write("
" + Request.Url.Authority);
// localhost:57089
Response.Write(Request.Url.DnsSafeHost);
// localhost
Response.Write( Request.Url.Host);
// localhost
Response.Write(Request.Url.LocalPath);
// /test/WebForm1.aspx
Response.Write( Request.Url.OriginalString);
// http://localhost:57089/test/WebForm1.aspx?id=10
Response.Write( Request.Url.PathAndQuery);
// /test/WebForm1.aspx?id=10
Response.Write(Request.Url.Port.ToString());
// 57089
Response.Write(Request.Url.Query);
// ?id=10
Response.Write( Request.Url.Scheme);
// http
foreach (var Segment in Request.Url.Segments)
{
Response.Write("
" + Segment );
}
// [0] /
// [1] test/
// [2] WebForm1.aspx
Response.Write("
" + Request.QueryString);
// id=10
Response.Write( Request.PhysicalPath);
// C:\Users\user\documents\visual studio 2010\Projects\WebApplication3\WebApplication3\test\WebForm1.aspx
Response.Write( Request.PhysicalApplicationPath);
// C:\Users\user\documents\visual studio 2010\Projects\WebApplication3\WebApplication3\
Response.Write(Request.Path);
// /test/WebForm1.aspx
Response.Write(Request.ApplicationPath);
// /

 Response.Write("<br/>" + System.IO.Path.GetFileName(Request.Url.LocalPath));
//   WebForm1.aspx
Musthaan
Musthaan

Select all rows from one checkbox in a GridView

Page Markup

<asp:GridView runat="server" ID="grdAbsentApprovals" ShowHeader="true" ShowHeaderWhenEmpty ="true"  Width="100%"
                            CssClass="mGrid" AutoGenerateColumns="False">
                               <AlternatingRowStyle BackColor="#EEEEEE" />
                <Columns>
                    <asp:TemplateField>
                    <HeaderTemplate>
                    <input type="checkbox" id ="chkSelectAll" onclick="SelectAllCheckboxes(this)"></checkbox>
                    </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox runat="server" ID="chkItem" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="DOC_NO" HeaderText="DOC NO" SortExpression="DOC_NO" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
                   
                    <asp:BoundField DataField="NAME" HeaderText="NAME" SortExpression="NAME" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
                     <asp:BoundField DataField="NOOFDAYS" HeaderText="DAYS" SortExpression="NOOFDAYS" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right" />
                    <asp:BoundField DataField="DESCRIPTION" HeaderText="DESCRIPTION" SortExpression="DESCRIPTION"  HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
                </Columns>
                <EmptyDataTemplate>
                No Data Found.
                </EmptyDataTemplate>
            </asp:GridView>

JavaScript

 

  function SelectAllCheckboxes(chk) {
                    $('#<%=grdAbsentApprovals.ClientID%>').find("input:checkbox").each(function () {
                        if (this != chk) { this.checked = chk.checked; }
                    });
                }

Musthaan

Read Excel Data as a DataSet in C#

Hi,
In one of my CMS project,client need to upload data from a excel file and update that datas to our database.
First did that using Office Excel Interop.It Working in locally and in IIS also. but when i upload it to actual web site, that not working.What is the issue ? MS Office must installed in server and some settings in DCOMCNFG. Both are not posible becouse i have only ftp access. Then i search any other ways is there ? Yes i found a dll for this. Read all data as a dataset each sheet read in seperate table.So my problem solved.

I am sharing a very sample app for how to use this.

Download Source Code from github