i am able to see the jpeg file on my gridview but what i want is to see the image itself. here is my button code:

protected void Button1_Click(object sender, EventArgs e)
        if (FileUpload1.HasFile)
            string bname = TextBox1.Text;
            string city = DropDownList1.SelectedValue.ToString();

            string filename = Path.GetFileName(FileUpload1.FileName);
            FileUpload1.SaveAs(Server.MapPath("~/Images/") + filename);

            Execute("INSERT INTO building VALUES('" + bname + "','Binay',1, '" + filename + "')");
            Label3.Text = "sucess";

            SqlDataAdapter sda = new SqlDataAdapter("Select * from building",ConnectionString);
            DataTable dt = new DataTable();
            GridView1.DataSource = dt;
            Label3.Text = "upload image";


any suggestions will be of great help. thanks!

I am creating a control dynamically using the HtmlGenericControl method, and then trying to call that control a few lines down in my code. Obviously, because this control is not actually created yet, the code throws build errors. Is there anyway to work around this? This is the code that I am working with:

foreach(string t in equipmentTypes)
    HtmlGenericControl li = new HtmlGenericControl("li");//Create html control <li>
    //Create the correct <li> for the equipment type. Using the naming convention tableAbreviation_recordName eg: et_ATV.
    li.InnerHtml = "<div id='et_" + t +"' >" + t + "<label><input type='checkbox'></label></div><ul id='make' runat='server'>";

makes = Statements.GetMake();

foreach(string t in makes)
    HtmlGenericControl li = new HtmlGenericControl("li");//Create html control <li>
    //Create the correct <li> for the equipment type. Using the naming convention tableAbreviation_recordName eg: et_ATV.
    li.InnerHtml = "<div id='mk_" + t + "' >" + t + "<label><input type='checkbox'></label></div>";

So I am creating the <ul> with id='make'. I want to call this <ul> in the next foreach loop an append some html to it. How would I go about this?

After some additional research, I tried the Page.FindControl to find the control, but in the order the code runs/page is created, the object is not set to an instance of an object. So it looks like I may need to call the control after the page has rendered?

Hi can anyone tell me that how can I fetch lines of code from C# code. For example, I have following code in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCodeHelp
    class MultiplicationProgram
        public int Multiplication(int Firstnumber, int SecondNumber)
            int Result = (Firstnumber * SecondNumber);
            return Result;

So please tell me how can I fetch the following code from the code above and display it in a label or panel?

public int Multiplication(int Firstnumber, int SecondNumber)
    int Result = (Firstnumber * SecondNumber);
    return Result;

Can a Page_Load() method be async? I ask as if I have declared as such

protected void Page_Load()

Everything loads as it should. If I have it declared as such

protected async void Page_Load()

the Page_Load() breakpoint is not hit, nor does the catch() block get hit.

Now I am trying to set my Page_Load() method as async in order to have 3 different stored procedures execute to completion before the page is fully rendered. If I do not have my Page_Load() method as async I get this compile error:

The await operator can only be used with an async method.

My code is as such.

private DataSet ds1 = new DataSet();
private DataSet ds2 = new DataSet();
private DataSet ds3 = new DataSet();

protected async void Page_Load(object sender, EventArgs e)
 if (!IsPostBack)
    var task1 = GetStoreInfo();
    var task2 = GetSalespersonInfo();
    var task3 = GetManagerInfo();
    await System.Threading.Tasks.Task.WhenAll(task1, task2, task3);


async System.Threading.Tasks.Task<DataSet> GetStoreInfo()
  ds1 = RunStoredProcedureToReturnThisData();
  return ds1;

async System.Threading.Tasks.Task<DataSet> GetSalespersonInfo()
  ds2 = RunStoredProcedureToReturnThisData();
  return ds2;

async System.Threading.Tasks.Task<DataSet> GetManagerInfo()
  ds3 = RunStoredProcedureToReturnThisData();
  return ds3;

protected void PopulateAll()
  //Bind the different returned datasets

Can prerender.io be used in an ASP.NET 4.5 application if neither Node.js or Ruby are installed on the server?

I'm trying to send an email to multiple recipients in my project however I am getting an error: The array is returning with a value of 0 even when users have been selected. My code:

        //Creates variables for information
        StringBuilder sb = new StringBuilder();

        foreach (GridViewRow gr in TuteeListGrid.Rows)
            CheckBox cb = (CheckBox)gr.FindControl("checkUser");
            if (cb.Checked && gr.RowIndex >= 0 && gr.RowIndex < TuteeListGrid.DataKeys.Count) //Don't do the rest if the Row Index is invalid.
                mail.To.Add(new MailAddress(


Can anyone please let me know where I went wrong and let me know how I would fix it? Thanks for your help.

    cb  {Text = "" Checked = true}  
    cb.Checked  true    
    gr  {System.Web.UI.WebControls.GridViewRow} 
    gr.RowIndex 0   

I have an .NET MVC application that is using iTextSharp to create a PDF. Everything works correctly with a nice PDF on my localhost. (I did not post the code since it works on the localhost). However, when I deploy to the production server it fails with the error. Any idea of why the exact same code would fail on one but work on another?:

System.IO.IOException: The document has no pages.

My asp code like this

<asp:Repeater ID="Repeater1" runat="server" Visible="true">
            <asp:HyperLink ID="imgbtnHl" runat="server" Target="_blank"> // hyper   link btn am givem target equal to blank but it is not working/ 
      <asp:ImageButton runat="server" Width="300px"ID="imgbtnHospitalimg" ImageUrl=images/tt.png" />/while click the image i want new window not an popup/

I understand that my sample is not a good way of getting each object from a list. Here's my sample:

var getWeeks = GetWeeks();
        var startOfWeek6 = getWeeks[0].startOfWeek6;
        var endOfWeek6 = getWeeks[0].endOfWeek6;
        var startOfWeek5 = getWeeks[0].startOfWeek5;
        var endOfWeek5 = getWeeks[0].endOfWeek5;
        var startOfWeek4 = getWeeks[0].startOfWeek4;
        var endOfWeek4 = getWeeks[0].endOfWeek4;
        var startOfWeek3 = getWeeks[0].startOfWeek3;
        var endOfWeek3 = getWeeks[0].endOfWeek3;
        var startOfWeek2 = getWeeks[0].startOfWeek2;
        var endOfWeek2 = getWeeks[0].endOfWeek2;
        var startOfWeek1 = getWeeks[0].startOfWeek1;
        var endOfWeek1 = getWeeks[0].endOfWeek1;

Do you have the ideal or simplier method? Here's my sample how they're being used:

var transactionWk6 = dataSet.Tables["dataBridge"]
            .Where(a => Convert.ToDateTime(a["reportingDate"].ToString()) >= startOfWeek6 && Convert.ToDateTime(a["reportingDate"].ToString()) < endOfWeek6.AddDays(1)) 
            .GroupBy(a => 1)
            .Select(d =>
                d.Sum(a => a.Field<double?>("TranCount"))

I have a dropdownlist with autopostback and an update panel, it works correctly, but I have also other controls in my page. What I need is to control when the page is autopostback but the dropdownlist is not autopostback do something, like this:

     If is not Page.autopostback then
    'do something

else if is not MyDropdownlist.autopostback then    
    ' do something different    
    End if

I can use this:

If is not Page.autopostback then
End If

But I can´t do this:

If is not MyDropdownlist.autopostback then
End If

So how can I do this? I hope my explanation has been helpful, thanks.

tl;dr: Can get bearer token using angular from adfs, but cant authenticate on the webserver

For a new project we are implementing an api using asp.net web api 2 (.net 4.5.2) that is consumed by a javascript application (written in angular, but that does not matter). Our user accounts are stored in AD, which we would love to use.

In our older applications, using mvc, it was easy to connect everything and access claims you specified in ADFS, using js however is proving to be difficult.

Using the new endpoints in adfs 3, we can get the beaerer token using javascript (and a bit of web api):

GET https://path.to.sts/adfs/oauth2/authorize?parameters

Gives us a token that we pass on to our web api (otherwise the STS will block you due to CORS errors):

$scope.tokenRequest = {
           grant_type: "authorization_code",
           client_id: "client id thing",
           redirect_uri: "http://path.to.api/api/token",
           code: "Token from prev call"

    url: "https://kevin.local/app/test/token",
    data: $scope.tokenRequest,
    headers: {'Content-Type': 'text/json'}
    $cookies['token'] = response['access_token'];

The call is:

public async Task<IHttpActionResult> Token(OAuthResquest request)
    string accessToken = string.Empty;
    HttpClient client = new HttpClient();

    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("grant_type", request.grant_type));
    postData.Add(new KeyValuePair<string, string>("code", request.code));
    postData.Add(new KeyValuePair<string, string>("client_id", request.client_id));
    postData.Add(new KeyValuePair<string, string>("redirect_uri", request.redirect_uri));
    HttpContent content = new FormUrlEncodedContent(postData);
    var response = (await client.PostAsync(new Uri
       ("https://path.to.sts/adfs/oauth2/token"), content));

    string result = null;
    if (response.IsSuccessStatusCode)
        if (response.Content != null)
            result = (await response.Content.ReadAsStringAsync());

        obj = JsonConvert.DeserializeObject(result);
        return StatusCode(response.StatusCode);

    HttpContext.Current.Response.Cookies.Add(new HttpCookie("accessToken", result["accessToken"]));
    return Ok(obj);

This gives us a bearer token. In angular I have an interceptor that adds this to each http request, which works, because I can see it in the inspector.

Unfortunately, this is where I got stuck. I can't seem to find how to get authentication working, using adfs, given the bearer token.

I experimented with app.UseOAuthBearerToken, app.UseActiveDirectoryFederationServicesBearerAuthentication, app.UseOAuthBearerTokens(OAuthOptions) and app.UseOAuthBearerAuthentication, but I keep getting 401's on api calls decorated with [Authorize], let alone access the claims we specified in adfs.


I would like to achieve a hybrid Windows & Forms authentication for our ASP.NET web applications. I’ve seen details of several ways to do this, some on Stackoverflow, from simple re-directs to an OWIN solution which looks pretty fearsome and I honestly can’t follow what’s going on! I could really use some architecture advice please!

Currently, we have several web applications (all under one root domain) all using forms authentication. Users are re-directed to a single authentication application which verifies their credentials and checks that they have been granted access to the application they want to use. The web server is public facing, being hosted in a DMZ in an external data centre.

I would like users who are logged on to our corporate AD to be able to access these applications without having to go through forms authentication. Whereas non-corporate users such as customers, or corporate users who are not logged on to the AD (e.g. employee using a computer at a customer’s premises) are sent to a form for authentication.

Reviewing what I have read about so far:

  • Simple redirect.

Approaches such as this - https://msdn.microsoft.com/en-us/library/ms972958.aspx and http://mvolo.com/iis-70-twolevel-authentication-with-forms-authentication-and-windows-authentication/ - still use forms authentication. But the logon URL target is an aspx page which is secured using Windows authentication. Domain authenticated users are able to access this page, so the Windows username can be lifted and used to create a normal forms ticket. Non-domain users will get a 401 permission denied error with IIS being configured to redirect on such errors to the normal authentication form.

This seems like a simple approach but I guess (a) it won’t work for me because the web server is in a DMZ which does not have access to our AD and (b) most references to this technique seem quite old, so I guess it’s an outdated approach.

  • Windows Identity Foundation.

I quite like this approach. I’ve been through some material on Pluralsight, but our exact requirement is not covered. We do have AD FS 2.0 (soon to be updated to 3.0 I understand). Would it be possible to have domain users directed to AD FS, acting as a STS, to obtain a token, but non-domain users directed to a simple STS in the DMZ for username/password authentication? From the diagrams I’ve seen it appears that WIF can trust more than one STS, but can a user be automatically directed to a particular STS depending on, for example, IP address or another way to discriminate between internal/external access?

Also, I’ve seen quite a few Powerpoints around this topic, but could someone point me in the direction of some concrete examples, as I don’t seem to be able to find any.

  • OWIN/Katana.

This would seem to be the favoured way now, with new ASP.NET projects getting this added from the start. Again, I watched some Pluralsight videos. I followed the idea of a request pipeline and middleware (I’ve used BizTalk a lot so the concept is familiar). But I lost the plot when it got to authentication middleware. I’ll have to re-visit the material. I did find this code which says it does what I want - https://github.com/MohammadYounes/MVC5-MixedAuth/tree/WindowsFirst - but to be honest it was beyond my understanding.

Could someone please let me know whether Katana could be used to achieve what I want and whether there is a simpler method than used in this sample code?

So, overall, I guess I could use some advice about which of these approaches I should use. Or is there a better way? Thanks in advance.

i wrote Javascript that copies the data from textbox to the clipboard:


<asp:TextBox ID="contNoTxtBox" runat="server" Width="182px" style="height: 22px"></asp:TextBox>


function CopyToClipBoard()
    var text = document.getElementById('contNoTxtBox').innerHTML;                       
    window.clipboardData.setData('Text', text);                       

and i call it in HTML button the following way:

<input id="CopyButton" type="button" value="Copy" onclick="CopyToClipBoard()" /><br />

However i get the following error:

Uncaught TypeError: Cannot read property 'setData' of undefined

Why am i getting this type pf error?

This method works:

IIS > Sites > Add WebSite...


This doesn't:

IIS > Sites > SomeWebSite > Add Application...


My WebApiConfig:

public static void Register(HttpConfiguration config)

    config.Routes.MapHttpRoute("DefaultApi", "api/{controller}");


    var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
    jsonSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;


public class ValuesController : ApiController
    [Route(""), HttpGet]
    public IHttpActionResult Get()
        return Ok("Is working");

I don't know the error reason, I've did a lot of research but I can't find what is causing this.

By the way, in the development environment the two ways works.

http://localhost:<someport>/api/values and


The server has the IIS 8.5.

The development environment has the IIS 10.

Any thoughts?

I need to create a quiz like website that is similar to hot potatoes which is in java language. I was wondering if anyone knows anything similar that can be done in visual studios using asp.net c#. or if there is anyways to use hot potatoes for c#? please i would really appreciate any help

I have a dropdownlist that is working just fine , but when I have add a CKeditor ( ckeditor-standard 4.5.7) to handel EditorFor helper i'm getting this error "The ViewData item that has the key 'OccupationId' is of type 'System.Int32' but must be of type 'IEnumerable'. ",removing the Ckeditor solv this error but I do need it , relevant code (from view)

    <div class="form-group">
        @Html.LabelFor(model => model.rev.ReviewBody, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.rev.ReviewBody, new { htmlAttributes = new { @class = "form-control", @id = "RevBEditor" } })
            @Html.ValidationMessageFor(model => model.rev.ReviewBody, "", new { @class = "text-danger" })
    </div>  <div class="form-group">
            @Html.LabelFor(model => model.sub.Occupation.OccupationDecription, "Occupation", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("OccupationId", null, htmlAttributes: new { @class = "" })
                @Html.ValidationMessageFor(model => model.OccupationId, "", new { @class = "text-danger" })
        </div><script src="~/Scripts/ckeditor/ckeditor.js"></script> 

im trying to add values up and submit to a label once a radio button is selected. Its not doing it at all.

any ideas?


<asp:Label ID="CountTest" runat="server" Text="CountTester"></asp:Label>
 <asp:RadioButton ID="RadioButton1" runat="server" />


        int Total = 2 ;

        CountTest.Text = Convert.ToString(Total);

        if (RadioButton1.Checked == true)
            Total = Total + 1;

        else if (radio2.Checked == true)
            Total = 0;

Dynamically how can i create html table or asp table, i tried with below code,but it's not working.

 Table tb = new Table();
   TableRow rowNew = new TableRow();
                                for (int j = 0; j < cols; j++)
                                    TableCell cellNew = new TableCell();
                                    Label lblNew = new Label();

here i want to create more then one html table using loop.how can i do this?

When I click in a textbox from a grid I don't want the event SelectedIndexChanged to be fired? How can I do that?

I don't know what type of data is this [['jan',100],['feb',100]] its use in script and I want to make my data look exact same way but from C#.

I want to use the data for making statistic canvas for my Web Application.


    function GetRowValue(val) {

         window.opener.document.getElementById("UniqueKeyField").value = val; 


========================================================================= window.opener.__doPostBack error and Even if i have window.Close() function Popup window is not closing. `