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

I have this Method that should display The Most Popular/favorite Product and Order By Descending base on the Sum of the Quantity of each product.Although is still need to be tested. I need to call this Method ProductPop() From a controller into a View.That is not linked to the Controller

      public class AnalysisController : Controller
    {

     public List<Order_Detail> ProductPop()
            {

              List<Order_Detail> result = new List<Order_Detail>();
                result.GroupBy(l => l.ProductName).Select(cl => new Order_Detail
                {
                    ProductName = cl.First().ProductName,
                    Quantity = cl.Sum(c => c.Quantity)
                }).OrderByDescending(k=>k.Quantity).ToList();
                return result;
            }
}

This is what I have in my View(This view is an empty Index method of another Controller that just returns a View)

@using ProjectName.Controllers;
@{
    AnalysisController AC = new AnalysisController();
    ViewBag.Title = "Index";
}
   @foreach(var od in ProductPop())
{
   <table>
      <tr>
          <th>
              Product Name
          </th>
          <th>
             Quantity
          </th>
      </tr>
       <tr>
           <td>
               @od.ProductName
           </td>
           <td>
               @od.Quantity
           </td>
       </tr>
   </table>

}

If there are any references / Advice. I will Glady appreciate it. Thanks!

Hello every one here i am Generating a BarCode using Font Free 3 of 9 like this in a .rdlc Report Page.

 `<Textbox Name="ID">
            <rd:DefaultName>ID</rd:DefaultName>
            <Top>1.1in</Top>
            <Width>1.15 in</Width>
            <Style>
              <FontFamily>Free 3 of 9</FontFamily>
              <FontSize>28pt</FontSize>
              <TextAlign>Center</TextAlign>
              <PaddingLeft>2pt</PaddingLeft>
              <PaddingRight>2pt</PaddingRight>
              <PaddingTop>2pt</PaddingTop>
              <PaddingBottom>2pt</PaddingBottom>
            </Style>
            <ZIndex>6</ZIndex>
            <Left>2.26406in</Left>
            <Height>0.59063in</Height>
            <Value>= "*" &amp; Fields!ID.Value &amp; "*" </Value>
          </Textbox>` 

But the Scanner i have isn't reading it its not scanning it at all. Can any one help where is the error. Its a ID that gets to be printed and should be Scan able but its doesn't Scan. what other Font could Replace it ? It creates the BarCode looks fine prints and every thing Converts to PDF but doesn't Scan.

I am working as an Asp.Net developer(SQL) in a small organization. I have more than 4 years of experience in Dotnet. But I have a break of over 5 years and recently I restarted my career and landed a job. I want to do Microsoft Certification in Asp.net (C#) and SQL server. I was told i can do a certification to recollect and understand the complete workflow of a project. I am not sure where I should start.

Moreover I found the below sites: http://www.itcareerfinder.com/it-certifications/microsoft-certifications.html

http://www.itcareerfinder.com/it-certifications/microsoft-certifications/mcsd-certifications.html

I was confused if I should do two certifications.

Can someone suggest me the right approach or article in a step-by-step manner?

Thanks in Advance.

I am creating a web app using ASP.Net that is utilizing SignalR for client communication.

Whenever my client side code attempts to Close a HubConnection instance, using either the .Stop() method or wrapping the HubConnection in a using block, the server starts throwing System.Net.WebSockets.WebSocketsExceptions.

My server is being hosted by Visual Studio using IIS Express, and I have tried client code in both Linqpad and as a stand-alone exe. Both clients produced the same server exceptions.

My client side code (with unnecessary details removed) looks like this

async Task Main()
{
    var signalServerLocation = "http://localhost:5462/signalr";

    using (var hubConnection = new HubConnection(signalServerLocation))
    {
        await hubConnection.Start();
    }
}

The exception that gets raised looks like this

System.Net.WebSockets.WebSocketException occurred
  HResult=0x800703E3
  Message=The I/O operation has been aborted because of either a thread exit or an application request
  Source=System.Web

with a stack trace of

at System.Web.WebSockets.WebSocketPipe.<>c__DisplayClass9_0.<ReadFragmentAsync>b__0(Int32 hrError, Int32 cbIO, Boolean fUtf8Encoded, Boolean fFinalFragment, Boolean fClose)

This exception is non-fatal so it doesn't crash my server, but continuing through it leads to more exceptions of the same type being thrown, as well as System.OperationCancelledExceptions with the description of The operation was cancelled.

I've searched around a bit but couldn't find a straight answer as to why this happens.

So my question is this. Is there something I can do to stop these Exceptions from being thrown, or are they expected? Is there a problem with the way I am connecting?

How to delete mutable objects in the repeater were I am using a repeater I won't to set a checkbox and a delete button when you click that button all the data of the checked boxes are deleted.

This is the table in the database:

create table Employee(
                      ID int primary key identity,
                      FName nvarchar(50) not null,
                      LName nvarchar(50) not null,
                      PhoneNumber nvarchar(20) not null,
                      Gender nvarchar(1) not null,
                      createdOn datetime not null,
                      countryCity nvarchar(50) not null,
                      Email nvarchar(50) not null,
                      photo nvarchar(50) not null,
                      DepartmentsID int references Departments(ID));

This is the front end code:

<asp:CheckBox runat="server" ID="Delete" class="deleteemployee" AutoPostBack="true" OnCheckedChanged="Delete_CheckedChanged"/>
  <asp:Button ID="btndelete" runat="server" Text="Delete" OnClick="btndelete_Click" CssClass="btn btn-danger pull-right" />

This is the back end code:

protected void btndelete_Click(object sender, EventArgs e){
}
protected void Delete_CheckedChanged(object sender, EventArgs e){
}

In my project I have a modal window where a cascading dropdownlist is shown for two properties (Family, TypeID) of a class (Machine).

The issue: The dependant dropdownlist populates only when the modal window has been open for the second time. On the first time, nothing happens:

Here is a picture of how it works for a better understanding:

enter image description here

Notice that the row that says Modelo (Modelo is the name for TypeID) is empty in the first moment, but once re-opened, it populates with the expected information.

The code:

Note The Javascript is located in the Index page that contains the link to the modal window

This modal window is used when a New Machine is Created, or Edited. For that reason, in the first section of the Javascript, I check in which situation I am and check if the Machine property: MchName, has a value. In case it doesn't have a value, I assign the value of the variable items to the property TypeID that should be shown when the Modal opens.

<script type="text/javascript">
    $(document).ready(function () {
        $('#modal-action-machine').on('shown.bs.modal', function () {
            var test = "#MchName";
            if ($(test).val()) {

            } else {
                var items = "<option value='0'>Select</option>";
                $('#TypeID').html(items);
            }
        });
    });
</script>

<script type="text/javascript">
    $('#modal-action-machine').on('shown.bs.modal', function (e) {
        $('#FamilyID').change(function () {
            var url = '@Url.Content("~/")' + "Machines/GetModel";
            var ddlsource = "#FamilyID";
            $.getJSON(url, { FamilyID: $(ddlsource).val() }, function (data) {
                var items = '';
                $("#TypeID").empty();
                $.each(data, function (i, model) {
                    items += "<option value='" + model.value + "'>" + model.text + "</option>";
                });
                $('#TypeID').html(items);
            });
        });
    });
</script>

Get Method:

    [HttpGet]
    public IActionResult CreateEdit(int? id)
    {
        //Lista de Familias
        List<MachineFamily> FamilyList = new List<MachineFamily>();
        FamilyList = (from family in _context.MachineFamilies
                      select family).ToList();
        FamilyList.Insert(0, new MachineFamily { FamilyID = 0, FamilyDescription = "-- Seleccione Familia --" });
        ViewBag.ListofFamily = FamilyList;

        ViewBag.TypeID = string.Empty;
        return PartialView("~/Views/Shared/Machines/_Create.cshtml");
    }

JsonResult:

    public JsonResult GetModel(int FamilyID)
    {
        List<MachineType> ListaModelos = new List<MachineType>();
        ListaModelos = (from model in _context.MachineTypes
                        where model.FamilyID == FamilyID
                        select model).ToList();
        ListaModelos.Insert(0, new MachineType { TypeID = 0, TypeDescription = "-- Seleccione Modelo --" });
        return Json(new SelectList(ListaModelos, "TypeID", "TypeDescription"));
    }

View: Modal

@model Application.Models.ApplicationviewModels.MachineIndexData
@using Application.Models

<form asp-action="CreateEdit" role="form">
    @await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo") })

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="modal-body form-horizontal">
        <input type="hidden" asp-for="Id" />
        <div class="form-group">
            <label asp-for="FamilyID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="FamilyID" class="form-control"
                        asp-items="@(new SelectList(ViewBag.ListofFamily,"FamilyID","FamilyDescription"))"></select>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="TypeID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="TypeID" class="form-control"
                        asp-items="@(new SelectList(ViewBag.TypeID,"TypeID","TypeDescription"))"></select>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="BrandID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="BrandID" class="form-control" asp-items="ViewBag.BrandID">
                    <option value="">-- Seleccione Marca --</option>
                </select>
                <span asp-validation-for="BrandID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="SupplierID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="SupplierID" class="form-control" asp-items="ViewBag.SupplierID">
                    <option value="">-- Seleccione Proveedor --</option>
                </select>
                <span asp-validation-for="SupplierID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="StoreID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="StoreID" class="form-control" asp-items="ViewBag.StoreID">
                    <option value="">-- Seleccione Tienda --</option>
                </select>
                <span asp-validation-for="StoreID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="MchName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="MchName" class="form-control" />
                <span asp-validation-for="MchName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="NumDevices" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input id="NumDevices" asp-for="NumDevices" class="form-control" readonly />
                <span asp-validation-for="NumDevices"  class="text-danger"></span>
                <input id="getNum" type="range" min="" max="10" step="1" onchange="fetch()" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="FechaCompra" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input data-format="0:dd/MM/yyyy" type="datetime" asp-for="FechaCompra" class="form-control datepicker" />
                <span asp-validation-for="FechaCompra" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="CostoMaq" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="CostoMaq" class="form-control" />
                <span asp-validation-for="CostoMaq" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="MachineStatus" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select name="MachineStatus" asp-for="MachineStatus" class="form-control" disabled>
                    <option value="0">Operativo</option>
                    <option value="1" selected="selected">Nuevo Item</option>
                    <option value="2">Reparación</option>
                </select>
                <input type="hidden" name="MachineStatus" value="1" />
                <span asp-validation-for="MachineStatus" class="text-danger"></span>
            </div>
        </div>

        @await Html.PartialAsync("_ModalFooter", new ModalFooter { })
    </div>
</form>

Final notes: I believe that to fix this I should change the Javascript. Can someone please explain to me why this happens and how to fix it?

I have a recursive method in a razor view that takes an object as parameter which is a list of nested lists. To make it clearer : categories containing child categories that I show in HTML <ul> elements. Each category has a Html.CheckBoxFor(). I want to do something simple : if you validate without ticking any checkbox, go back to the view and show error message. The problem is that validating without anything returns an empty model, so when I send my user back to the view, the model is empty and the list cannot be regenerated and an exception is thrown. Here's an example :

@using (Html.BeginForm("AddCategory", "Create", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="treeview">
    <ul class="list-group addCat">
        @showMenu(Model, "#root", "")
    </ul>
</div>
@helper showMenu(MyProject.Models.CategoryModel model)
{
foreach (var category in model.categories){
    @Html.RadioButtonFor(m=>m.selected, category.idCategory)
    @Html.Label(category.name)
    @Html.ValidationMessageFor(m => m.selected)
    if(category.childCategories.Count()!=0)
    {
           @showMenu(category.childCategories)
     }
}
}

And my model:

public class CategoryModel
{
    public int idCategory { get; set; }
    public List<CategoryModel> categories { get; set; }
    [Required(ErrorMessage ="Choisissez une catégorie")]
    public int selected { get; set; }
    public string name { get; set; }
}

This is not my actual code, it's just to give a general idea, I'm listing every category as a checkbox and then want to use my validation summary in my controller like this :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddCategory(CategoryModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);//When you validate without anything checked, values are null in here and exception gets thrown
    }
    else
    {
        return RedirectToAction("AddCategoryToDB", model);
    }
}

I know how to do this with some JQuery and show an alert dialog but I managed to make this work for other parts of my website so it needs to be uniform. The thing being that it works where models are not needed to create the form. Whereas here I need the data initially retrieved to show my list items.

I'm working on a timesheet application where employees create timesheet based on the number of projects they have been assigned to by an Admin.This is a view of a user with 4 project to create a timesheet for. Each row here is a form created by a loop based on the number of projects passed to a viewbag.

This is the code from my view that creates the forms

<tbody style="font-size: 13px;">
                        @{ 
                            int i = 0;

                            }
                        @while (i < ViewBag.projCount)
                        {
                            using (Ajax.BeginForm("BillableHours", "TimesheetManager",
                                new AjaxOptions
                                {
                                    OnSuccess = "OnSuccess",
                                    OnFailure = "OnFailure",
                                    LoadingElementId= "progress"
                                }, new { id= "Form-" + i}))
                            {
                            <tr>
                                <td>
                                    <!-- Hours code begins -->
                                    <div>
                                        @Html.TextBoxFor(p => p.B_Monday, new { @class = "form-control", type = "number", min = "0", id = "B_Monday-" + i.ToString(), max = "8", onChange = "totalMonday(); checkTotal();" })
                                    </div>
                                    <!-- hours code ends -->
                                </td>
                                <td>
                                    <!-- Hours code begins -->
                                    <div>
                                        @Html.TextBoxFor(p => p.B_Tuesday, new { @class = "form-control", type = "number", min = "0", id = "B_Tuesday-" + i.ToString(), max = "8", onChange = "totalTuesday(); checkTotal();" })
                                    </div>
                                    <!-- hours code ends -->
                                </td>
                                <td>
                                    <!-- Hours code begins -->
                                    <div>
                                        @Html.TextBoxFor(p => p.B_Wednesday, new { @class = "form-control", type = "number", min = "0", id = "B_Wednesday-" + i.ToString(), max = "8", onChange = "totalWednesday(); checkTotal();" })
                                    </div>
                                    <!-- hours code ends -->
                                </td>
                                <td>
                                    <!-- Hours code begins -->
                                    <div>
                                        @Html.TextBoxFor(p => p.B_Thursday, new { @class = "form-control", type = "number", min = "0", id = "B_Thursday-" + i.ToString(), max = "8", onChange = "totalThursday(); checkTotal();" })
                                    </div>
                                    <!-- hours code ends -->
                                </td>
                                <td>
                                    <!-- Hours code begins -->
                                    <div>
                                        @Html.TextBoxFor(p => p.B_Friday, new { @class = "form-control", type = "number", min = "0", id = "B_Friday-" + i.ToString(), max = "8", onChange = "totalFriday(); checkTotal();" })
                                    </div>
                                    <!-- hours code ends -->
                                </td>
                                <td>
                                    <!-- Hours code begins -->
                                    <div>
                                        @Html.TextBoxFor(p => p.B_Saturday, new { @class = "form-control", type = "number", min = "0", id = "B_Saturday-" + i.ToString(), max = "8", onChange = "totalSaturday(); checkTotal();" })
                                    </div>
                                    <!-- hours code ends -->
                                </td>
                                <td>
                                    <!-- Hours code begins -->
                                    <div>
                                        @Html.TextBoxFor(p => p.B_Sunday, new { @class = "form-control", type = "number", min = "0", id = "B_Sunday-" + i.ToString(), max = "8", onChange = "totalSunday(); checkTotal();" })
                                    </div>
                                    <!-- hours code ends -->
                                </td>
                                <td>
                                    <!-- project selection -->
                                    @Html.DropDownListFor(p => p.ProjectID, ViewBag.Projects as SelectList, "--select project--", new { @class = "form-control" })
                                    <!-- project selection ends -->
                                </td>
                                <td>
                                    <!-- comments -->
                                    <div>
                                        @Html.TextBoxFor(p => p.ResourceComments, new { @class = "form-control", placeholder = "Comments...", type = "text" })
                                    </div>

                                </td>
                            </tr>                            
                            }
                            i++;
                        }

                    </tbody>

Please, I need help on how to submit the form(s), considering the number of rows is different for each user

This is the ViewModel

 public class BillableHoursViewModel
{

    //billable hours

    public int ProjectID { get; set; }        
    public double B_Monday { get; set; }
    public double B_Tuesday { get; set; }
    public double B_Wednesday { get; set; }
    public double B_Thursday { get; set; }
    public double B_Friday { get; set; }
    public double B_Saturday { get; set; }
    public double B_Sunday { get; set; }
    public string ResourceComments { get; set; }
 }

I am working in an ASP.net MVC app using javascript. I am using a devExpress dxSwitch to try to change the theme of the page.

I have this code in my head of my _layout.cshtml

    @Html.DevExpress().GetStyleSheets( "dark",
    new StyleSheet { ExtensionSuite = ExtensionSuite.NavigationAndLayout },
    new StyleSheet { ExtensionSuite = ExtensionSuite.Editors },
    new StyleSheet { ExtensionSuite = ExtensionSuite.GridView },
    new StyleSheet { ExtensionSuite = ExtensionSuite.Dashboard}
)

Instead of hard coding "dark" in for the theme I want to see if I could use a variable in place of it and apply this function to switch between light and dark.

$('#switch').click(function () {


            var whichTheme = $("#switch").dxSwitch("instance");
            var valueSwitch = whichTheme.option("value");
            if (valueSwitch === true) {

                $('body').css('background-color', '#343434');

            } else {

                $('body').css('background-color', 'whitesmoke');
            }
        });

I am managing Active Directory using asp.net I have a requirement to restore deleted user to their respective OU.

How to do below one?

First How to find out deleted users in AD? Second How to restore that deleted users to their respective OU?

Please help me on this.

Using F12 in firefox, showed "ReferenceError: readXML is not defined"

According to the opensource website https://data.gov.hk/en-data/dataset/clp-team1-electric-vehicle-charging-location/resource/c9dc4e0f-c618-445b-9c00-7f3d952b1e8a, it said HTTPS request method: GET can be used. Why error shown? Thanks !

<html>
<head>
<title>Reading XML file</title>
<script type="text/javscript">
function readXML(){
    var xml=new XMLHttpRequest();
    xml.open('GET','https://opendata.clp.com.hk/GetChargingSectionXML.aspx?lang=en',false);
    xml.send();
    var xmlData=xml.responseText;
    document.write (xmlData);
}
</script>
</head>

<body>
<h1>XML file</h1>
<button onclick="readXML()">Read XML file</button>
</body>

</html>

I want to capture the images using webcam ,its working fine by using getusermedia() function

<script type="text/javascript">
    function take_snapshot() {
        Webcam.snap(function (data_uri) {
            // display results in page
            var DImg_rawURI = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
            document.getElementById('results').innerHTML = '<img src="' + data_uri + '"/>';
            document.getElementById('<%=imgdonor .ClientID %>').src = data_uri;
            document.getElementById('<%=txt_imgurl.ClientID %>').value = data_uri;
            document.getElementById("divCamera").style.display = "none";
            document.getElementById('<%=txtDImg_rawURI.ClientID %>').value = DImg_rawURI;
        });
    }
</script>

but I dont want to use this function becuse its not working in chrome and i cant move my applcation to https

I have cloned the project from github and followed instructions from the MixERP documentation. Built the project in visual studio successfully, installed PostgreSQL version 9.6. When I ran the project it gave me error ' relation config.mixerp not exist'.

We are using VS2015, PgAdmin4.

ERROR: 42P01: relation "config.mixerp" does not exist 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: Npgsql.NpgsqlException: ERROR: 42P01: relation "config.mixerp" does not exist

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.

I can't figure out how to upload a file using the upload button and then insert into (along with other stuff) the database.

When I debug into btnRegister_Click, HasFile returns false.

Is there a way to persist HasFile across 2 different button onclicks?

enter image description here

Upload code:

            <tr>
                <td>Expense Receipt
                </td>
                <td class="blackDisplayName">
                    <asp:UpdatePanel ID="uplExpenseReceipt" runat="server" ViewStateMode="Enabled">
                        <ContentTemplate>
                            <asp:FileUpload ID="fuExpenseReceipt" runat="server" />
                            <asp:Button ID="btnUploadExpenseReceipt" runat="server" Text="Upload" OnClick="btnExpenseReceiptUpload_Click" />
                        </ContentTemplate>
                        <Triggers>
                            <asp:PostBackTrigger ControlID="btnUploadExpenseReceipt" />
                        </Triggers>
                    </asp:UpdatePanel>
                    <asp:Label ID="lblFileWarning" runat="server" Text="" Font-Bold="true" ForeColor="Red"></asp:Label>
                </td>
            </tr>

C# code behind:

protected void btnExpenseReceiptUpload_Click(object sender, EventArgs e)
{
    if (!fuExpenseReceipt.HasFile)
    {
        lblFileWarning.Text = "Please browse your computer to load a pdf or jpg file";
        return;
    }

    if (fuExpenseReceipt.PostedFile.ContentLength > 1000000)
    {
        lblFileWarning.Text = "file size must be < 1Mb";
        return;
    }

    //if (!fuExpenseReceipt.PostedFile.ContentType.Equals("application/pdf") | !fuExpenseReceipt.PostedFile.ContentType.Equals("image/jpg"))
    if (!fuExpenseReceipt.PostedFile.ContentType.Equals("application/pdf"))
    {
        lblFileWarning.Text = "Only pdf or jpg files are allowed to be uploaded";
        return;
    }

    if (!Directory.Exists(@"C:\Ireland Resources\ExpenseReceipts"))
    {
        Directory.CreateDirectory(@"C:\Ireland Resources\ExpenseReceipts");
    }

    string FolderUpload = @"C:\Ireland Resources\ExpenseReceipts\";
    string PostedFile = FolderUpload + User.Identity.Name + "-" + fuExpenseReceipt.PostedFile.FileName;
    fuExpenseReceipt.SaveAs(PostedFile);
}

Register code:

            <td class="blackDisplayName" align="right">
                <asp:Button ID="btnRegister" runat="server" Text="Register" ValidationGroup="ExpenseRegistration"
                    OnClick="btnRegister_Click" CssClass="gray-gradient" SkinID="NONE"/>
            </td>

C# code behind:

protected void btnRegister_Click(object sender, EventArgs e)
{
    try
    {
        if (!fuExpenseReceipt.HasFile)
        {
            lblFileWarning.Text = "Please browse your computer to load a pdf or jpg file";
            return;
        }

        byte[] expenseReceipt = null;

        Stream fs = fuExpenseReceipt.PostedFile.InputStream;
        byte[] bytFileData = new byte[fs.Length];
        fs.Read(bytFileData, 0, Convert.ToInt32(fs.Length));
        fs.Close();
        expenseReceipt = bytFileData;

        int tillID = Int32.Parse(hfTillID.Value);

        double beforeVAT = double.Parse(txtBeforeVAT.Text);
        double VAT = double.Parse(txtVAT.Text);
        double totalAmount = double.Parse(txtExpenseTotal.Text);
        lblExpenseMessage.Visible = true;
        try
        {
            new TillEndOfDayDAL().SaveExpense(StationID, tillID, beforeVAT, VAT, totalAmount, txtExpenseDescription.Text
                , expenseReceipt, Int32.Parse(ddlExpenseTypes.SelectedValue), Page.User.Identity.Name.ToUpper());

            lblExpenseMessage.Text = "Sundry expense has been successfully registered.";

        }

I'm going to fetch some data from a ASPX site and since the data's value change time by time it was generate by ASPX script.

When I use cheerio code and tried to fetch the value I found out an issue, a API GET request can only get ASPX source (looks like the script that generate the data) but can't get the current data that's showing (the data you can view in browser).

When I found the above issue I tried to solve it but I can't, I tried to search something like get aspx content by node.js but can't find any useful result.

So, how can I get the ASPX script generated value (the value that normal browser visitor can see) using node.js

This is not duplicate thread . My case is to send array parameter without model. but other thread is send int, string parameter individual.

I know about how to post to controller with model object.
But sometimes I want to post data outside of model db and post in format object or array How could I do?

View

<form action="/home/showdata" method="post">
  <input type="text" name="arr.username" />
  <input type="text" name="arr.password" />
  <input type="text" name="arr.email" />
</form>

Controller

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult ShowData(Array data)
    {  
        return Content(data.username + data.password + data.email);
    }
}

I have a Web API with only one user, I'm trying to use the basic authentication to protect it. It works fine on my local server but when I try it online the "Headers.Authorization" is always null. I tried it with Fiddler.

This is my code:

Class BasicAuthenticationAttribute

public override void OnAuthorization(HttpActionContext actionContext)
{
    if (actionContext.Request.Headers.Authorization == null)
    {
        actionContext.Response = actionContext.Request
            .CreateResponse(HttpStatusCode.Unauthorized);
    }
    else
    {
        string authenticationToken = actionContext.Request.Headers
                                    .Authorization.Parameter;
        string decodedAuthenticationToken = Encoding.UTF8.GetString(
            Convert.FromBase64String(authenticationToken));
        string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
        string username = usernamePasswordArray[0];
        string password = usernamePasswordArray[1];

        if (CheckUser.Login(username, password))
        {
            Thread.CurrentPrincipal = new GenericPrincipal(
                new GenericIdentity(username), null);
        }
        else
        {
            actionContext.Response = actionContext.Request
                .CreateResponse(HttpStatusCode.Unauthorized);
        }
    }
}

The API Controller

public class adduserController : ApiController
{
[HttpGet, BasicAuthentication]
[Route("api/user/{email}")]
public string adduser(string email)
{
    string country_code = "";

    string username = System.Threading.Thread.CurrentPrincipal.Identity.Name;

    return "Welcome";
}

On My Page, i set up a gridview with a few columns. I coded an update, delete and insert method. While my GridView binds its data, the following method is called:

protected void GridViewAutomat_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if(e.Row.RowState != DataControlRowState.Edit)
            { 
                //some code

            }
    }

The Problem with my second if statement is that when my GridView is entering the 'Edit Mode' (when i wanna update a record in my gridview) it doesnt catch the RowState Alternate | Edit which looks like this(this is how the RowState is after i call my Update Method):

enter image description here

When i try to combine the two RowStates seperately it wont work either:

   if(e.Row.RowState != DataControlRowState.Edit && e.Row.RowState != DataControlRowState.Alternate)

The Code in the if-statement shound be executed when the row is not in edit (Alternate | Edit) mode, thats why i have != as an operator

Does anyone know how i can catch the combined mode Alternate | Edit and the Edit Mode together?

Thanks for your help :-)

I am using spreadsheetgear for my project. I have included the spreadsheetgear by using NuGet package and it is also showing in my reference list.

Severity Code Description Project File Line Suppression State Error BC30002 Type 'SpreadsheetGear.Drawing.Image' is not defined. devo.net F:\devo.net\DEVO\Dashboard.aspx 56 Active

Dim image As SpreadsheetGear.Drawing.Image = New SpreadsheetGear.Drawing.Image(shape)

Here is my code

<%@ Import Namespace="SpreadSheetGear.Drawing" %>
<a href="Compare.html">Compare.html</a><%@ Page Language="VB" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="cache-control" content="no-cache" />

<title>.NET Spreadsheet Component Calculation Sample Using VB.NET and Microsoft Excel Compatible Spreadsheet Component for Microsoft .NET, ASP.NET, C#, VB.NET, XLS and Microsoft Visual Studio .NET</title>
<meta content=".NET spreadsheet component calculation sample using Visual Basic .NET and SpreadsheetGear, a royalty free Microsoft Excel compatible spreadsheet component for the Microsoft .NET Framework featuring the fastest and most complete calculation engine available. Create, read, modify, calculate and write Microsoft Excel workbooks from your Microsoft .NET, ASP.NET, C#, VB.NET and Microsoft Office solutions. Integrates with Microsoft Visual Studio .NET, including IntelliSense and Dynamic Help." name="description" />
<script language="VB" runat="server">



    Sub Page_Load(sender As Object, e As EventArgs)

        Dim stopWatch As New System.Diagnostics.Stopwatch()


        stopWatch.Start()
        ' Open workbooks
        Dim filenameMaster As String = Server.MapPath("Files/DEVO Engine.xlsx")
        Dim filenameInput As String = Server.MapPath("Files/Versions/DEVO Input1.xlsx")
        Dim filenameOutput As String = Server.MapPath("Files/Versions/DEVO Dashboard2.xlsx")
        Dim workbookMaster As SpreadsheetGear.IWorkbook = SpreadsheetGear.Factory.GetWorkbook(filenameMaster)
        Dim workbookInput As SpreadsheetGear.IWorkbook = SpreadsheetGear.Factory.GetWorkbook(filenameInput)
        Dim workbookOutput As SpreadsheetGear.IWorkbook = SpreadsheetGear.Factory.GetWorkbook(filenameOutput)

        ' Copy Inputs to Master

        Dim wsInput As SpreadsheetGear.IWorksheet

        For Each wsInput In workbookInput.Worksheets
            Dim InstInput As SpreadsheetGear.IRange = wsInput.UsedRange
            Dim NameInput As String = wsInput.Name
            Dim DestMaster As SpreadsheetGear.IRange = workbookMaster.Worksheets(NameInput).UsedRange
            Dim type1 As SpreadsheetGear.PasteType = SpreadsheetGear.PasteType.ValuesAndNumberFormats
            Dim operation1 As SpreadsheetGear.PasteOperation = SpreadsheetGear.PasteOperation.None
            workbookMaster.Worksheets(NameInput).Unprotect("")
            InstInput.Copy(DestMaster, type1, operation1, "False", "False")

        Next

        Dim DataMaster As SpreadsheetGear.IRange = workbookMaster.Worksheets("Data").UsedRange
        Dim DataOutput As SpreadsheetGear.IRange = workbookMaster.Worksheets("Data").UsedRange
        Dim type2 As SpreadsheetGear.PasteType = SpreadsheetGear.PasteType.ValuesAndNumberFormats
        Dim operation2 As SpreadsheetGear.PasteOperation = SpreadsheetGear.PasteOperation.None

        DataMaster.Copy(DataOutput, type2, operation2, "False", "False")


        Dim shape As SpreadsheetGear.Shapes.IShape

        For Each shape In workbookMaster.Worksheets("Data").Shapes

            Dim image As SpreadsheetGear.Drawing.Image = New SpreadsheetGear.Drawing.Image(shape)
            Dim size As System.Drawing.Size = image.GetSize()
            Dim bitmap As System.Drawing.Bitmap = image.GetBitmap()
            Dim Imagename As String = Server.MapPath("Files/Images/" & shape.Name & ".png")

            bitmap.Save(Imagename, System.Drawing.Imaging.ImageFormat.Png)
            'Dim Imageurl As String = "Files/" & shape.Name & ".png"
            'SpreadsheetGear.Drawing.Image.ImageUrl = Imageurl
            bitmap.Dispose()

        Next

        stopWatch.Stop()
        Dim ts As TimeSpan = stopWatch.Elapsed
        Dim elapsedTime As String = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
        System.Diagnostics.Debug.Print("RunTime " + elapsedTime)


        'Send data from Master to Output file
        'Dim instance As SpreadsheetGear.IRange = workbookMaster.Worksheets("Data").UsedRange
        'Dim destination As SpreadsheetGear.IRange = workbookOutput.Worksheets("Data").UsedRange
        'Dim type As SpreadsheetGear.PasteType = SpreadsheetGear.PasteType.ValuesAndNumberFormats
        'Dim operation As SpreadsheetGear.PasteOperation = SpreadsheetGear.PasteOperation.None
        'workbookOutput.Worksheets("Data").Unprotect("")
        'instance.Copy(destination, type, operation, "False", "False")
        'workbookOutput.Save()
        'Server.Transfer("OutputDashboard.html")


    End Sub 'Page_Load



</script>


</head>
<body>


</body>
</html>

I use Windows Authentication against Active Directory in my ASP.NET MVC website. I am now trying to deploy the site to test, but the problem is that I keep getting the following exception at login:

Cannot open database "PrincipalServerDB" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\WebExploit'.

I have followed this tutorial to deploy to test : https://docs.microsoft.com/en-us/aspnet/web-forms/overview/deployment/visual-studio-web-deployment/deploying-to-iis

And I use authentication as described here : http://tech.trailmax.info/2016/03/using-owin-and-active-directory-to-authenticate-users-in-asp-net-mvc-5-application/ that uses OWIN authentication.

I am conscious that my question lacks understanding, but it is because I don't understand what's going on . I have tried following the steps as described in this post https://stackoverflow.com/a/7698316/4714502 but I had already done a Grant.sql script to grant access as follows :

    IF NOT EXISTS (SELECT name FROM sys.server_principals WHERE name = 'IIS APPPOOL\DefaultAppPool')
BEGIN
    CREATE LOGIN [IIS APPPOOL\DefaultAppPool] 
      FROM WINDOWS WITH DEFAULT_DATABASE=[master], 
      DEFAULT_LANGUAGE=[us_english]
    END
    GO
    CREATE USER [WebExploitUser] 
      FOR LOGIN [IIS APPPOOL\DefaultAppPool]
    GO
    EXEC sp_addrolemember 'db_owner', 'WebExploitUser'
    GO

In the first tutorial they say :

When the application runs in IIS on your development computer, the application accesses the database by using the default application pool's credentials. However, by default, the application pool identity does not have permission to open the databases. So you have to run a script to grant that permission. In this section you create the script that you'll run later to make sure that the application can open the databases when it runs in IIS.

That means it's the application that has the rights right? Not the actual user? Don't know how to solve this...

If I look into SSMS, in my PrincipalServerDB properties, authorizations show WebExploitUser as defined.