We have an ASP.NET Web Api application which uses OAuth Bearer Tokens for authentication, for which we are trying to implement Request/Response logging.

Basically it works like this:
1. User sends request to "/authenticate" and receives an authentication token
2. User then uses this authentication token for requests to the exposed API methods

For logging requests to the exposed API methods, we use a DelegatingHandler which works perfectly fine.

However, requests made to "/authenticate" are not captured by the DelegatingHandler implementation.

Is there a different approach required for logging requests for tokens?

public abstract class MessageHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var correlationId = Guid.NewGuid();

        var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri);

        var requestContent = await request.Content.ReadAsByteArrayAsync();

        var context = ((HttpContextBase)request.Properties["MS_HttpContext"]);

        await IncomingMessageAsync(correlationId, request.Method, request.RequestUri, request.Headers, requestContent, 
            context.Request.UserHostAddress, context.Request.IsAuthenticated, context.User.Identity.Name);

        var response = await base.SendAsync(request, cancellationToken);

        byte[] responseMessage;

        responseMessage = await response.Content.ReadAsByteArrayAsync();

        await OutgoingMessageAsync(correlationId, response.StatusCode, response.Headers, responseMessage);

        return response;
    }

    protected abstract Task IncomingMessageAsync(Guid correlationId, HttpMethod requestMethod, Uri requestUri, HttpRequestHeaders requestHeaders, byte[] messageContent, string ipAddress, bool isAuthenticated, string requestMadeByUserName);
    protected abstract Task OutgoingMessageAsync(Guid correlationId, HttpStatusCode statusCode, HttpResponseHeaders responseHeaders, byte[] messageContent);
}

EDIT w/ OAuth Code

[assembly: OwinStartup(typeof(MyApp.Infrastructure.IdentityConfig))]
namespace MyApp.Infrastructure
{
    public class IdentityConfig
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext<ApplicationIdentityDbContext>(() => ApplicationIdentityDbContext.Create(ConfigurationDataProvider.MYDBCONNSTRING));
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
            {
                 Provider = new ApplicationAuthProvider(),
                 AllowInsecureHttp = true,
                 TokenEndpointPath = new PathString("/Authenticate")
            });
        }
    }
}

I want to add OData syntax for querying my application's data. I don't want to fully implement ODataController, but have ApiController and implement one GET action that will support OData queries, as described here: Supporting OData Query Options in ASP.NET Web API 2

Example of what I want to have:

public class LetterEntity
    {
        public int Id {get; set;}

        public string Title {get; set;}

        public string Content {get; set;}

        public string Source {get; set;}

        public DateTime SendingTime {get; set;} 

        public string AnotherWierdString {get; set;
        ...
    }

    public class LetterDTO
    {
        public int Id {get; set;}

        public string Title {get; set;}

        public string LetterContent {get; set;}

        public string Source {get; set;}

        public DateTime SendingTime {get; set;} 
    }

    public class LetterInsideFolderDTO 
    {
        public string Title {get; set;}

        public string Source {get; set;}
    }


public class LettersController : ApiController
{           
    // Is there a way to do something like the following?:  
    [HttpGet]
    [Route("api/letters")]
    [EnableQuery]
    public IQueryable<LetterInsideFolderDTO> Get(ODataQueryOptions<LetterDTO> query) 
    { 
        IQueryable<Letter> letters = db.Letters;

        var queryOnEntites = // Convert the query to work on the entities somehow? - This is where I need help!!

        var afterQuery = query.ApplyTo(letters)

        IQueryable<LetterInsideFolderDTO> dtos = afterQuery.ProjectTo<LetterInsideFolderDTO>(afterQuery)

        return dtos;
    }
}

Because of the fact that at the moment I take Entity model directly in the clients query, there is a strong coupling between clients and server. For example if i want to query and get all the letters that has "abc" inside the Content field, I need to route to the following:

api/letters/?$filter=contains(Content,'abc')

If tomorrow I decide to change that property from "Content" to "LetterContent" all clients code will be broken.

How can I surpass it?

I am trying to append following code in div but validation is not working in mvc.I am using model binding

$("#addQuestion").on("click", function () {

        str = '<input type="hidden" name="Questions.Index" value="abc" />'
        str = str +'clause'
        str = str + ' <input type="text" value="" name="Questions[abc].Clause" id="Questions[abc].Clause" data-val-required="The Clause field is required." data-val="true" class="text-box single-line">'
        str = str +' <span data-valmsg-replace="true" data-valmsg-for="Questions[abc].Clause" class="field-validation-valid"></span>'
        str = str + '<span class="field-validation-error" data-valmsg-for="Questions[abc].Clause" data-valmsg-replace="true"></span>'
        str = str +' question'
        str = str + '  <input type="text" value="" name="Questions[abc].Question" id="Questions[abc].Question" data-val-required="The Question field is required." data-val="true" class="text-box single-line">'
        str = str + ' <span data-valmsg-replace="true" data-valmsg-for="Questions[abc].Question" class="field-validation-valid"></span>'


      //  str = str + '<span class="field-validation-error" data-valmsg-for="Questions[abc].Question" data-valmsg-replace="true"></span>'
        alert(str);
       // alert(id);
       // str = "Question<input type='text' id='txtquestion" + id + "' name='txtquestion" + id + "'/><br/>Clause<input type='text' id='txtclause" + id + "' name='txtclause" + id + "'/><br/><br/>";
        $("#countQuestion").val(id)
        id = id + 1;
        $("#content").append(str);
    });
<div id="content"> </div>

where as Question and Clause is Required in model class

The sample wizard is like this:

<asp:Wizard ID="wizRegistration" runat="server" DisplaySideBar="false" NavigationButtonStyle-CssClass="hide">
                    <WizardSteps>
                        <asp:WizardStep runat="server" title="Step 1">
dropDown1 here and a button1
                        </asp:WizardStep>
<asp:WizardStep runat="server" title="Step 2">
dropDown2 here based on dropDown1 value
                        </asp:WizardStep>
                    </WizardSteps>
                </asp:Wizard>

I want to databind a dropdown control in wizard control, based on the selected value in the previous step.

on button1 click, i have this code,

dropDown1.DataSource = SomeSource;
dropDown1.DataBind();

But it is not working. Why ?

I am currently working on a C# asp.net website that has a File Upload control, a grid view, a "Image Name" textbox and a "Upload" button. The functionality of this webpage is to use a file upload to upload an image which is sent to a sql database. The grid view then displays the image ID, Image Name, and the Image from the database. I have successfully completed that portion of the project. However, my problem now is I want users to only be able to see the uploads that they have selected rather than all the images that are stored on the database... I strictly want the latest entry from the database to show on the grid view! How would I be able to do this???? Thank you!

I´m developing an application with Visual Studio Enterprise 2015 Update 2 MVC 5 where i need to check the users login credentials via a LDAP server. I have set up a LDAP server using Apache Directory Studio.

Now im trying to connect to the LDAP server i have set up and check the credentials of a user that is stored in the server. I´m using the code from Microsofts tutorial : https://msdn.microsoft.com/en-us/library/ms257181(v=vs.80).aspx

I´m using the standard MVC project provided by Microsoft and wrote some code within the HomeController:

....

public ActionResult About()
   {
       ldap();
       ViewBag.Message = "Your application description page.";

       return View();
   }

....

// static variables used throughout the example
    static LdapConnection ldapConnection;
    static string ldapServer;
    static NetworkCredential credential;
    static string targetOU; // dn of an OU. eg: "OU=sample,DC=fabrikam,DC=com"

    public void ldap()
    {
        try
        {
            // Create the new LDAP connection
            ldapServer = "LDAP://localhost:10389";
            ldapConnection = new LdapConnection(ldapServer);
            credential = new NetworkCredential("cbrunato", "c2VjcmV0", "example.com");
            ldapConnection.Credential = credential;
            ldapConnection.Bind();
        }
        catch (Exception e)
        {
        }
    }

When i trigger the method by clicking "About" in the Webbrowser i get an exception after Bind() is executed, that the LDAP server is not available, even though it is running in Apache Directory studio. Apache Directory Studio

I´m very thankful for any help.

Hello I am fairly new to asp.net. I was wondering how to write a boolean method that will check the inputted textbox value and check to see if the input was already placed in another sql table. I have many sql tables that have foreign keys connecting them to one another.

For example say I have a table for all the customers the store gets and the primary key is customer id. Then I have another table that shows all the customers that come in only on Saturdays, one of the columns being customer id and there is a foreign key that connects the ids of the two tables together. If I am trying to add another customer to the list of customers that only comes on saturday how do I write a boolean method that will check textbox values to see if customer id already exists in the table with all the customers?

I am trying to configure an area to use some custom JSON esrializer settings for a newly created area in an ASP.Net project.

Unfortunately, I cannot affect the entire project (lots of legacy code), else I would have just done:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.Converters = new List<JsonConverter>() { new StringEnumConverter() };

But I can change this new area however I see fit.

Is it possible to configure this one new area (there are other areas I don't want affected, as well) in a similar way as the code above?

I am trying to show/hide html tag based on the cookie value. I can do this by assigning ID to that anchor tag and set its display none in javascript but I want to this in html only.

Example code:

Get the CompanyName from cookie.

$(document).ready(function () {
   var companyName = getCookie("GlobalCompanyName"));
});

Want to do something like this.

<div class="coach_title_row">
  <% if (companyName == "XYZ" )
  { %>
     <a class="new" href="<%= this.ResolveUrl("~/")%>Reports/Tool/Step1.aspx" title="Create New Report"><img src="<%= this.ResolveUrl("~/")%>Static/V3/Images/ReportingTool/new_report.png"/></a>
<% } %>
</div>

I know how to do this using jQuery but I just don't want to use them. I am queries to know that anyhow we can use that jQuery variable inside the html for comparison (in if/else).

I am using EnumDropDownListFor in ASP.NET MVC:

 @Model.PhoneNumberType

 @Html.EnumDropDownListFor(model => model.PhoneNumberType, new {@class = "form-control"})

This does not pre-select the value of the enum in the drop down list. If I just Display the enum value it will Show the right enum value. The DropDown is always set to the first value in the drop down, but not to the value of the enum field.

How can I configure EnumDropDownListFor to pre-select the drop down with the value of the enum field?

We're experiencing an issue with ASP.Net runtime compilation.

At the start (and after restarts) of the IIS, user controls and layouts compile just fine without any problem. But at some point during the lifecycle, the runtime compilation simply stops working. A restart of the IIS process makes it work again.

After searching through a myriad of different posts, we've done some extra debugging, but we are still stumped as to what causes our problem.

To keep this to the point, I'll skip explaining all tests we have done, and jump right to what I believe is closest to the heart of the error.

We have switched our compilation.tempDirectory to a custom folder used exclusively by this web application, and we have set a procmon to see all file changes in this folder. Once the error starts occuring we can see that the temporary files are actually written to this drive, and csc.exe is started (and during this, conhost.exe, CcmExec.exe and many other processes), we see no errors in procmon, but after csc.exe has run, it deletes the temporary files without leaving the compiled versions. (and the asp.net error screen shows us csc.exe failed, but not exactly what failed). The temporary files are all created (except for the resulting dll) - .0.cs, .1.cs, .tmp, .cmdline, .out, .err are all there for a short time. But immediatly after creation, they're all deleted again, and the application cannot find them.

Does anyone have any clue as to what causes this to fail after the process has run for a while? The exact same file compiles just fine if we run it just after an IIS restart, but after a while it seems that something during the runtime compilation fails, causing the ASP/w3wp/csc process to delete all signs of the temporary files, not creating the dll, and making the functionality fail.

 Try

            If Not MyCache.GetInstance.AzureCacheOn Then
                reader = New IO.StreamReader(FilePathUtility.GetInstance.MapPath(objUrl))
            Else

                request = System.Net.HttpWebRequest.Create(objUrl)
                response = DirectCast(request.GetResponse, System.Net.HttpWebResponse)
                strm = DirectCast(response.GetResponseStream, IO.Stream)
                reader = New IO.StreamReader(strm)
            End If

            Dim list = New List(Of String)()

            Using reader
                Dim line As String
                While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
                    list.Add(line)
                End While
            End Using


            lines = list.ToArray()



        Catch ex As Exception
            Throw ex
        End Try



 Private Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
        target = value
        Return value
    End Function

I have this code snippet which is working fine but now in csv file i need to add some information in first line so i need to skip the first line how I can do that please help screenshot of csv is attachedFirst Line skip

I am working on angular application, i am using asp.net mvc(not .html page). in which i need dynamic menu + routing + i want to remove # from url. how to use .cshtml page as templates?is it possible?

i am using angular 1.5.0

i already tried below mentioned solutions but its not working for me. http://csharp-video-tutorials.blogspot.in/2016/02/remove-from-url-angularjs.html (this solution working fine for html templates but not for cshtml)

Is angular routing template url support for .cshtml file in ASP.Net MVC 5 Project?

please let me know if any one has solution for this problem.

Many Thanks.

in my project cookies value not set,i can't understand why,where the problem i cant find out .please help

 [HttpPost]
    public ActionResult sellerLogin(string userid,string password)
    {

        int count = db.sellers.Count(p => p.userId == userid && p.password == password);
        if (count == 1)
        {
            HttpCookie selleruserid = new HttpCookie("selleruserid");
            selleruserid["selleruserid"] = userid.ToString();
            selleruserid.Expires = DateTime.Now.AddDays(220);
            Response.Cookies.Add(selleruserid);                
            return View("loginSuccess");
        }


        return View();
    }

loginSuccess() Action result is

 public ActionResult loginSuccess()
    {
        HttpCookie selleruserid = Request.Cookies["selleruserid"];
        if (selleruserid != null)
        {
            ViewBag.userid = selleruserid["selleruserid"].ToString();

        } 


        return View();
    }

loginSuccess() View contain

@ViewBag.userid

but when control goes to loginsuccess then viewbag showing blank...

After I've added the reference for the tag helpers in the razor views, following this tutorial.

The issue the reference add another method that has the same signature and at the end the compiler doesn't know which signature to choose, telling me that I have an ambiguous call.

enter image description here

I've added to my project.json file the following dependencies:

"Microsoft.AspNet.Razor": "4.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Razor": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc":"1.0.0-rc1-final"

//And this is the code where I'm getting the error:
services.Configure<AppOptions>(opt =>
{
    opt.ApiHost = "http://localhost:2934/";
});

Any Ideas?

I'm trying to write a code in VS2012 where I can type in a username, tick project checkboxes in a table, and submit. It will then insert that username with each project in a database table. I tried doing something like this but it won't insert.

I'm trying to add new rows into a table called SectionAccess. So if an ID "group1" checks 3 projects (with link 1,2,3) respectively, it will insert 3 rows into the table, ('group1','1'), ('group1','2'), ('group1','3').

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Admin Console";

    var db = Database.Open("Testreporting");
    var sql_c = "select Link, PPMID, EPRID, Proj_Name from AdminConsole;";
    var addgroup = "insert into SectionAccess (Access, UserID, Link) values ('user', '" + Request["UserID"] + "','" + Request["add"] + "');";
    var temp = "";
    var Link = "";
    var r_group = Request["UserID"];
    int counter = 0;

    if (!Request.Params["add"].IsEmpty())
    {
        foreach(var row in db.Query(sql_c)){
            if (Request["add"+Link]=="True")
            {
                db.Execute(addgroup);
            }
        }
    }
}

<form name ="NewGroup" method="get" >
    <fieldset>
        <legend>Add New Group</legend>

        <h6>Step 1:</h6>
        <label for ="NewGroupID">Enter New Group ID: </label>
        <input type="text" name= "UserID" value="@Request.Form["UserID"]" />

        <h6>Step 2:</h6>
        <p>Add Desired Project: </p>

        <table>      
        <tr>
        <th >#</th>
        <th >PPMID</th>
        <th >EPRID</th>
        <th >Project Name</th>
        <th >Add</th>
        </tr>

        @foreach (var row in db.Query(sql_c)) {
        counter++;

        <tr class="@temp">

            <td><br />
                    @row.Link
            </td>

            <td><br />
                    @row.PPMID
            </td>

            <td ><br />
                    @row.EPRID
            </td>

            <td ><br />
                    @row.Proj_Name
            </td>

            <td><br /><input type="checkbox" id="checkbox" name="add@(row.Link)" value="@row.Link"/></td>

        </tr>            
        }
        </table>

        <br /><input style="float:right;font-weight:bold" type="submit" onclick="return confirm('Are you sure you want to add?')" id="add" name="add@(Link)" value="@Link"/>Add Project<br />

        <div class = "home">
            <br /><a href="@Href("~/AdminConsoleHome.cshtml")">Back to Homepage</a>
        </div>

    </fieldset>


</form>

What I'm doing wrong here?

The following razor

@Html.DropDownList("ForeignKeyId", null)

or

@Html.DropDownListFor(model => model.ForeignKeyId, null)

picks up the select list items from my Entity Framework models, using the foreign key. In the foreign entity I happen to have a property call Name which is being used for the Text and the Id is being used for the Value.

This appears to be voodoo.

How is this wired up? Are there any conventions to be followed? Was it pure luck that I had a Id and Name property?

I have 4 Action results

public ActionResult Parent1 ()
{
    ViewModel VM = new ViewModel ();      
    return View(VM);
}

[HttpPost]
public ActionResult Parent1(ViewModel VM)
{           
    return View(VM);
}

[ChildActionOnly]
public ActionResult PortfolioComposition(ViewModel VM)
{
    string UserId = "UserId1";
    VM.PortfolioUserName = "ac";
    VM.PList = new List<PortfolioBar>();
    PortfolioBar bar = new PortfolioBar();
    bar.Category = "a";
    bar.InstrumentName = "a";
    bar.Weight = "c";
    bar.XyzStats = "d";
    vm.PortBarList.Add(bar);
    return View(vm);
}

[ChildActionOnly]
public ActionResult Partial2(ViewModel VM)
{
    return View(VM);
}

In view Model

public class ViewModel
{
    public String PortfolioUserName { get; set; }
    public List<PortfolioBar> PortBarList = new List<PortfolioBar>();
}

public class PortfolioBar
{
    public string InstrumentName { get; set; }
    public string Category { get; set; } 
    public string Weight { get; set; } 
    public string XyzStats { get; set; }
}

Parent View

@using (Html.BeginForm())
{
    @{ Html.RenderAction("Partial1", "Home", new { vm = Model }); }
    <div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Search" class="btn btn-default" />
    </div>
}  

Partial1 View

@foreach (var item in Model.listvm)
{
    @{ Html.RenderAction("Partial2", "Home", new { vm = Model }); }
}

partial2 View

@TextBoxFor(m => m.weight)

Everything is public in above code. I want to get value of weight on postback to parent controller. I don't know how to do it. May be I am doing something wrong. Is it fine that I am doing it with same object? or do I need to use another object ? But then how will I merge those two objects on post back?

I'm generating rows dynamically, I've added an ID value to <tr> tag, therefore each generated row has got the same ID. The problem is when I try to hide and show these rows, it's only hiding and showing the first row, even though there are many more.

 <tr style="color: lightgrey; display: none" id="deletedTrainingRecords">
                        <td>@d</td>
                        <td>@e.TrainingDate.ToShortDateString()</td>
                        <td>@e.DateAdded.ToShortDateString()</td>
                        <td>@e.AddedBy</td>

                        <td class="@cls[0]"></td>
                        <td>
                            <a class="fa fa-flag-o" style="cursor: default" title="Deleted Record"></a>
                        </td>
                    </tr>

I have created a form for add comment. I have created it in main View called Index in Home controller. bellow is Index View

private projectDBEntities db = new projectDBEntities();
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        return View();
    }

    public ActionResult AddComment()
    {
        return PartialView("_Comment");
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddComment(comment cmt)
    {
        if (ModelState.IsValid)
        {
            db.comments.Add(cmt);
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
        return PartialView("_Comment", cmt);
    }

below is _Comment Partial View

@using (Html.BeginForm()) {@Html.AntiForgeryToken()@Html.ValidationSummary(true)
<fieldset>
    <legend>comment</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.cmd_content)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.cmd_content)
        @Html.ValidationMessageFor(model => model.cmd_content)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.t_email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.t_email)
        @Html.ValidationMessageFor(model => model.t_email)
    </div>
    <p>
        <input type="submit" value="Comment" />
    </p>
</fieldset>}

System.Web.HttpException was occuerd. I want to know What is the reason behind this error and what is the best method to form submit using partail View.

I've read that ASP.NET MVC can be used together with AngularJS, but why would you do that? ASP.NET MVC offers MVC pattern at server-side, and AngularJS offers MVC pattern at browser-side. I would fully understand if the case would be to use AngularJS at browser-side and ASP.NET WEB API at server-side, for integrating to database and external systems.

Or is the point in ASP.NET MVC + AngularJS to use only basic Ajax capabilities of AngularJS, and not even try to implement the MVC pattern at browser-side, much like you would use ASP.NET MVC + jQuery?