I have the following code in ASP.Net Generic handler to download the file.

// generate you file
// set FilePath and FileName variables
string stFile = FilePath + FileName;
try {
    response.ContentType = "application/pdf";
    response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
} catch (Exception ex) {
    // any error handling mechanism
} finally {

it works fine with local path - like "D:\Files\Sample.pdf" or "\localserver\Files\Sample.pdf".

but it throws and access denied error while trying to access the Network file share like "\anotherServer\Files\Sample.pdf".

Does it related to double hopping? If can I use spsecurity.runwithelevatedprivileges to fix this issue? or what are the other options?

As per this article https://weblogs.asp.net/owscott/iis-windows-authentication-and-the-double-hop-issue it seems to be a double hopping issue. How do I address this? All I want is that end user should be able to download remote resources by using asp.net generic handler.

I have converted my .docx file to html using Open XML PowerTools in c# asp.net. In my word file I have multiple headings(h1,h2,h3 etc). I want them as divs e.g.

<div id = h1>
  <p> some text <p>
  <div id = h2>
    <p> some additional text</p>

but what I'm getting is as below

<h1 dir="ltr" class="pt-000026"><span lang="en-GB" class="pt-000027"></span><a id="_Toc485046534" class="pt-000018"></a><span lang="en-GB" class="pt-DefaultParagraphFont-000028">Safety Control</span></h1>
<p dir="ltr" class="pt-Normal-000004"><span lang="en-GB" class="pt-DefaultParagraphFont-000012">This section will describe the safety features of the control system to ensure safe operation.</span></p>
<h2 dir="ltr" class="pt-000029"><span lang="en-GB"></span><span lang="en-GB">C_100</span><span lang="en-GB" class="pt-DefaultParagraphFont-000030">Power and Safety System Group Monitor</span></h2>

The aim is to convert all information in readable form so that some of information could be stored in database. I have tried saving .docx file as html but it results the same.

Also, I have tried saving .docx file as zip, and converted xml to JSON but i don't get JSOn as word document is laid out (multiple headings).

This is how it looks in word file, and I want similar layout in html

If you could put me in right direction that would be great.

I'm trying to get working the NLog with target to Elasticsearch in my asp.net web API application.

The .net framework version of my application is 4.6.

I'm using Elasticsearch, Nest.net and Elasticsearch.NET V. 5.6.

NLog.Targets.ElasticSearch V 3.0.0

NLog 4.4.3

Following is my NLog.config

<?xml version="1.0" encoding="utf-8" ?>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
        xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
    <add assembly="NLog.Targets.ElasticSearch"/>
          fileName="Nlog.txt" />

    <target name="elastic"
      <target xsi:type="ElasticSearch"
              layout="${logger} | ${threadid} | ${message}"

        <field name="user"
        <field name="host"

    <logger enabled="true" name="*" minlevel="Debug" writeTo="logfile" />
    <logger enabled="true" name="*" minlevel="Debug" writeTo="elastic" />

In the API I have a method for testing the log entry.

private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public HttpResponseMessage Hello()
            _logger.Info("Hello World!!!!!!!!!!!!");
            _logger.Trace("Sample trace message");
            _logger.Debug("Sample debug message");
            _logger.Info("Sample informational message");
            _logger.Warn("Sample warning message");
            _logger.Error("Sample error message");
            _logger.Fatal("Sample fatal error message");
            return Request.CreateResponse(HttpStatusCode.OK, "Hello World!");

I can see the Log entry in the Nlog.txt file but nothing in Elasticsearch. I downloaded the NLog.Targets.ElasticSearch project and attached to my application in order to debug it. Debugging it, I can see in the following code

private void SendBatch(ICollection<AsyncLogEventInfo> events)
                var logEvents = events.Select(e => e.LogEvent);

                var payload = FormPayload(logEvents);

                var result = _client.Bulk<byte[]>(payload);

                if (!result.Success)

that result.Seccess is equal true. So no exceptions, but I don't se the log index to be created. The web API already works properly with Elasticsearch.

Can someone help me to understand what is wrong? Did I miss something? Thanks in advance for your time.

I have a typical endpoint for updating an entity

public IHttpActionResult Patch([FromODataUri] int key, Delta<Individual> patch)

Individual has a non-nullable int property StatusId. When "" is passed in, it properly throws the error:


  "statusId": ""


    "error": {
        "code": "",
        "message": "Request contains validation errors.",
        "details": [
                "target": "patch",
                "message": "",
                "innerError": {
                    "message": "Cannot convert the literal '' to the expected type 'Edm.Int32'."

However when I pass in null, it doesn't give a validation error, and the Delta object does not list it as a changed property.


  "statusId": null

Expected Response

    "error": {
        "code": "",
        "message": "Request contains validation errors.",
        "details": [
                "target": "patch",
                "message": "",
                "innerError": {
                    "message": "Cannot convert null to the expected type 'Edm.Int32'."

We want to be able to validate and return an error when they pass in null for a non-nullable field, not just silently ignore the error.

How would I accomplish this?

I am using below code to place a call from agent(Web Browser interface) to customer(phone).

var response = new VoiceResponse();
var dial = new Dial(callerId: callerId,action : "https://ba2d9819.ngrok.io/voice/CallEnd");
if (Regex.IsMatch(to, "^[\\d\\+\\-\\(\\) ]+$"))


This works fine when customer picks up the call. I have a requirement to play a prerecorded audio message when customer do not pickup the call and it goes to voicemail. How can i achieve this?

Attempting to get a Jquery UI dialog to confirm (OK, Cancel) a call to a delete operation (DeleteTestUser). My jquery ui dialog is coming up on click. The cancel button works as expected but OK is not.

The error (Uncaught TypeError: Illegal Invocation) is what Chrome is showing in the console when I click OK. This is probably not surprising since it doesn't know what testUser.TestUserId is...

How do I ultimately pass that value along from client to server? The delete operation from HomeController.cs otherwise does work without the confirmation dialog. I need to get OK to call that. I feel like I am close but not sure how to form the Url.Action post in Javascript.

I'm pretty sure the problematic line is the post in _layout.cshtml


    <script type="text/javascript">
    $(document).ready(function() {

                title: 'Test User',
                draggable: false,
                resizeable: false,
                closeOnEscape: true,
                modal: true,
                autoOpen: false,
                buttons: {
                    'Cancel': function() {
                    'OK': function() {
                        $.post("@Url.Action("DeleteTestUser", "Home")",
                            { id: $('testUser.TestUserId') });


        $('#confirm-delete').click(function () {


    public ActionResult DeleteTestUser(int id)
        return this.RedirectToAction("Index");


    @foreach (var testUser in this.Model)
                <a href="@Url.Action("TestUser", "Home",
                        new {id = testUser.TestUserId})">
                    <i class="fa fa-pencil fa-lg text-primary"></i>
                <a href="#" id="confirm-delete" >
                    <i class="fa fa-trash fa-lg text-primary"></i>

I have been staring at this problem for a few days now and still I can't understand what's going on. It's probably something really trivial but I can't find the correct assistance on existing questions. I have the following Razor Html:

<div class="modal-body">
            @using (Html.BeginForm("Index", "Study", FormMethod.Post))
                <div class="row">
                    <div class="col-sm-12">
                        <div class="radio">
                            <label><input type="radio" name="Mhd" value="1"> Yes</label><br />
                            <label><input type="radio" name="Mhd" value="0"> No</label>
                <div class="row">
                    <div class="col-sm-12">
                        <label>What is your Gender</label>
                        <div class="radio">
                            <label><input type="radio" name="Gender" value="1"> Male</label><br />
                            <label><input type="radio" name="Gender" value="0"> Female</label>
                <div class="row form-group">
                    <div class="col-sm-12">
                        <label for="age">Age:</label>
                        <select class="form-control" name="Age" id="age">
                            @for (int count = 16; count <= 130; count++)
                <div class="g-recaptcha" data-sitekey="6LcRHE0UAAAAALRTlf_wvx2Si6VxU7oZS3mCfyqS"></div>
                <br />
                <button type="submit" value="Index" class="btn btn-primary float-right" data-dismiss="modal">Start</button>
                <button type="button" class="btn float-left" data-dismiss="modal">Cancel</button>

My controller will be doing something more complex but in the meantime, i am just trying to bind to the following action in a different controller called StudyController.cs :

    public async Task<IActionResult> Index()
    { return View(); }

In my post action, I simple put the simple code as follows:

public ActionResult Test()
   Session["mykey"] = DateTime.Now.ToString("HH:ss");
   return View();

In debugging, when I clicked on the submit button, the Session contained correct value. But when I submitted again, the Session did not contain "mykey"(Session["mykey"] is null). This did not happen if I removed Thread.Sleep method or set the short time (e.g. System.Threading.Thread.Sleep(10000))

The config setting in my application is as follows:

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" 
         host="myhost.cache.windows.net" port="6380" 
         ssl="true" />

Could you please give me your ideas? Thank you!

In an ASP.NET project I'd like to save and retrieve the configuration from another server. The appsettings is saved as a file in a asp.net project. However, I'd like the configuration saved to an external server. This way I can retrieve the configuration across several projects. Is this possible with either asp.net or asp.net core?


We have been experiencing a rogue CurlException being thrown without a very meaningful stack trace in an dotnetcore 2 ASP.NET app. We think this code is being caused by an HttpClient POST request being sent from one of our background processing threads, but we are not able to capture the exception to pinpoint the error.


  • .NET Core 2.1.4
  • Host: Ubuntu 16.04 (Xenial) on an Azure Scale Set

Exception info (from Application Insights)

problemId: System.Net.Http.CurlException at System.Net.Http.CurlHandler.ThrowIfCURLEError
type: System.Net.Http.CurlException
assembly: System.Net.Http, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
method: ystem.Net.Http.CurlHandler.ThrowIfCURLEError
outerType: System.Net.Http.HttpRequestException
outerMessage: An error occurred while sending the request.
outerAssembly: System.Private.CoreLib, Version=, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
outerMethod: System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
innermostType: System.Net.Http.CurlException
innermostMessage: Couldn't connect to server
parsed stack trace:
{"assembly":"System.Net.Http, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Net.Http.CurlHandler.ThrowIfCURLEError","level":0,"line":0}
{"assembly":"System.Net.Http, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Net.Http.CurlHandler+MultiAgent.FinishRequest","level":1,"line":0}

Additional Info

  • We have not been able to figure out how to capture this exception before Application Insights sends it (we've tried using an ITelemetryInitializer and an ITelemetryProcessor to no avail)
  • This seems to be intermittent (or at least temporal to our cluster is fully starting and all endpoints being available)
  • We are overriding the server certificate validation for requests sent within our Azure VNET using the ServerCertificateCustomValidationCallback.

I am using this code to display summernote editor on my page

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-lite.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-lite.js"></script>
<textarea id="summernote" name="summernote">@Model.InviteEmailBody</textarea>
                        tabsize: 4,
                        height: 220
                    $('#summernote').on('summernote.blur', function () {


Then saving to database

string str = Request.Form["summernote"];
string htmlEncoded = WebUtility.HtmlEncode(str);
roleToUpdate.InviteEmailBody = htmlEncoded;

Everything is fine when I actually edit the content, but when i don't, the value I fet in str variable has a lot of


I am not sure if the way I implemented summernote is correct or how would I fix this problem.. if anybody can help I would appreciate it

I've added an HTML audio element and changed the source of audio on button click using C# code. Now I want to control the audio play/pause. How would I control the play/pause of this HTML audio element using ASP code?

HTML Audio element

<div runat="server" id="myDivTag">
    <audio autoplay runat="server" id="myaudio">
        <source src="" runat="server" type="audio/mpeg">
        <p>If you can read this, your browser does not support the audio element.</p>

ASP Code to control the audio

string ety ="http://audio.oxforddictionaries.com/en/mp3/ranker_gb_1_8.mp3";

 myaudio.Src = ety;

<asp:GridView ID="CompanyGridView" runat="server" BackColor="#2d437d" 
            BorderWidth="1px" DataKeyNames="CompanyID"
            DataSourceID="SqlDataSource1" ForeColor="White" Height="16px" 
             Style="margin-top: 300px; margin-left: 30px;"
            Width="1100px" ShowFooter="True" EmptyDataText="No record found" 
            RowStyle-BackColor="#cccccc" RowStyle-ForeColor="black" 
            AllowPaging="True" AutoGenerateColumns="false"
            OnRowCommand="CompanyGridView_RowCommand" >
                        <asp:Button ID="InsertButton" runat="server"  
                              CommandName="Insert" Text="Insert New Record" 
                               CssClass="button" />
                        <th colspan="6">
                        <asp:LinkButton Text="Details" runat="server" 
                         CommandName="Details" />
                 <asp:BoundField HeaderText=" " />
                 <asp:BoundField DataField="CompanyID" HeaderText="CompanyID" 
                 ItemStyle-Width="150" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" 
                ItemStyle-Width="150" />
                <asp:BoundField DataField="BusinessPhone" 
                 HeaderText="BusinessPhone" ItemStyle-Width="150" />
                <asp:BoundField DataField="CompanyCode" HeaderText="CompanyCode" 
                ItemStyle-Width="150" />
                <asp:BoundField DataField="Status" HeaderText="Status" 
               ItemStyle-Width="150" />


Hi I am having problem in Gridview control my CompanyID and its data from datasource are being displayed in different columns. I want them to have in same column. The problem is CompanyID is showing nothing while Company Name is showing data of CompanyID and so on.

I have this problem where i need to call Controller x3 times from view but it depends on how many checkboxes are checked in view. View is calling controller's pdf view, each checkbox have true or false values.

Let's say I've got an asp:button on a website which I'm trying to track to count how many times it has been clicked by different users.

 <asp:Button ID="SubBtn" runat="server" OnClick="Button1_Click" runat="server" Text="Sub" />

In my code behind I've got a redirect link to a different page.

I'm aware that I need to include something like

<a href="#" name="button1" onclick="dataLayer.push({'event': 'button1-click'});" >Button 1</a>

Do I need to convert my asp:button to a html button to make this work?

I found solutions telling me to use something like this (in system.web) to a make custom error page:

<customErrors mode="On" defaultRedirect="~/home">
  <error redirect="~/home/page_not_found" statusCode="404" />

and this (in system.webServer):

  <httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" subStatusCode="-1" />
    <remove statusCode="500" subStatusCode="-1" />
    <error statusCode="404" path="Error404.html" responseMode="File" />
    <error statusCode="500" path="Error.html" responseMode="File" />

I tried both of these methods and none of them seemed to work. I'm not sure if I have to delete things in in system.web and `system.webServer, or if I'm suppose to make Routes to the controller in which I want the error messages to be displayed in, so I am going to show you what I have


  <compilation debug="true" targetFramework="4.5.2" />
  <httpRuntime targetFramework="4.5.2" />
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />


  <validation validateIntegratedModeConfiguration="false" />
    <remove name="ApplicationInsightsWebTracking" />
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />


      <add assembly="System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />


  <modules runAllManagedModulesForAllRequests="true" />
    <remove name="BlockViewHandler"/>
    <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />


public class HomeController : Controller
    public ActionResult PageNotFound()
        Response.StatusCode = 404;
        return View();
    public ActionResult InternalServerError()
        Response.StatusCode = 500;
        return View();

My question is this: "What do I do to get my program to redirect to the error pages using the solution above?"

Side Note: if you need my Route.Config, here it is:

public static void RegisterRoutes(RouteCollection routes)


I see several versions of this question, but none of them has had a solution that works for me. I have two places I need to access the current, logged in users data. One is in an asp-route-id on an cshtml view page and the other is in a controller.

  1. Is there a way to access the current user data in a view? Something like asp-route-id=@currentusersid and what would it look like?

  2. How can I just call the current ApplicationUser's Id?

    public IActionResult Add(int id) { ApplicationUser user = ; List<Model> models= context.Models.ToList(); //This line works return View(new AddUsersBillerViewModel(user, billers)); }

I'm kinda new at this and I am running out of resources. Any assistance would be hugely appreciated.

am using jquery dataTable in mvc to display records. now there is one column Icon in my category table which contains names of font awsome icon classes like "fa fa-plus". now what i want is to display icons instead of these classes names when displaying records to users

this is my jquery datTable code

$(document).ready(function() {
  dataTable = $("#categoryTable").DataTable({

    "ajax": {
      "url": "/Category/GetData",
      "type": "Get",
      "datatype": "json"
    "columns": [

        "data": "CategoryName"
        "data": "Description"
        "data": "Icon"
        "orderable": false,
        "searchable": false,
        "width": "150px"
    "language": {
      "emptyTable": "No Data Found Plese Click <b>Add Category</b> Button"

This question already has an answer here:

This is my code and here am geting this error "System.NullReferenceException: 'Object reference not set to an instance of an object.'" This is run-time error and _DefaultRepo its showing NULL.

public class DefaultController : Controller
        // GET: Default
        private readonly IDefautlRepository _DefaultRepo;

        private readonly LoginRepository _Login;

        public DefaultController()


        public DefaultController(IDefautlRepository DefaultRepo, LoginRepository Login)
            this._DefaultRepo = DefaultRepo;
            this._Login = Login;

        public ActionResult Index()
            return View();

        public JsonResult GetGroupId (string EmailId , string Password)
                string _emailId;
                string _password;
                MT_UserDetails User= new MT_UserDetails();                
                _emailId = EmailId;
                _password = Password;

                User = this._DefaultRepo.GetGroupId(_emailId, _password);              
                Session["GroupId"] = User.GroupId;
            catch (Exception e)
                throw e;
            return Json(false, JsonRequestBehavior.AllowGet);

I'm working with a KendoGrid that looks like this:

  .Filterable(f => f.Mode(GridFilterMode.Menu).Extra(false))
      columns => {
          columns.Bound(c => c.Batch).Filterable(f =>f.UI("$.proxy (ShedGridFilter, {field: 'Batch'})"));
          columns.Bound(c => c.Shed).Filterable(f =>f.UI("$.proxy (ShedGridFilter, {field: 'Shed'}))"));
  .Scrollable(s => s.Height("350px"))
  .Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
  .DataSource(datasource => datasource
  .Model(model =>
        model.Id(i => i.ShedId);
        model.Field(f => f.Batch).Editable(false);
        model.Field(f => f.Shed).Editable(false);
  .Read(read => read.Action(MVC.MilkFeedShed.ActionNames.MilkFeedShed_Read, MVC.MilkFeedShed.Name).Data("selectedDateGetter"))
  .Update(update => update.Action(MVC.MilkFeedShed.ActionNames.MilkFeedShed_Update, MVC.MilkFeedShed.Name).Data("selectedDateGetter"))
  .Sort(s => s.Add("ChangeTime").Descending())

The JavaScript for the filters is shown below:

function MilkFeedGridFilter(element) {
    var grid = "ShedGrid";

    var fieldName = this.field;
    var gridDataItems = $("#" + grid).data("kendoGrid").dataSource.data();
    var listDataItems = [];
    for (var i = 0; i < gridDataItems.length; i++) {
        if (gridDataItems[i][fieldName] !== null && $.inArray(gridDataItems[i][fieldName], listDataItems) < 0) {

            dataSource: {
                data: listDataItems


This setup creates a DropDownList in each of the KendoGrid filter columns, but I don't know how to give them a name, so that I can find them using another function later on, basically I want to translate the following into JavaScript:

      //.DataSource(List in JavaScript)

i have a problem with my single Page Application, maybe anone can help me. The Problem is simple. When i start my Project with the keyuser.html as first site(home page) the Table from the connected Database is shown with the Data. When i use the normal home.html as entry Point for my Programm, i can click the Hyperlink to my keyuser.html file, the controller does the necessary routing and i am on my keyuser.html site. But here is just the update Button, but not my Table with my Data. Has anyone an idea for me. Already tried some stuff. Maybe i missed something here... please feel free to ask me details an other information necessary. Hope anyone can help me!

+++++++++ keyuser.html ++++++

<!DOCTYPE html>
<button onclick="update()">Update</button>

<div id="flexGrid"></div>

var cv = new wijmo.collections.CollectionView();
var flexGrid = new wijmo.grid.FlexGrid('#flexGrid');

flexGrid.itemsSource = cv;
// Get Data
wijmo.httpRequest("/api/Colors", {
    success: function (xhr) {
        cv.sourceCollection = JSON.parse(xhr.response);

++++++++++++ control.js ++++++++++++++

 var app = angular.module("myApp", ["ngRoute"]);

 app.config(function ($routeProvider) {
    .when("/keyuser", {
    templateUrl: "keyuser.html"

++++++++++++ home.html ++++++++++++++

 <!DOCTYPE html>
 <script src="http://cdn.wijmo.com/5.latest/controls/wijmo.min.js"></script>
 <script src="http://cdn.wijmo.com/5.latest/controls/wijmo.grid.min.js"></script>
 <div ng-app="myApp">
   <a href="#!keyuser">Stammdaten</a>
   <div ng-view></div>