I'm building a login form with Web API(ASP.NET), but dunno how to do it.

At first what I thought was to send a POST with the username and password and query it through the database, if they user info is correct then redirect the user to the welcome screen.

But i thing this approach is really old/plain, I'm just doing it to learn so I don't need something fancy.

I've reading and found something called token based authentication, can you briefly explain me what are the benefits of using this method vs the method that I thought?

BTW to show the data related to that user that logged in, I thought to store the username in a variable and then query through the database and see if the data belongs to the user, is this approach right?

Or how can I do it to show the data that is bind to a certain user.

THANKS

I'm trying to implement routing in my website. Homepage of the website consists of various articles and if I click on any one of them another page opens(singlepage1.aspx) which consists of the whole article.

Following is the route table:

enter image description here

name is the article heading. queryValues is the article code.

Code in the home page is as follows:

enter image description here where lblln1 contains the heading and lblhidln1 contains the article code.

On singlepage1.aspx I am getting the queryValues parameter and then I'm fetching that article from the database.

Suppose I open up an article from home page and get the following url:

enter image description here where heeading-12 is the heading of article and 103 is the code of the article.

But if I change the heading part of URL, suppose i write it as - heead12ing-12-103. It still opens up the same page, but with URL heead12ing-12-103.

Is there any way that if someone changes the URL manually and loads the page, the URL should be set in correct form i.e., if someone writes as heead12ing-12-103 then after loading the page the URL should be automatically set to heeading-12-103.

Thanks in advance for the help

I have a HTML page which contains a back button which is supposed to send user to immediate previous page. This is happening if there is no activity on the application for more than 2 Minutes, if time is less in that case it is working perfect. My application is deployed on IIS7. Below is the complete HTML page and with back button to send to previous page..

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title></title>
    <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
    <meta name="ProgId" content="VisualStudio.HTML">
    <meta name="Originator" content="Microsoft Visual Studio .NET 7.1">
    </head>
<body>
    <TABLE cellSpacing="1" cellPadding="1" width="100%" border="0" height="100%">
        <TR>
            <TD height=256 align=center><font color ="red">Exception Occurred !!<br>
            Kindly contact your system administrator</font></TD>
        </TR>
        <TR>
            <TD height=41 align =center><button onclick="history.go(-1);" type=button>Back</button></TD>
        </TR>
        <TR>
            <TD></TD>
            <TD></TD>
            <TD></TD>
        </TR>
    </TABLE>
</body>
</html>

What is the issue? How to resolve

Update: I am redirecting to above HTML page from C# code as ..

if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))
 {
   this.Server.ClearError();
   this.Server.Transfer("Error.htm");
}

Above shared HTML is Error.htm.

enter image description here I have been trying to get the proper input type radio button to select based on the value in the database on page load. It should show the respective button as selected, eg. if the file type is 'Delimited', the delimited button should be selected. I have verified the code behind that it works fine. I have also checked the page source that shows checked="checked" but the button still does not visibly show as being selected. I have tried it with a regular asp.RadioButton and that worked fine, why is it not working here? The code behind runs in the OnInit method.

HTML

<div class="form__group">
    <asp:label class="form__label" id="switchLabel_FileType" runat="server">File Type</asp:label>
    <div id="FileType" class="btn-group" data-toggle="buttons" style="width:100%">
            <label class="btn btn-primary btn-small active" style="width:33.3%" >
                <input type="radio" name="options" id="label_Delimited" autocomplete="off" runat="server" style="width:33%" /> Delimited
            </label>

            <label class="btn btn-primary btn-small active" style="width:33.3%" >
                <input type="radio" name="options" id="label_Excel" autocomplete="off" runat="server" style="width:33%"/> Excel
            </label>
            <label class="btn btn-primary btn-small active" style="width:33.3%">
                <input type="radio" name="options" id="label_FixedWidth" autocomplete="off" runat="server" style="width:33%"/> Fixed Width
            </label>
    </div> 
</div>

C#

            string fType = row[Constants.FILE_TYPE].ToString();
            if (fType == Constants.FILETYPE_DELIMITED)
            {
                label_Delimited.Checked = true;
            }

            else if (fType == Constants.FILETYPE_XLS)
            {
                label_Excel.Checked = true;
            }

            else if (fType == Constants.FILETYPE_FIXEDWIDTH)
            {
                label_FixedWidth.Checked = true;
            }

This is how whole project should work:
1. Mysql database holds all the userIDs
2. There is aspx Webservice (connected to mysql) in the server, which has functions like GetMessage/SendMessage
3. User from client app sends his ID, the receiver ID and a message to Webservice
4. Webservice puts a message into mysql database (with sender ID and receiver ID)
5. SignalR should send notification (e.x. senderID X sent you a message) to the specific user's client app (if he's connected at the time) and the client app then contacts webservice and returns a message from mysql.

Client app is Xamarin android project
Webservice is simple asp.net webservice

The problem is:
How to map a connected client with a userID from mysql? Hope it makes sense.

After searching through lots of examples online I'm struggling with what seems to be a fairly simple requirement.

I'm trying to extend an existing ASP.NET Application that uses Form Authentication today so that it can use OpenID Connect for authentication as well as some role information coming from the Identity Provider. In particular I'm integrating with an existing hosted Identity Provider that I do not have control over.

I'm using ASP.NET MVC with the Owin components for OpenIdConnect. Namely,

Microsoft.Owin.Security
Microsoft.Owin.Security.Cookies
Microsoft.Owin.Security.OpenIdConnect

I am successfully able to:

  1. In a web browser -- navigate to a controller method that is secured with the [Authorize] attribute
  2. The Owin components properly redirect me to the Identity Provider where I can authenticate and then and I'm redirected back to my app (NOTE: my Identity Provider requires that a redirect_uri be passed in, so I'm currently setting that as part of the OpenIdConnectAuthenticationOptions startup configuration.)
  3. When the redirect back to my app happens, I'm able to see the access_token and the id_token as part of the query string. Additionally, I've been able to use the access_token to call into the user info endpoint and properly derive information about the user using that token.

So far so good! HOWEVER.

What I'm failing to grasp and what most Owin examples I've seen don't seem to explain: what, if any, extra configuration is required to get ASP.NET to actually create an authenticated session in my application based on the redirect from the Identity Provider back to my application.

The general feeling I get from the documentation is that I should NOT have to do extra configuration within the Owin libraries -- that once I've configured the system to use cookie authentication and the OpenId Connect libraries -- that it should just work. However, this doesn't seem to be as easy as it looks. I'm guessing I'm missing something.

Some specific considerations/observations:

  1. Many examples I've found don't require the RedirectUri to be set in the OpenIdConnectAuthenticationOptions, but my Identity Provider requires this parameter to be set each time.
  2. Very few examples that I've found explain whether the controller method that fires as a result of the RedirectUri being hit should be secured with [Authorize] or left anonymous. In my testing, if I mark it as [Authorize] I get into an infinite redirect loop. If I leave it anonymous, I'm able to see the tokens in the request info but the ASP.NET Session is never created. For example, Request.IsAuthenticated is always false.
  3. As a test I've set breakpoints inside several of the OpenIdConnectAuthenticationNotifications() events and currently I'm only seeing my code break into the RedirectToIdentityProvider event, and NONE of the others seem to hit -- which leads me to believe I'm not configuring this right.
  4. Per suggestions I've found, I've set the authentication node this way in the web.config, but it doesn't seem to make a difference if I exclude this node.

    <system.web>
        <authentication mode="None" />
    </system.web>
    

To summarize:

  1. Do I need to specifically write code to handle the returning redirect from the Identity Provider to manually set up the ASP.NET Session (cookie etc.) for the given user? and
  2. If so, should this code go in the controller method that is called as a result of RedirectUri being hit, or should the code go into one of the "Notifications" events available within OpenIdConnectAuthenticationNotifications()?

Lastly, if I'm NOT supposed to be setting up the Authenticated session manually after redirect from the Identity Provider (if it's supposed to work automatically), any suggestions for common mistakes on this configuration?

For completeness:

My Owin pipeline Startup Configuration method:

public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            //no problems on these as far as I can tell
            ClientId = "client_id_string",
            ClientSecret = "client_secret_string",
            Authority = "url_to_identity_provider",
            Scope = "email name etc",

            //I'm properly redirected to this URL but not sure 
            //if I should need to create the session manually
            RedirectUri = "http://mymachine/mymvcapp/authorize",

            //this causes the redirection to come with the access_token, 
            //which is valid
            ResponseType = "token",
            SignInAsAuthenticationType = "Cookies",
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                RedirectToIdentityProvider = (context) =>
                {
                    //I'm able to break into this method
                    return Task.FromResult(0);
                },
                MessageReceived = (context) =>
                {
                    //doesn't seem to run this line
                    return Task.FromResult(0);
                },
                SecurityTokenReceived = (context) =>
                {
                    //doesn't seem to run this line
                    return Task.FromResult(0);
                },
                SecurityTokenValidated = (context) =>
                {
                    //doesn't seem to run this line
                    return Task.FromResult(0);
                },
                AuthorizationCodeReceived = (context) =>
                {
                    //doesn't seem to run this line
                    return Task.FromResult(0);
                },
                AuthenticationFailed = (context) =>
                {
                    //doesn't seem to run this line
                    return Task.FromResult(0);
                },
            },
        });
}

My secured method that properly initiates the login flow:

[Authorize]
public class HomeController : Controller
{
    //I'm sent to the login flow the first time this is hit
    public ActionResult Index()
    {
        return View();
    }
}

My method at the RedirectUri that does get called but does indicate that the ASP.NET authenticated session was created:

public class AuthorizeController : Controller
{
    // [Authorize] -- currently this Authorize attribute is turned off 
    //so the method is anonymous. 

    //If I turn that back on, I get infininte redirect loops to 
    //the Identity Provider
    public ActionResult Index()
    {
        //the incoming request to this controller method from the 
        //identity provider DOES include valid access_token and id_token 
        //(which can be used against the user info endpoint) but does not 
        //create a valid ASP.NET session for my web app

        //Request.IsAuthenticated is always false

        //should there be a manual creation of the ASP.NET 
        //session/cookie information in this controller method?

        //note: to me it would make most sense if this attribute was not
        //anonymous since it's unlikely that the Request would ever appear
        //as IsAuthenticated == true, but if you read the entire question
        //it will be clear why I'm trying this method with anonymous access

        return View();
    }
}

Thanks in advance for the help here.

I have a javascript function in main.js file as below

 $(document).ready(function(){
 {    
     callAlert()
 });
  $.fn.callAlert = function()
  {
      alert("hi");
  }

I need to call this callAlert() method on 2 occasions 1. when document is ready. Below is how I created

 $(document).ready(function(){
 {    
     callAlert() // This is not working
 });
 $.fn.callAlert = function()
  {
      alert("hi");
  }

2. on partial view ( from .cshtml)

  <script>How do I call from partial view</script>

Please note: the callAlert method is in main.js file

I just learn Asp.net.

How can one highlight in ASP.net active links (on which one is located) at the _Loayout.cshtml? I have not found possibility or example.

I just want to highlight automaticly the link "Config" if user is at this Controller + Action:

<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Config">Config</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>

Is this not possible?

Thanks a lot Karsten

I was using list box to print label but i am getting space in the top and i showing my coding here:

         -----------------------------------
          [1]: https://i.stack.imgur.com/U9rBy.png
          -------------------------
    da = New Odbc.OdbcDataAdapter(lsSql, con)
    dt = New DataTable
    da.Fill(dt)

    lb_label.UseCustomTabOffsets = True
    lb_label.CustomTabOffsets.AddRange(New Integer() {100, 100})
    lb_label.ColumnWidth = "30,0"


    reader = cmd.ExecuteReader()
    If reader.Read() Then
        i = 0
        While i < dt.Rows.Count

            ' Since we know the name of the DataTable Columns
            'rtb_label.Text += (dt.Rows(i)("folio_no").ToString() & vbNewLine & dt.Rows(i)("holder1_name").ToString() & vbNewLine & dt.Rows(i)("folio_country").ToString() & vbTab & vbNewLine)
            lb_label.Items.Add("Folio:" & vbNewLine & dt.Rows(i)("folio_no").ToString() & vbNewLine)
            lb_label.Items.Add(dt.Rows(i)("holder1_name").ToString() & vbNewLine)
            lb_label.Items.Add(dt.Rows(i)("folio_addr1").ToString() & vbNewLine)
            'lb_label.Items.Add(dt.Rows(i)("folio_addr2").ToString() & vbNewLine)
            'lb_label.Items.Add(dt.Rows(i)("folio_addr3").ToString() & vbNewLine)
            lb_label.Items.Add(dt.Rows(i)("folio_city").ToString() & vbNewLine)
            lb_label.Items.Add(dt.Rows(i)("folio_state").ToString() & "-" & dt.Rows(i)("folio_pincode").ToString())
            lb_label.Items.Add("")
            lb_label.Items.Add("")
            lb_label.Items.Add("")
            lb_label.Items.Add("")
            lb_label.Items.Add("")

            i = i + 1
            End While
            --------------

please suggest me if anybody knows and thanks in advance

I have :

<input class="datefield" value="@ViewBag.SelectedFromHour" id="TimeFrom" name="TimeFrom" type="time">

My @ViewBag.SelectedFromHour value is 5:00. But it does not display it.

I have a task to change the existing image with the new image on clicking a link called photo, it will redirect to uploadimage view page. But when I choose an image , an alert with "image uploaded successfully " occured , but it will not uploaded to the database.

controller

    public async Task<ActionResult> Photo(int id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Board board = await db.Boards.FindAsync(id);
        clsPhoto img = new clsPhoto();
        img.Id = id;

        var images = db.Boards.Where(s => s.Id == id).ToList();
        img.BoardImage = images;

        if (board == null)
        {
            return HttpNotFound();
        }
        return View(img);
    }

    [HttpPost, ActionName("UploadImageMethod")]
    public async Task<ActionResult> UploadImageMethod([Bind(Include = "Id,Name,Designation,Phone,PhotoUrl")] Board board)
    {
        if (Request.Files.Count != 0)
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                int fileSize = file.ContentLength;
                string fileName = file.FileName;
                file.SaveAs(Server.MapPath("~/BoardImages/" + fileName));

                try
                {
                    if (ModelState.IsValid)
                    {
                        Board hosw = new Board();
                        hosw.PhotoUrl = fileName;
                        hosw.Id = Convert.ToInt32(TempData["id"]);
                        db.Entry(board).State = EntityState.Modified;
                        await db.SaveChangesAsync();
                        return RedirectToAction("Index");
                    }
                }
                catch (Exception ex)
                {

                }
            }
            return Content("Success");
        }
        return Content("failed");
    }

    public ActionResult UploadImage(int id)
    {
        TempData["id"] = id;
        return View();
    }

In this controller when I click on the photo link it will move to uploadImage method and here I can choose the image , and there is a button called image upload. when I click it will move to UploadImageMethod action method and show image uploaded successfully

uploadImage view

 @model BeyondThemes.BeyondAdmin.Models.Board

@{
ViewBag.Title = "Upload Image";
Layout = null;
}

<html>
 <head>
  <title>Image Gallery</title>
  <link href="~/assets/css/beyond.min.css" rel="stylesheet" />
    <script type="text/javascript">
    window.onload = function ()
    {
        document.getElementById('imageUploadId').onsubmit = function ()
        {

            var formdata = new FormData();
            var fileInput = document.getElementById('fileInputType');
            for (i = 0; i < fileInput.files.length; i++)
            {
                formdata.append(fileInput.files[i].name, fileInput.files[i]);
            }
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/Boards/UploadImageMethod');
            xhr.send(formdata);

            xhr.onreadystatechange = function ()
            {

                if (xhr.readyState == 4 && xhr.status == 200)
                {
                    if (xhr.responseText == "Success")
                    {
                        alert("Upload image successfully.");
                        parent.jQuery.fancybox.close();
                    }
                    else
                    {
                        alert("Error occurred.! Please try again");
                    }
                }
            }
            return false;
        }
    }
</script>

</head>
<body style="background-color:#fff">
<div style="height:400px; border:1px solid;">
    <div style="width: 100%; height: 50px; border-bottom: 1px solid #808080; background-color: #66CCFF; ">
        <div style="float:right; height:30px; width:30px; margin-top:10px;
            border-left:0px solid #c8c8c8">
            <a href="javascript:parent.jQuery.fancybox.close();"
               style="color: orange; cursor: pointer; text-decoration: none;">
                <img src="../Content/fullscreenButton.png">
            </a>
        </div>
    </div>
    <div>
        <div style="margin-left:80px; float:left; width:500px;
              height:270px; border: 0px solid black;">
            <div>
                <br />
                <form id="imageUploadId">
                    <h3>Upload a picture</h3>
                    <input id="fileInputType" type="file" multiple class="fileUpload"
                           style="width:300px;"><br />
                    <p style="color: #0066FF">
                        You Can Upload a JPG, GIF, Or PNG File.
                        This example of upload image from Ajax and Image Gallery
                    </p>
                    <input type="submit" class="btn btn-success" value="Image Upload" />
                </form>
            </div>
        </div>
    </div>
    <div style="width:100%; margin-top:290px; border-bottom:1px solid #808080"></div>
    <div style="background-color: #66CCFF; height:57px; margin-top:-20px;">
        <div style="text-align:center; margin-top:20px;"><p>2014 &copy; Admin</p></div>
    </div>
</div>

class(Board)

public partial class Board
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Designation { get; set; }
    public string Phone { get; set; }
    public string PhotoUrl { get; set; }
}

this is the class. Here the problem is I am not able to change the image that was already saved in the table. Iam searching for the solution , but didnt get, can anyone please help me to get the solution.??

I am using a jquery imagezoom plugin, but the image is not displaying on zoom, i realised the javascript code cannot pick the image source because am using Url.Content to map my image and folder. Please any help on how i can work around this. Below is my code snippet

 ViewBag.ImagePath = "~/UploadedFiles/";
 string sep = "/";
<img src="@Url.Content(ViewBag.ImagePath + Model.ProductName + sep + Model.SubImage)"  data-imagezoom=" true" class="img-responsive">

var sce = $("#mainimage img").prop('src')

I have also tried setting it with javascript like this but to no avail.

var urlmain = '@Url.Content(ViewBag.ImagePath + Model.ProductName + sep + Model.MainImage)';
    var urlsub = '@Url.Content(ViewBag.ImagePath + Model.ProductName + sep + Model.SubImage)';
    var urlsubii = '@Url.Content(ViewBag.ImagePath + Model.ProductName + sep + Model.SubImageII)';
    $("#mainimage").prop('src', urlmain);  
    $("#subimage").prop('src', urlsub);
    $("#subimageii").prop('src', urlsubii);

Thanks in anticipation for your response.

I am new to Ckeditor please help.

i have put two ckeditor controls on page , one with no toolbar attribute specified and another with custom toolbar.

<CKEditor:CKEditorControl ID="CKEditorControl1" Height="300" Width="96%" runat="server"  ></CKEditor:CKEditorControl><br /><br /><CKEditor:CKEditorControl ID="CKEditorControl2" Height="300" Width="96%" runat="server"  Toolbar="Bold|Italic|Underline|JustifyLeft|JustifyCenter|JustifyRight|JustifyBlock"    ></CKEditor:CKEditorControl>

from code behind i m setting same Text value for both controls

"<table width='100%' cellpadding='0' cellspacing='0'><tbody><tr><td style='background-color: #d2ba90; color: #000000; font-size: 14px; font-family: Arial, sans-serif;padding: 5px;'> &nbsp;Case ID: <strong><font style='font-size: 18px'> IR160137 </font></strong> </td> <td align='right' style='background-color: #d2ba90; color: #000000; font-size: 12px;font-family: Arial, sans - serif; padding: 5px;'> Tested on: <strong>  1-Sep-2016 </strong></td></tr></tbody></table>"

First one works fine it show formatted html but second control didn't.

Problem is that, i don't wants to give user so many formatting options.

I able to adjust my gridview's column width but in the pdf generated the column width is different from the gridview.

<form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Font-Size="9pt" OnRowCreated="gridView_RowCreated" OnRowDataBound="gridView_DataBound">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="AssetName" ItemStyle-Width="100"/>
            <asp:BoundField DataField="AssetPurDate" HeaderText="AssetPurDate" SortExpression="AssetPurDate" ItemStyle-Width="40"/>
            <asp:BoundField DataField="Balancebf" HeaderText="Balancebf" SortExpression="AssetPurValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="Addition" HeaderText="Addition" SortExpression="AssetPurValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="Disposal" HeaderText="Disposal" SortExpression="AssetPurValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="Balancecf" HeaderText="Balancecf" SortExpression="AssetPurValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="AssetDepPercen" HeaderText="AssetDepPercen" SortExpression="AssetDepPercen" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="30"/>
            <asp:BoundField DataField="BalanceB" HeaderText="BalanceB" SortExpression="AssetDepValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="AdditionB" HeaderText="AdditionB" SortExpression="AssetDepValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="DisposalB" HeaderText="DisposalB" SortExpression="AssetDepValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="BalanceC" HeaderText="BalanceC" SortExpression="AssetDepValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="NBVnew" HeaderText="NBVnew" SortExpression="AssetDepValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
            <asp:BoundField DataField="NBVold" HeaderText="NBVold" SortExpression="AssetDepValue" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="40"/>
        </Columns>
    </asp:GridView>

This is my code behind

protected void gridView_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType == DataControlRowType.Header)
        {
            GridView DepGrid = (GridView)sender;
            GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

            TableCell HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.RowSpan = 3;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Date";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 3;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "COST";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 4;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Dep. rate";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 3;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "ACCUMULATED DEPRECIATION";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 4;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "NBV \n31.12.2016";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 3;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "NBV \n31.12.2015";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 3;
            HeaderRow.Cells.Add(HeaderCell);

            DepGrid.Controls[0].Controls.AddAt(0, HeaderRow);

            HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Balance b/f";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Addition";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Disposal";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Balance c/f";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Balance b/f";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Addition";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Disposal";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.VerticalAlign = VerticalAlign.Bottom;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "Balance c/f";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.RowSpan = 2;
            HeaderRow.Cells.Add(HeaderCell);

            DepGrid.Controls[0].Controls.AddAt(1, HeaderRow);

        }
    }

  protected void gridView_DataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[1].Visible = false;
            e.Row.Cells[2].Visible = false;
            e.Row.Cells[3].Visible = false;
            e.Row.Cells[4].Visible = false;
            e.Row.Cells[5].Visible = false;
            e.Row.Cells[6].Visible = false;
            e.Row.Cells[7].Visible = false;
            e.Row.Cells[8].Visible = false;
            e.Row.Cells[9].Visible = false;
            e.Row.Cells[10].Visible = false;
            e.Row.Cells[11].Visible = false;
            e.Row.Cells[12].Visible = false;
        }
    }

private void ExportGridToPDF()
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Report.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(new RectangleReadOnly(842, 595), 10f, 10f, 10f, 10f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
        GridView1.AllowPaging = true;           
        GridView1.DataBind();
    }

How can change the pdf column width to same with my gridview's column width

Is there any way to test the file uploading to a .Net WCF Stream using Postman?

Any Help would be appreciated. Thanks

Can any one has any idea how to resolve the below mentioned error.

Message: Exception of type 'System.Web.HttpUnhandledException' was thrown. Message: at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.memberpages_contentkeystatisticspt2_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\gateway_qa\6f1df499\46e60c88\App_Web_sxacsfc4.25.cs:line 0 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

This code opens XML file fine unless I UNCOMMENT the code to force login. Then I get:

"Error 3709:The connection cannot be used to perform this operation. It is either closed or invalid in this context."

Why can I only open anonymously?

enter code here
<%Option Explicit%>
<%Response.Buffer=True%>
<%Server.ScriptTimeOut=120%>
<!DOCTYPE html>
<!--METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.8 Library"
UUID="{2A75196C-D9EB-4129-B803-931327F72D5C}"
VERSION="2.8"
-->

<%
Dim sUserName, rsXML
Const LoadsDB="\\fs1\FileCache\EZL_GridLoads.xml"

'If sUserName="" Then
'  ' Force login if we are anonymous
'  If Request.ServerVariables("LOGON_USER") = "" Then
'    Response.Status = "401 Access Denied"
'    Response.End
'  End If
'End If

Response.Write "User=" & Request.ServerVariables("LOGON_USER") & "<br/>"

On Error Resume Next
Set rsXML=Server.CreateObject("ADODB.Recordset")
rsXML.Open LoadsDB,,,,adCmdText

if err.number then
  response.write "Error " & Err.Number & ":" & Err.Description & "<br/>"
  response.write "Opening XML file"
  response.end
else
  Response.Write "XML successfully opened!<br/>"
  Response.Write rsXML.RecordCount & " Records read.<br/>"
  rsXML.Close
end if

Set rsXML=Nothing

%>

I have an asp.net core web api application whose get and delete request arent working, i wrote the same code logic in another application and everything worked fine but now it doesnt work anymore.

My first get

[HttpGet]
public IEnumerable<People> Get()
{
    return _ontext.People.Where(a => a.Id == id).Select(a => new People()
    {
        Id = a.Id,
        FirstName = a.FirstName,
        LastName = a.LastName,
        Password = a.Password,
        EmailAddress = a.EmailAddress
    }).ToList();
}

My second get

[HttpGet("{id}")]
public IQueryable<People> get(int id)
{
    return _ontext.People.Where(a => a.Id == id).Select(a => new People()
    {
        Id = a.Id,
        FirstName = a.FirstName,
        LastName = a.LastName,
        Password = a.Password,
        EmailAddress = a.EmailAddress
    });
}

Note: My table isn't empty, but when i call those apis, all i get is []

And finally my delete

[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
    var people = new People() { Id = id };

    dbContext.Attach(people);
    dbContext.Entry(people).State = EntityState.Deleted;
    dbContext.SaveChanges();

    return Ok(people);
}

This just throws an exception with the following message when called: Unable to create or track an entity of type 'People' because it has a null primary key or alternate key value.

I'm trying to convert my integer value of hours, 0-23 into a nicely formatted one like:

15 would be represented like: 15:00
0 would be represetnted like: 00:00
23 like: 23:00

This is the code from my view:

 @foreach (var item in ViewBag.HourlyGraph)
 {
   @:{device: '@item.Hour', geekbench:@item.Sales },
 }

I'm trying to represent the @item.Hour value like I mentioned above. I've tried using interpolated string like this:

"{@item.Hour}:00"

But in my view says it's not supported since I use C# 5.0 instead of C# 6.0 ...

How could do this instead of using interpolated strings?

As per the title, is there a default focus and select behaviour following a JavaScript alert being clicked?

The reason I ask is that I have a JavaScript function validating an asp.net text box in a web forms application. I added a JavaScript alert to the function to help with debugging and the behaviour seemed to change. When I clicked on the OK button of the alert it then set the focus to the field I was validating and selected the text.

I thought it must be something in my code causing this behaviour so I commented out all the instances where I was setting focus and select, but still saw the same behaviour. As soon as I removed the alert it went back to behaving as expected and no longer selected the data in the text box.

Does this sound like it could be related to the JavaScript alert or just something odd going on in my code?

I just created a ReportViewer and went through the wizard to add a rest service and the sample report.

Everything seemed to work out and the application builds.

Where the hell do I navigate to in order to actually see the report in the browser?

It registered it's own little telerik routes and obviously the function that does that is not included in the metadata...

The documentation says nothing about the URL to use once it's been created.

I tried navigating to /api/reports and it returned a json object containing strings like XML, HTML and other things...

I feel like this is a stupid question...