I have this scenario, I am working on where a notification message needs to be sent to all workstations in my company. We have a client service which handles Desktop Notifications and it is a very simple WebApi.

Question/ Requirement How do I both Asynchronously and in Parallel send out request to all these machines from server/ASP.Net web app, and capture its response to custom log file ?

Many machines may be switched off at the time of notification is sent out or dns might not be able to resolve as the machine could have been decommissioned.

The request/response cycle to the code which is currently being prototyped needs to a non-blocking one. So that the user does not have to wait for response from all these machines.

My Homework : I understand Asynchronous operations are better suited for IO bound operations, however the number of machines are so many that makes me feel parallel and async together, might suit this situation better.

I have set ServicePointManager.DefaultConnectionLimit = 10000

HttpClient with constructor with dispose option to false has been passed. See Below code - Factory Class.

HttpClient class in framework is designed for reuse however, from what I understand some properties not be changed like base address. Source : HttpClient - This instance has already started

I am using Request/Response specific ID (Correlation ID) to make sure all async and parallel operations right to the same folder for a given request.

TaskCanceledException catch block never gets hit !!

Timeout has been extended to 30 seconds which I am quite sure is more than enough.

Prototype Code :

public class HttpClientFactory  : IHttpClientFactory
    {
        public void CreateClient(string baseUrl, Action<HttpClient> methodToExecute)
        {
            using (var handler = new HttpClientHandler())
            {
                handler.AllowAutoRedirect = true;
                using (var client = new HttpClient(handler, false))
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.Timeout = TimeSpan.FromSeconds(30);
                    methodToExecute(client);
                }
            }
        }
   }

Where IHttpClientFactory is Transient (IoC)

workstationUrls.ForEach(baseUrl =>
            {
                _httpClientFactory.CreateClient(baseUrl, async (client) =>
                {
                    await client.PostAsync(resourceUrl, content).ContinueWith(t =>
                    {
                        try
                        {
                            var response = t.Result;

                            var workstationResponse = new WorkstationResponse
                            {
                                StatusCode = (int)response.StatusCode,
                                Response = response.Content.ReadAsStringAsync().Result
                            };

                            workstationResponse.IsSuccess
                                = workstationResponse.StatusCode >= 200 &&
                                  workstationResponse.StatusCode <= 299
                                    ? true
                                    : false;

                            var docContent = JsonConvert.SerializeObject(workstationResponse);
                            if (workstationResponse.IsSuccess)
                            {
                                // Write workstation log
                                File.WriteAllText(path
                                                  + "\\Bulk Notifications\\"
                                                  + userFolder + "\\Success\\"
                                                  + GetWorkstationNameFromUrl(baseUrl)
                                                  + GetUniqueTimeStampForFileNames()
                                                  + workstationResponse.IsSuccess + ".txt",
                                    docContent);
                            }
                            else
                            {
                                // Write workstation log
                                File.WriteAllText(path
                                                  + "\\Bulk Notifications\\"
                                                  + userFolder + "\\Fail\\"
                                                  + GetWorkstationNameFromUrl(baseUrl)
                                                  + GetUniqueTimeStampForFileNames()
                                                  + workstationResponse.IsSuccess + ".txt",
                                    docContent);
                            }

                        }
                        catch (TaskCanceledException exe)
                        {

                        }
                        catch (Exception ex)
                        {

                            var workstationResponse = new WorkstationResponse
                            {
                                Exception = ex,
                                IsSuccess = false
                            };
                            var docContent = JsonConvert.SerializeObject(workstationResponse);
                            // Write workstation log
                            File.WriteAllText(path
                                              + "\\Bulk Notifications\\"
                                              + userFolder + "\\Fail\\"
                                              + GetWorkstationNameFromUrl(baseUrl) + " "
                                              + GetUniqueTimeStampForFileNames() + " "
                                              + workstationResponse.IsSuccess + ".txt", docContent);
                        }
                    });
                });
            }); 

Problem With Prototype Code : I get these errors in Exception messages and StackTrace does not seem to be helpful

  • "A task was canceled"
  • "Cannot access a disposed object.Object name: 'System.Net.Http.StringContent'"

Please Advice. And thanks a lot in advance for your opinion.

for some reason DropDownListFor doesnt work for me and i cant find a reason why.

My game model

    public class Game
{
    public virtual int GameId { get; set; }
    public virtual string Name { get; set; }
    public virtual Studio Studio { get; set; }
    public virtual Genre Genre { get; set; }
    public virtual List<Level> Levels { get; set; }
}

My controller:

        [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult MyEditEdit([Bind(Include = "GameId,Name,Genre")] Game game)
    {

        if(ModelState.IsValid)
        {
            db.Entry(game).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("MyEdit");
        }
        return View();
    }

    //get
    public ActionResult MyEditEdit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Game game= db.Games.Single(g => g.GameId == id);
        if(game == null)
        {
            return HttpNotFound();
        }
        object genre;
        if(game.Genre == null)
        {
            genre= 0;
        }
        else
        {
            genre= genre;
        }
        ViewBag.GenreList = new SelectList(db.Genres,"GenreId", "name", genre);


        return View(game);
    }

my view

@using GameStore.Controllers
@using GameStore.Models
@model GameStore.Models.Game

@using (Html.BeginForm())
{
        <div class="form-group">
            @Html.LabelFor(model => model.Genre, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(m=>m.Genre, ViewBag.GenreList, "GenreId", "name")
                @Html.ValidationMessageFor(model => model.Genre, "", new { @class = "text-danger" })
            </div>
        </div>
}

View doesnt even load, i get the error from topic name. When i write DropDownListFor lambda code intelisense doesnt work for m=>m.Genre. I have no idea what im doing wrong and im lost, googled it and didint find anything.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace XEx04Quotation
{
    public partial class Confirm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;

            if (Session["SalesPrice"] != null)
            {
                lblSalesPrice.Text = Convert.ToDecimal(Session["SalesPrice"]).ToString("c");
            }

            if(Session["Discount"]!= null) 
            {
                lblDiscountAmount.Text = Convert.ToDecimal(Session["Discount"]).ToString("c");
            }

            if(Session["TotalPrice"] != null)
            {
                lblTotalPrice.Text = Convert.ToDecimal(Session["TotalPrice"]).ToString("c");
            }
        }
    }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Confirm.aspx.cs" Inherits="XEx04Quotation.Confirm" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Confirm quotation</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="Scripts/jquery-1.9.1.min.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/site.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server" class="form-horizontal">

        <main class="container">

            <h1 class="jumbotron">Quotation confirmation</h1>

            <div class="form-group">
                <label class="col-sm-3 control-label">Sales price</label>
                <asp:Label ID="lblSalesPrice" runat="server" CssClass="col-sm-3 bold"></asp:Label>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">Discount amount</label>
                <asp:Label ID="lblDiscountAmount" runat="server" CssClass="col-sm-3 bold"></asp:Label>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">Total price</label>
                <asp:Label ID="lblTotalPrice" runat="server" CssClass="col-sm-3 bold"></asp:Label>
            </div> 

            <div class="row">
                <h3 class="col-sm-offset-2 col-sm-10">Send confirmation to</h3>
            </div>
            
            <div class="form-group">
                <label class="col-sm-3 control-label">Name</label>
                <div class="col-sm-3">
                    <asp:TextBox ID="txtName" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="col-sm-6">
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" 
                        Display="Dynamic" ErrorMessage="Required" CssClass="text-danger"></asp:RequiredFieldValidator>
                </div>  
            </div>  
            
            <div class="form-group">
                <label class="col-sm-3 control-label">Email address</label>
                <div class="col-sm-3">
                    <asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="col-sm-6">
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtEmail" 
                        Display="Dynamic" ErrorMessage="Required" CssClass="text-danger"></asp:RequiredFieldValidator>
                </div>  
            </div>  

            <%-- Quotation and Return buttons --%>
            <div class="form-group">
                <div class="col-sm-offset-3 col-sm-9">
                    <%-- buttons go here --%>
                    <asp:Button ID="Button1" runat="server" Text="Send Quotation"  CssClass="btn btn-primary"/>
                    <asp:Button ID="Button2" runat="server" Text="Return" CssClass="btn btn-primary" PostBackUrl="~/Default.aspx" CausesValidation="false"/>
                </div>
            </div> 
            
            <%-- message label --%>
            <div class="form-group">
                <div class="col-sm-offset-1 col-sm-11">
                    <%-- message label goes here --%>
                    <asp:Label ID="lblmessage" runat="server" Text="Click the Send Quotation button to send the quotation via email" CssClass="text-info"></asp:Label>
                </div>
            </div>

        </main>

    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace XEx04Quotation
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
        }

        protected void btnCalculate_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                decimal salesPrice = Convert.ToDecimal(txtSalesPrice.Text);

                // save the salesPrice into a session state variable 
                Session["SalesPrice"] = salesPrice;


                decimal discountPercent = Convert.ToDecimal(txtDiscountPercent.Text) / 100;

    
                decimal discountAmount = salesPrice * discountPercent;

                // save the discountAmount into a session state variable
                Session["Discount"] = discountAmount;

                
                decimal totalPrice = salesPrice - discountAmount;

                // save the totalPrice into a session state variable

                Session["TotalPrice"] = totalPrice;

                lblDiscountAmount.Text = discountAmount.ToString("c");
                lblTotalPrice.Text = totalPrice.ToString("c");
            }   
        }

        protected void Button1_Confirm(object sender, EventArgs e)
        {
             if(Session["SalesPrice"] != null)
            {
                Response.Redirect("Confirm.aspx");
            }
            else 
            {
                lblmessage2.Text = "Click the Calculate button before you click confirm";
            }
            


        }
    }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="XEx04Quotation.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Price quotation</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="Scripts/jquery-1.9.1.min.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/site.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server" class="form-horizontal">

        <main class="container">

            <h1 class="jumbotron">Price quotation</h1>

            <div class="form-group">
                <label class="col-sm-3 control-label">Sales price</label>
                <div class="col-sm-3">
                    <asp:TextBox ID="txtSalesPrice" runat="server" CssClass="form-control bold">100</asp:TextBox>
                </div>
                <div class="col-sm-6">
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSalesPrice" 
                        Display="Dynamic" ErrorMessage="Required" CssClass="text-danger"></asp:RequiredFieldValidator>
                    <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtSalesPrice" 
                        Display="Dynamic" ErrorMessage="Must be from 10 to 1000" CssClass="text-danger" 
                        MaximumValue="1000" MinimumValue="10" Type="Double"></asp:RangeValidator>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">Discount percent</label>
                <div class="col-sm-3">
                    <asp:TextBox ID="txtDiscountPercent" runat="server" CssClass="form-control">20</asp:TextBox>
                </div>
                <div class="col-sm-6">
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtDiscountPercent" 
                        Display="Dynamic" ErrorMessage="Required" CssClass="text-danger"></asp:RequiredFieldValidator>
                    <asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="txtDiscountPercent" Display="Dynamic" 
                        ErrorMessage="Must be from 10 to 50" CssClass="text-danger"
                        MaximumValue="50" MinimumValue="10" Type="Double"></asp:RangeValidator>
                </div>  
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">Discount amount</label>
                <asp:Label ID="lblDiscountAmount" runat="server" CssClass="col-sm-3 bold"></asp:Label>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">Total price</label>
                <asp:Label ID="lblTotalPrice" runat="server" CssClass="col-sm-3 bold"></asp:Label>
            </div> 

            <%-- Calculate and Confirm buttons --%>
            <div class="form-group">
                <div class="col-sm-offset-3 col-sm-9">
                    <asp:Button ID="btnCalculate" runat="server" Text="Calculate"
                         CssClass="btn btn-primary" OnClick="btnCalculate_Click" />
                    <%-- confirm button goes here --%>
                    <asp:Button ID="Button1" runat="server" Text="Confirm"  CssClass="btn btn-primary" OnClick="Button1_Confirm"/>
                </div>
            </div> 
            
            <%-- message label --%>
            <div class="form-group">
                <div class="col-sm-offset-1 col-sm-11">
                    <%-- message label goes here --%>
                    <asp:Label ID="lblmessage" runat="server" Text="Enter price and discount amount and click calculate" CssClass="text-info"></asp:Label>
                </div>
                <div class="col-sm-offset-1 col-sm-11">
                  <asp:Label ID="lblmessage2" runat="server" CssClass="text-info"></asp:Label>
                </div>
            </div>   

        </main>

    </form>
</body>
</html>

Hello Everyone,

I am building multi-web application pages using the Default.aspx, Default.aspx.cs and Confirm.aspx and Confirm.aspx.cs. The problem that I am having is that when I click "Confirm" before clicking "Calculate," the event handler displays the "Click the Calculate button before the confirm" at the bottom of the page. It does that even if the Calculate button is clicked before the Confirm and also displays again when I reload the page. How can I get this to only display if the session state value of SalesPrice is null? Otherwise, it will redirect to the confirm page. Here is all aspx files and code behind files below:

I have a matrix int with 10 numbers, and I want to generate numbers randomly every 3 seconds. For example when run program random show number 2, wait 3 seconds show 5, wait 3 seconds show 10.... but I don't know how to add interval to generate

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Random rnd = new Random();
rnd.Next(1, numbers.Length);

I have this rewrite rule:

<rule name="rentals by proptype+state+city+street test" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{UNENCODED_URL}" pattern="^/([a-zA-Z0-9\-+]+)/rent/province/([a-zA-Z\-+]+)/street/([a-zA-Z0-9%\-+]+)/([0-9a-zA-Z%\-+']+)$" />
  </conditions>
  <action type="Rewrite" url="search_new.aspx?proptype={C:1}&amp;province={C:2}&amp;city={C:3}&amp;street={C:4}" appendQueryString="true" />
</rule>

I also tried:

<rule name="rentals by proptype+state+city+street test" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{UNENCODED_URL}" pattern="^/([a-zA-Z0-9\-+]+)/rent/province/([a-zA-Z\-+]+)/street/([a-zA-Z0-9%\-+]+)/([0-9a-zA-Z%\-+']+)$" />
    <add input="{QUERY_STRING}" pattern=".*" />
  </conditions>
  <action type="Rewrite" url="search_new.aspx?proptype={C:1}&amp;province={C:2}&amp;city={C:3}&amp;street={C:4}" appendQueryString="true" />
</rule>

This URL works: http://www.example.com/apartment/rent/province/texas/street/houston/mystreet
But when I add query string parameters, the URL throws a 404: http://www.example.com/apartment/rent/province/texas/street/houston/mystreet?rooms=3&pricemin=2500

I already checked here:
IIS URL Rewrite not working with query string
https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
https://msdn.microsoft.com/en-us/library/ms972974.aspx

It seems I have to use a QUERY_STRING server variable. I actually just want to append the query string parameters, without having to write a special mapping for each parameter. I thought I could solve this through the appendQueryString="true" property, but that apparently doesn't work.

How can I make sure my rewrite rule works also with query string parameters?

I have an UpdatePanel:

<asp:UpdatePanel runat="server" ID="panelFatt">
<ContentTemplate>

    <div class="row" runat="server" id="divCFPIva">
        <div class="col-md-6">
            <div class="form-group">
                <label for="txtCF">Codice Fiscale</label>
                <asp:TextBox runat="server" ID="txtCF" type="text" MaxLength="16" class="form-control" />
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label for="txtPIVA">Partita IVA</label>
                <asp:TextBox runat="server" ID="txtPIVA" type="text" MaxLength="11" class="form-control" />
            </div>
        </div>
        <div class="col-md-12">
            <span class="help-inline hidden lblerror" runat="server" id="lblErrorCFPIva"></span>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="form-group" runat="server" id="divEmail">
                <label for="txtEmail" class="control-label">Email*</label>
                <div class="controls">
                    <asp:TextBox runat="server" TextMode="Email" type="text" ID="txtEmail" class="form-control" />
                    <span class="help-inline hidden lblerror" runat="server" id="lblErrorEmail"></span>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group" runat="server" id="divTelefono">
                <label for="txtTelefono" class="control-label">Recapito Telefonico*</label>
                <div class="controls">
                    <asp:TextBox runat="server" ID="txtTelefono" type="text" TextMode="Phone" class="form-control" />
                    <span class="help-inline hidden lblerror" runat="server" id="lblErrorTelefono"></span>
                </div>
            </div>
        </div>
    </div>
    <!-- /Row -->
    <div class="form-group">
        <asp:RadioButton runat="server" ID="radioScegliIndirizziFatt" Text="&nbsp;Scegli tra uno dei tuoi indirizzi" AutoPostBack="true" OnCheckedChanged="radioScegliIndirizziFatt_CheckedChanged" Checked="true" GroupName="radioIndirizziFatt" />
        <div class="form-group" runat="server" id="divScegliIndirizzoFatt">
            <asp:DropDownList runat="server" ID="ddlIndirizziFatt" class="form-control"></asp:DropDownList>
            <span class="help-inline hidden lblerror" runat="server" id="lblErrorScegliIndirizziFatt"></span>
        </div>
        <br />
        <asp:RadioButton runat="server" ID="radioNuovoIndirizzoFatt" Text="&nbsp;Inserisci un nuovo Indirizzo" AutoPostBack="true" OnCheckedChanged="radioNuovoIndirizzoFatt_CheckedChanged" GroupName="radioIndirizziFatt" />

        <div class="form-group" runat="server" id="divNomeFatt">
            <label for="txtNomeFatt" class="control-label">Nome o Ragione Sociale*</label>
            <div class="controls">
                <asp:TextBox runat="server" ID="txtNomeFatt" type="text" class="form-control" />
                <span class="help-inline hidden lblerror" runat="server" id="lblErrorNomeFatt"></span>
            </div>
        </div>
        <div class="form-group" runat="server" id="divIndirizzoFatt">
            <label for="txtIndirizzoFatt" class="control-label">Indirizzo*</label>
            <div class="controls">
                <asp:TextBox runat="server" ID="txtIndirizzoFatt" type="text" class="form-control" />
                <span class="help-inline hidden lblerror" runat="server" id="lblErrorIndirizzoFatt"></span>
            </div>
        </div>
        <div class="row">
            <div class="col-md-5">
                <div class="form-group" runat="server" id="divStatoFatt">
                    <label for="ddlStatoFatt" class="control-label">Stato</label>
                    <div class="controls">
                        <asp:DropDownList runat="server" ID="ddlStatoFatt" OnSelectedIndexChanged="ddlStatoFatt_SelectedIndexChanged" class="form-control" AutoPostBack="true" />
                    </div>
                </div>
            </div>
            <div class="col-md-7">
                <div class="form-group" runat="server" id="divProvinciaFatt" visible="false">
                    <label runat="server" id="lblProvinciaFatt" for="ddlProvinciaFatt" class="control-label">Provincia</label>
                    <div class="controls">
                        <asp:DropDownList runat="server" ID="ddlProvinciaFatt" class="form-control" OnSelectedIndexChanged="ddlProvinciaFatt_SelectedIndexChanged" AutoPostBack="true" />
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-8" runat="server" id="divCittaFatt">
                <div class="form-group">
                    <label runat="server" id="lblCittaFatt" for="txtCittaFatt" class="control-label">Città*</label>
                    <div class="form-group" runat="server" id="divDDLFatt" visible="false">
                        <asp:DropDownList runat="server" ID="ddlCittaFatt" class="form-control" OnSelectedIndexChanged="ddlCittaFatt_SelectedIndexChanged" AutoPostBack="true" />
                    </div>
                    <br />
                    <div class="form-group" runat="server" id="divTXTFatt" visible="false">
                        <asp:TextBox runat="server" ID="txtCittaFatt" type="text" class="form-control" />
                    </div>
                    <span class="help-inline hidden lblerror" runat="server" id="lblErrorCittaFatt"></span>
                </div>
            </div>
            <div class="col-md-4" runat="server" id="divCAPFatt">
                <div class="form-group">
                    <label for="txtCAPFatt" class="control-label">CAP*</label>
                    <div class="controls">
                        <asp:TextBox runat="server" ID="txtCapFatt" type="text" class="form-control" />
                        <span class="help-inline hidden lblerror" runat="server" id="lblErrorCAPFatt"></span>
                    </div>
                </div>
            </div>
        </div>

    </div>
</ContentTemplate>
</asp:UpdatePanel>

And I'm trying to fire an UpdateProgress that I would like show loading image at every post back of the controls inside the UpdatePanel.

<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="panelFatt">
<ProgressTemplate>
    <div class="modal">
        <div class="center">
            <img alt="" src="http://i.stack.imgur.com/FhHRx.gif" />
        </div>
    </div>
</ProgressTemplate>
</asp:UpdateProgress>

This is not working at all. I saw on the Internet that someone associates a client method with the click of a button in the Update Panel. But I should do it for all the controls that make a post back within my update panel.

Is there a way to make it work?

I'm trying to use Keycloak as a Single Sign On server for more than one ASP.Net apps. I found a library on Github by called KeycloakOwinAuthentication and I cloned the sample code provided within twice to use as two different applications.

I configured 2 apps (App1 and App2) within the same Realm in Keycloak, created the test user with all roles and tried to log in.

Expected Behaviour: Log in from app one, refresh App2 and you're automatically logged in

Actual result: Log in from App one, refresh app 2 and get "Server Error in '/' Application. If I log out from App1 and try to refresh App2, it works back just fine!

My 2 sample apps can be found here

Is there a specefic configuration that I have missed? I used my testing Realm as well as a working Realm with 3 different apps (not Asp) but I failed to be logged in at all clients. I was using the same Browser with two tabs to ensure that all cookies are accessible...

Error Text:

Server Error in '/' Application.
IDX10214: Audience validation failed. Audiences: 'App1'. Did not match:  validationParameters.ValidAudience: 'null' or validationParameters.ValidAudiences: 'null, App2'
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: IDX10214: Audience validation failed. Audiences: 'App1'. Did not match:  validationParameters.ValidAudience: 'null' or validationParameters.ValidAudiences: 'null, App2'
Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 

Good day, im have a little problem. I try to save value from three dropdownlist, but it doesnt work.

My HttpGet

 [HttpGet]
    public ActionResult Create()
    {
        Produkt_Typ_Rohstoff_Indikator viewModel = new Produkt_Typ_Rohstoff_Indikator
        {
            _Typ_Id = _db.ProduktTyps.ToList(),
            _LIndikator = _db.Umweltindikators.ToList(),
            _Rohstoffe = _db.Rohstoffes.ToList()
        };
        return View(viewModel);
    }

This is how I get my data from database and send it to the view. It works well.

In my View:

@Html.AntiForgeryToken()
@Html.DropDownListFor(model => model._Typ_Id, new SelectList(Model._Typ_Id, "Id","Name", "Typ"), new {id="selectTyp"})
@if (Model._Rohstoffe.Count != 0)
{
    foreach (var elements in Model._Rohstoffe)
          {
             listElements.Add(new SelectListItem {Value = elements.Name , Text = elements.Name});
          }
}
@Html.DropDownListFor(model => model._Typ_Id, listElements, new {id="selectRohstoff"})
@if(Model != null)
{
    foreach (var elements in Model._LIndikator)
    {
        selectListUmweltIndikator.Add(new SelectListItem {Value = elements.Name , Text = elements.Name});
    }
}
@Html.DropDownListFor(model => model._LIndikator, selectListUmweltIndikator,  new{id= "selectIndi" }) 
<input id="btnErstelen" type="submit" value="Eingabe speichern" class="btn btn-default"/>

And this is how my Model look likes:

public class Produkt_Typ_Rohstoff_Indikator
{
    public List<ProduktTyp> _Typ_Id { get; set; }
    public Produkt _Produkt { get; set; }
    public List<Rohstoffe> _Rohstoffe { get; set; }
    public Rohstoff _Rohstoff { get; set; }
    public List<Umweltindikator> _LIndikator { get; set; }
    public Umweltindikator _Indikator { get; set; }
    public EndOfLifeData _EndOfLifeData { get; set; }
    public Umweltindikatorwert _Umweltindikatorwert { get; set; }
}

This is how my HttpPost look likes:

[HttpPost,ActionName("Create")]
    [ValidateAntiForgeryToken]
    public ActionResult CreateConfirmed(Produkt_Typ_Rohstoff_Indikator _produktDetails)
    {
        try
        {
            if (ModelState.IsValid)
            {
                ...

                _db.Produkts.Add(_produktDetails._Produkt);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DbEntityValidationException dbEx)
        {
            ....
        }
        return HttpNotFound();
    }

The problem is that the httpPost function dont get the selectedvalues of the three dropdownlist

Have somebody any suggestion?

In the HTML below code works fine.

<html>
<head>
<body>
<h1>[http://www.smmotors.org][1]</h1>       

<form name="Redirect_to_NetConnect" method="post"  action="http://103.25.136.125/KPALServer/NetConnect.aspx"> 

<input type="hidden" name="Merchant_ID" value="170900010400235"/>
<input type="hidden" name="Order_No" value="1321"/>
<input type="hidden" name="Order_Amount" value="900.00"/> 
<input type="hidden" name="Date" value="11/09/2017"/>
<input type="hidden" name="Time" value="21:00:00"/>
<input type="hidden" name="CheckSum" value="6217bd46945786a8ab864943e615f2aa"/>
<input type="hidden" name="Transaction_Desc" value="Shop From SM Motors"/>

<input value="try now" type="submit">


</form>
</body>
</head>
</html>

I want to show the return page in the payment plugin (Controllers>HomeControllers.cs)

public void NetConnect()
        {
            try
            {

        HttpClient client = new HttpClient();
                var values = new List<KeyValuePair<string, string>>();
                values.Add(new KeyValuePair<string, string>("Merchant_ID", "170900010400235"));
                values.Add(new KeyValuePair<string, string>("Order_NO", "1321"));
                values.Add(new KeyValuePair<string, string>("Order_Amount", "900.00"));
                //values.Add(new KeyValuePair<string, string>("Date", DateTime.Now.ToString("dd/MM/yyyy")));
                //values.Add(new KeyValuePair<string, string>("Time", DateTime.Now.ToString("HH:mm:ss")));
                values.Add(new KeyValuePair<string, string>("Date", "11/09/2017"));
                values.Add(new KeyValuePair<string, string>("Time", "21:00:00"));

                values.Add(new KeyValuePair<string, string>("CheckSum", checksum));
                values.Add(new KeyValuePair<string, string>("Transaction_Desc", "Shop From SM Motors"));



                var content = new FormUrlEncodedContent(values);

                var response = client.PostAsync("http://103.25.136.125/KPALServer/NetConnect.aspx", content).Result;
                var responseString =  response.Content.ReadAsStringAsync();

                var responseString1 = client.GetStringAsync("http://103.25.136.125/KPALServer/NetConnect.aspx");


    }
            catch (Exception)
            {
                throw new Exception();
            }

        }

I Post Data To A Specific URL & Wants To Shows The Return Page.

In return upper code shows blank page. Please guide how shows the return page.

I am using Entity Framework in my Application.

I am publishing application for first time to somee.com But I have the problem with the connection string.

My connection string in web.config

  <connectionStrings>
    <add name="StoreDBContext" connectionString="metadata=res://*/Models.StoreModel.csdl|res://*/Models.StoreModel.ssdl|res://*/Models.StoreModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\StoreDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="StoreDB" connectionString="metadata=res://*/Models.StoreModel.csdl|res://*/Models.StoreModel.ssdl|res://*/Models.StoreModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\StoreDB.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

and by database connection string on somee database is :

workstation id=storebd.mssql.somee.com;packet size=4096;user id=****;pwd=****;data source=storebd.mssql.somee.com;persist security info=False;initial catalog=storebd

How should I format connection string in web.config file according to database connection provided by some.

Is it possible to scan document directly via code using leadtooks SDK? I couldn't find any example code in leadtools site

In sample code, we can scan but via interface such as interface to select sanner and then have to press scan button. Can we achieve this directly via code without any interface

Trying out ASP.NEt Core Razor (fairly new to MVC). What is the simplest way to go to a another .cshtml Razor page using an onclick event (see question marks in code below)?

I understand that in MVC you can’t link directly to a view (it is the controller's responsibility to determine what is returned to the user) but am unsure how this works in .NET Core 2.0 Razor which does not require a separate controller file.

Excerpt is from my index.cshtml file in the Pages directory.

<text class="HomeNavText" x="36" y="157">Maps</text>
<rect class="HomeNavRect" width="65" height="65" 
    onclick="?????" 
    style="fill:rgb(000,000,000); fill-opacity: 0.3;" 
    transform="translate(11,153) rotate(-45)"> 
</rect>

I want the onclick event to link to a page called "test.cshtml" in a subdirectory I created (Pages/maps). The Core 2.0 Razor template links to other .cshtml files using the "asp-page=''" helper within an anchor tag. However, I cannot get this helper to work within the onclick context. Thanks.

I'm an extreme newbie. Please bear with me.

I'm trying to populate a GridView with multiple resultsets. I'm using a DataSet with mulitple DataTables. This code has only 2 DataTables, but I will need to use more than 5 or maybe 10.

ASP.NET 4.5.1 Web Forms w/ MSSQL

Method

public DataSet GvTest()
{
    using (SqlConnection conn = new SqlConnection(strConn))
    {
        conn.Open();

        SqlCommand cmd = new SqlCommand
            (
            "SELECT s.StudioName, i.Studio, i.UPC, i.Title, i.Price, i.Availability, i.Location, i.Qty " +
            "FROM tbl_Item i JOIN tbl_studio s ON i.Studio = s.StudioID WHERE i.Availability = 'T' and i.Qty > 0 ORDER BY i.Location; " +

            "SELECT d.UPC, SUM(d.Qty) FROM tbl_PROrderDetail d JOIN tbl_PROrder p ON d.OrderNo = p.OrderNo " +
            "WHERE p.Status = 'P' and p.Type = 'P' GROUP BY d.UPC;"

            , conn);

        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();

        adapter.Fill(ds);
        conn.Close();

        DataTable dtTest = new DataTable();

        ds.Tables[0].Merge(ds.Tables[1]);
        dtTest = ds.Tables[0];

        return ds;
    }
}

Code behind

protected void Page_Load(object sender, EventArgs e)
{
    DataModel dm = new DataModel();
    DataSet ds = dm.GvTest();
    GridBind(ds);
}

private void GridBind(DataSet ds)
{
    gvItemList.DataSource = ds.Tables[0];
    gvItemList.DataBind();
}

This code just generates the first SELECT result and then the second SELECT result right after.

What I need to do is add a new column to Tables[0], and the result set of Tables[1] fills the new column.

Row count of Tables[0] = 94 Row count of Tables[1] = 6800

I need 94 rows on my GridView, not 6800. UPC is the connection.

Thanks in advance!

We have updated a ASP.NET WebForms website from .Net framework 3.5 to 4.5 . we are using telerik controls, website is compiled and working fine but i can see following error in log file. looks telerik related issue

System.Web.HttpException (0x80004005): This is an invalid webresource request.
  at 
System.Web.Handlers.AssemblyResourceLoader
.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at 
System.Web.HttpApplication.CallHandlerExecutionStep.
System.Web.HttpApplication.IExecutionStep.Execute()
at 
System.Web.HttpApplication.CallHandlerExecutionStep.
System.Web.HttpApplication.IExecutionStep.Execute()"

any idea how to fix the issue ?

There any way to do a project using pwa concept in aspx page??? . I am using a html with pwa it work fine but i am move in to the asp net it does not work and json file not loaded . If it is a asp net support pwa concept

I have this vote method on a API i'm working on (I am sure there is plenty of room for improvement, all advice is appreciated).

I get this error:

"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions." ExceptionType:"System.Data.Entity.Core.OptimisticConcurrencyException"

But everything seems to work fine

I add a new Vote object, with the voting user connected to it. And update the Post with a new nr of votes..

Can someone explain what goes wrong here? Perhaps advice to a solution

    [HttpGet]
    [Authorize]
    [Route("api/vote")]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(Post))]

    public IHttpActionResult Vote(string image_id, bool upVote)
    {
        // http://api.badgag.com/api/up/?image=123&upVote=true

        User user = new User(ClaimsPrincipal.Current.Claims);
        if (user != null)
        {
            telemetry.Context.User.Id = user.user_id;
        }

        Post post = (from p in db.Posts where p.image.id == image_id select p).FirstOrDefault();

        // find post with image_id
        if (post == null)
        {
            // string message = "Could not find image";
            string message = "2";
            System.Diagnostics.Trace.TraceWarning(message);
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
        }

        if (post.creator.user_id == user.user_id)
        {
            // string message = "User cannot vote on his own post";
            string message = "3";
            System.Diagnostics.Trace.TraceWarning(message);
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
        }

        // TODO: find a faster way to look this up!
        foreach (Vote v in post.votes)
        {
            if (v.user.user_id == user.user_id)
            {
                // string message = "User already voted on this post";
                string message = "4";
                System.Diagnostics.Trace.TraceWarning(message);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
            }
        }

        // add new vote
        Vote vote = new Vote();

        // if user does exist in db, add that object
        // if not, use new user object generated from claims
        vote.user = (from u in db.Users where u.user_id == user.user_id select u).FirstOrDefault();
        if (vote.user == null)
        {
            vote.user = user;
        }

        vote.upVote = upVote;
        vote.datetime = DateTime.Now;
        post.votes.Add(vote);

        // calc rating
        post.rating = new Rating();
        post.rating.datetime = post.image.datetime;
        post.rating.up = post.votes.Count(v => v.upVote == true);
        post.rating.down = post.votes.Count(v => v.upVote == false);
        post.rating.calc();

        // ERROR on saveChanges()
        /*
            "Store update, insert, or delete statement affected an unexpected number of rows (0). 
            Entities may have been modified or deleted since entities were loaded. 
            See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."

            ExceptionType: "System.Data.Entity.Core.OptimisticConcurrencyException"
         */

        // update post in DB
        db.SaveChanges();

        // remove sensitive info from Post before returning
        post.creator.email = "removed";
        post.creator.gender = "removed";
        post.creator.locale = "removed";
        post.creator.nickname = "removed";
        post.creator.picture = "removed";
        post.image.deletehash = "removed";
        post.votes.Clear();

        return Json(post);
        // return Json("user: " + user.user_id + " votes up image id: " + image);
    }

PS. This is from badgag.com, if you are interested in testing. Upload posts and vote :)

edit: full error message

{Message: "An error has occurred.", ExceptionMessage: "An error occurred while saving entities that do no…entity types. See the InnerException for details.", ExceptionType: "System.Data.Entity.Infrastructure.DbUpdateException", StackTrace: "   at System.Data.Entity.Internal.InternalContext.…tpControllerDispatcher.<SendAsync>d__1.MoveNext()", InnerException: {…}}
ExceptionMessage
:
"An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details."
ExceptionType
:
"System.Data.Entity.Infrastructure.DbUpdateException"
InnerException
:
ExceptionMessage
:
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."
ExceptionType
:
"System.Data.Entity.Core.OptimisticConcurrencyException"
Message
:
"An error has occurred."
StackTrace
:
"   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source)
↵   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
↵   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
↵   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
↵   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
↵   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
↵   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
↵   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
↵   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
↵   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
↵   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
↵   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
↵   at System.Data.Entity.Internal.InternalContext.SaveChanges()"
__proto__
:
Object
Message
:
"An error has occurred."
StackTrace
:
"   at System.Data.Entity.Internal.InternalContext.SaveChanges()
↵   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
↵   at System.Data.Entity.DbContext.SaveChanges()
↵   at Api.Controllers.PostController.Vote(String image_id, Boolean upVote) in C:\git\secureapi\Api\Controllers\PostController.cs:line 95
↵   at lambda_method(Closure , Object , Object[] )
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
__proto__
:
Object

Hello In PHP You can do something like this

$sql = "SELECT * FROM Food_Table";
$query = $db->query($sql);
while($result = $query->fetch(PDO::FETCH_ASSOC))
{
   $my_array[ $result["food_type"] ][ $result["food_id"] ] = $result["food_name"]; 
}

From above PHP code It's about doing query and then store data in 2 dimensional array.

So I would like to ask that there are thing equivalent to this in ASP.NET MVC using Entity Framework (LINQ) ?

How can do it Please. I could find the thread only about linq and send model to view

function createSalesInvoice() {

    SalesInvoice.TotalInvoiceValue = $('#txtinvoicevalue').val();
    SalesInvoice.TaxableValue = $("#txtTaxable").val();
    SalesInvoice.TotalCGST = $("#txtTotalCGST").val();
    SalesInvoice.TotalSGST = $("#txtTotalSGST").val();
    SalesInvoice.DiscountAmount = $("#txtTotalDiscount").val();
    SalesInvoice.FinalAmount = $("#txtGrandTotal").val();
    SalesInvoice.PaidAmount = $("#txtTotalPaid").val();
    SalesInvoice.RemainingAmount = $("#txtTotalRemAmt").val();
   // alert(SalesInvoice.TotalInvoiceValue); ----------------This alert is working fine and return all above values correct.
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/AjaxRequestToServer.aspx/createSalesInvoice", //URI   
        data: '{SalesInvoice: ' + JSON.stringify(SalesInvoice) + '}',
        dataType: "json",
        success: function (data) {

            bootbox.alert("Item Added Successfully", function (e) { });

            GetSalesInvoiceItemsList();
            $("#hdfFlag").val("false");
        },
        error: function (xhr) {
        }
    });
}

This Ajax function cannot call my webmethod from webpage. all values from textbox returns correct. i want to insert thoes values in table. But I am unable to call webmethod. Thanks in advance.

I am using a <asp:FileUpload> to upload a PDF file to my web page. But after clicking on browse the window opens, and once I select a file and click on Open i want to get the file name and display it in a Label. What function should I use in ASP.NET to do this? I tried the OnLoad, OnUnload, OnDataBinding, etc. in the <asp:FileUpload> but nothing works. Can someone suggest me a solution for this?

My code is as below:

<asp:FileUpload ID="fileUpload" runat="server" /><br />
<asp:Label ID="labelFilename" runat="server" Text=""></asp:Label>

Once I select a file and click open the file name should be displayed in the label.

I have a requirement:-

If the user has the company's Download Manager installed on the system then we should let the file get downloaded using the download manager. If not then the user should not be forced to download the Manager and the download should begin normally as it does for any file in the browser.

The problem I am facing is that the file download URL that is being created open in a new tab and is something that only Download Manger identifies(starts with hwdm). If the system has the Download Manager, it will begin the download and if it's not there it will close the browser tab after some time without downloading. When I need to modify this to accommodate the new requirement, I have now way of knowing if the download began for that file or not. Here is the code:-

function logDownloadRequest(el, fileLink) {
        if (logUrl) {
            $(el).attr('disabled', true);
            var req = new XMLHttpRequest();
            req.open('post', logUrl + '?fileLink=' + encodeURIComponent(fileLink));
            req.send();
            req.onload = function (e) {
                $(el).attr('disabled', false);
                if (req.status === 200) {
                    var hid = req.responseText;
                    if (hid.indexOf('"') === 0) {
                        hid = hid.substring(1, hid.length);
                    }
                    if (hid.lastIndexOf('"') === (hid.length - 1)) {
                        hid = hid.substring(0, hid.length - 1);
                    }
                    var targetWindow = window.open('hwdm:' + hid, '_blank');
                    setTimeout(function () {
                        targetWindow.close();
                    }, 5000);
                } else {
                    alert('Could not download file.');
                }
            };
            req.onerror = function (e) {
                $(el).attr('disabled', false);
                alert('Could not download file.');
            }
        } else {
            alert('Could not download file.');
        }
        return false;
    }

The targetWindow URL is of the form hwdm:aHR0cHM6Ly9oc21mdHBzb2Z0LmJsb2IuY29yZS53aW5kb3dzLm5ldDo0NDMvc29mdHdhcmVzL0JhcmNvZGUlMjBTY2Fubm.......

Can anyone suggest a way to get this done without downloading duplicate copies of the same file?

Thank you.

Error: The Remote Server Returned An Error 400 Bad Request

I am using asp vb.net and instagram api

I found a tutorial on instagram api but it is in c#. i tried to convert from c# to VB the best i cound but for some reason I am getting an error.

https://code.msdn.microsoft.com/Haroon-Said-e1d8d388

I am getting an error on line:

Dim result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters)

My code:

Function GetDataInstagramToken()
Try
    Dim parameters As New NameValueCollection
    parameters.Add("client_id", Client_ID)
    parameters.Add("client_secret", ClientSecret)
    parameters.Add("grant_type", "authorization_code")
    parameters.Add("redirect_uri", "http://localhost:8979/UI/InstaHome.aspx")
    parameters.Add("code", Code)

    Dim client As WebClient = New WebClient()
    Dim result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters)
    Dim response = System.Text.Encoding.Default.GetString(result)

    'deserializing nested JSON string to object
    Dim jsResult As JObject = JsonConvert.DeserializeObject(response)
    Dim accessToken As String = jsResult("access_token")
    Dim id As Int16 = jsResult("user")("id")

    'This code register id and access token to get on client side
    Page.ClientScript.RegisterStartupScript(GetType(String()), "GetToken", "<script>var instagramaccessid=\"" + @"" + id + "" + " \ "; var instagramaccesstoken=\"" + @"" + accessToken + "" + " \ ";</script>")

Catch ex As Exception
     myLabel.text += "-" &ex.message
End Try
End Function