I have a REST API which must get a file from a remote URL in AWS servers. The file is downloaded but when I try to open it, it shows nothing, like corrupted.

No exceptions are thrown

the code is this

[HttpPost]
        [Route("api/[controller]/UploadFileToAzureStorage")]
        public async Task<IActionResult> GetFile([FromBody]PDF urlPdf)
        {
            string localFilePath = CreateTemporaryFile(urlPdf.urlPDF);

            // Create storage account
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageAccount);

            // Create a blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Get a reference to a container named "mycontainer."
            CloudBlobContainer container = blobClient.GetContainerReference(UploaderStorage.Container);

            // Get a reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

            // Create or overwrite the "myblob" blob with the contents of a local file
            // named "myfile".
            using (var fileStream = System.IO.File.OpenRead(localFilePath))
            {
                await blockBlob.UploadFromStreamAsync(fileStream);
            }

            return Ok();
        }


        /// <summary>
        /// Creates temporary file
        /// </summary>
        /// <param name="urlPdf">PDF URL</param>
        /// <returns>Returns path of the new file</returns>
        private string CreateTemporaryFile(string urlPdf)
        {
            Uri uri = new Uri(urlPdf);
            string filename = default(string);
            //if (uri.IsFile)
            //{
                filename = System.IO.Path.GetFileName(uri.LocalPath);
            //}

            try
            {
                using (var client = new HttpClient())
                {
                    using (HttpResponseMessage response =
                        client.GetAsync(urlPdf, HttpCompletionOption.ResponseHeadersRead).Result)
                    {
                        response.EnsureSuccessStatusCode();

                        using (Stream contentStream = response.Content.ReadAsStreamAsync().Result, fileStream = new FileStream(@"\\pc030\TemporaryPDF\"+ filename,
                            FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                        {
                            var buffer = new byte[8192];
                            var isMoreToRead = true;
                            do
                            {
                                var read = contentStream.ReadAsync(buffer, 0, buffer.Length).Result;
                                if (read == 0)
                                {
                                    isMoreToRead = false;
                                }
                                else
                                {
                                    fileStream.WriteAsync(buffer, 0, read);
                                }
                            }

                            while (isMoreToRead);
                        }
                    }
                }

                return @"\\pc030\TemporaryPDF\" + filename;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

I am expermenting with writing my own custom role provider in asp.net. The goal here is to provide some really basic role checking specifically for the security trimming of sitemap files for menus. We use our own authentication scheme rather than a membership provider primarily because this application has been upgraded from .net 2.0 to 4.5.

The question is, how to get this all to come together. I have added the necessary directives to the web.config file:

<roleManager enabled="true" defaultProvider="MYRoleProvider">
  <providers>
    <clear />
    <add name="MYRoleProvider" type="MyProject.MYRoleProvider" applicationName="/" />
  </providers>
</roleManager>
<siteMap enabled="true">
  <providers>
    <clear/>
    <add siteMapFile="Web.sitemap" name="AspNetXmlSiteMapProvider" type="System.Web.XmlSiteMapProvider" 
        securityTrimmingEnabled="true"/>
  </providers>
</siteMap>

and added the necessary coding to this method for the custom provider:

    public override string[] GetRolesForUser(string username)
    {
        string[] Roles = { "Role1", "Role2" };
        return Roles;

    }

    public override bool IsUserInRole(string username, string rolename)
    {
       return rolename=="Role1";
    }

I have put breakpoints in these functions and they are never hit. The menu acts like the logged in user has no access to the admin folder. The admin folder's web.config is:

<configuration>
    <system.web>
      <authorization>
        <allow roles="Role1" />
      </authorization>
    </system.web>
</configuration>

What may I be doing wrong here? Perhaps I cannot user a custom role provider without a custom membership provider?

I should also point out that

User.IsInRole("Role1")

returns true so its seeing the role provider in the programming but not in the menu trimming.

This question already has an answer here:

is there a possibility to change the time format in boundfield? I get from SQL time values in the format hh:mm:ss and h:m:s

A solution would be to convert it per SQL Query but maybe there is a solution via C# or HTML, too?


Why is it marked as a dulicate? It's a different to How to fix date format in ASP .NET BoundField (DataFormatString)?, because it's about a time value not a date value. And

<asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:dd-M-yyyy}" />

seems not to be the solution.

I want to write something in an existing pdf. I have done so far =>

public void certificate()
{
    //get user info using UserId from database
    //UserDetail UserDetail = db.UserDetails.Where(x => x.UserId == UserId).FirstOrDefault();
    string oldFile = Server.MapPath("~/Content/img/tsms/Certificate/Certificate-of-Completion-Award-Template-Blue.pdf");
    string newFile = Server.MapPath("~/Content/img/tsms/Certificate/newFile.pdf");

    // open the reader
    PdfReader reader = new PdfReader(oldFile);
    Document document = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10);
    document.SetPageSize(PageSize.A4);

    // open the writer
    FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
    PdfWriter writer = PdfWriter.GetInstance(document, fs);
    document.Open();

    // the pdf content
    PdfContentByte cb = writer.DirectContent;

    // select the font properties
    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.SetColorFill(BaseColor.DARK_GRAY);
    cb.SetFontAndSize(bf, 8);

    // write the text in the pdf content
    cb.BeginText();
    string text = "Some random blablablabla...";
    // put the alignment and coordinates here
    cb.ShowTextAligned(1, text, 520, 640, 0);
    cb.EndText();

    // write the text in the pdf content
    cb.BeginText();
    text = "Other random blabla...";
    // put the alignment and coordinates here
    cb.ShowTextAligned(2, text, 100, 200, 0);
    cb.EndText();

    // create the new page and add it to the pdf
    PdfImportedPage page = writer.GetImportedPage(reader, 1);
    cb.AddTemplate(page, 0, 0);

    // close the streams and voilá the file should be changed :)
    document.Close();
    fs.Close();
    writer.Close();
    reader.Close();
}

This is working. My problem is: the document I provide old document is in landscape mode. I want the new document to be in landscape mode. But this provides me the pdf in portrait mode. So i try.....

update 1 =>

document.SetPageSize(PageSize.A4.Rotate());

This is also not working ..

Also the new text I am adding into old pdf in showing under the old page ...

means -(pdf snapshot below).... My New Pdf SnapShot and my OLD PDF oldpdfFile AND NEW PDF (CREATED)-newpdfFile

I have tried searching the msdn and google but unable to find any sources that specifically touches on this question. At the moment I can only assume A JSON is used.

If so then I guess the SQL server would process the query received, and send the results in a JSON format back to the web app. Which also leads me to ask, is the query also sent to the SQL Server in a JSON format?

Any thoughts?

I have the following javascript code in my view in MVC:

$("#summaryTotals").load('@Url.Action("GetLevelTotals", "Summary", new { level = Model.level, scenarioID = Model.selectedScenarioID}) ');

which leads to this in the controller:

public PartialViewResult GetLevelTotals(string level, int scenarioID)

The parameters come through as null.

However when I change the parameters around to this, it works:

$("#summaryTotals").load('@Url.Action("GetLevelTotals", "Summary", new {scenarioID = Model.selectedScenarioID, level = Model.level}) ');

public PartialViewResult GetLevelTotals(int scenarioID, string level)

Why is that?

We're setting up an existing Web API server to serve site(s) alongside an existing API. I have been loosely following this article.

Here's what my Global.asax.cs looks like:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        AutoMapperConfig.RegisterMappings();

        var host = new WebHostBuilder()
           .UseKestrel()
           .UseWebRoot("wwwroot")
           .UseIISIntegration()
           .UseStartup<Startup>()
           .Build();

        host.Run();
    }
}

and Startup.cs:

public partial class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseDefaultFiles();
        app.UseStaticFiles();
    }
}

When I run the project, I get the error

Unable to load DLL 'libuv': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

libuv is a dependency of Kestrel. If I manually copy it from the packages folder to the bin folder, it works. That seems to make sense with this GitHub Issue comment. Now that project.json is being moved away from, how can I get it to copy automatically?

Some have posited that it does not know whether to use 32 or 64 bit version of libuv because the Platform is set to Any CPU in the project properties. I have tried setting it to x64 in both the solution and project settings and the problem persists.

How can I make libuv.dll copy directly to the build directory automatically?

I do not consider including the file in the project (instead of in the packages folder) and setting it to copy to the output directory a real solution, only a workaround. I'm hoping to find a solution, not a workaround.

I am a beginner to OAuth2. Within our company we have written an authentication microservice which authenticates any Windows users and returns a Bearer token.

In the ASP.net Web API project that I am working on, I need to implement OAuth2 and I should use the authentication microservice mentioned above.

How do I setup the Oauth sepcifically OAuthAuthorizationServerOptions? How do I redirect the users if they are not authenticated to the microservice? Do I need an AccountController to redirect the users to the microservice?

A sample code will be helpful.

I want to achieve is same as this https://codepen.io/SitePoint/pen/Kpager but with chartjs v2. I cannot apply it as its using earlier version of chartjs. I am showing here how my bar graph is created. Also data is obtained with json using ajax:

$(document).ready(function () {
   $.ajax({
          type: 'GET',
          url: 'Data_List',      
          dataType: 'json',
          success:  function (data) {                                   
                var label_array= [];           
                var data1 = [];
                var data2= [];           
                for (var i in data) {
                    label_array.push(data[i].UserNames);                                                       
                    data1.push(data[i].User_Data1);
                    data2.push(data[i].User_Data2);                
                }
          var chartdata = {
                  labels: label_array,
                  datasets: [
                        {
                            label: 'Data 1',
                            xAxisID: 'xAxis1',
                            yAxisID: "yAxis1",                                                
                            hoverBackgroundColor: 'rgba(209, 0, 0, 1)',
                            hoverBorderColor: 'rgba(0, 0, 0, 0.75)',
                            backgroundColor: 'rgba(209, 0, 0, 1)',
                            borderColor: 'rgba(0, 0, 0, 1)',
                            borderWidth: 0.8,                        
                            data: data1                     
                        },
                        {
                            label: 'Data 2',
                            xAxisID: 'xAxis1',
                            yAxisID: "yAxis2",
                            backgroundColor: 'rgba(0, 250, 0, 0.75)',
                            borderColor: 'rgba(0, 0, 0,1)',
                            borderWidth: 0.8,                    
                            hoverBackgroundColor: 'rgba(0, 250,0, 1)',
                            hoverBorderColor : 'rgba(0, 0, 0, 0.75)',                                                      
                            data: data2                     
                        }
                    ]
                };

        var barGraph_options = {                          
                      scales: {                        
                        xAxes: [{
                            id: 'xAxis1',
                            categoryPercentage: 0.2,
                            barPercentage: 1.0,
                            type: "category",                               
                            display: false,                            
                            gridLines: {
                                lineWidth: 0,
                                color: "rgba(255,255,255,0)"
                            }}],
                        yAxes: [{
                            id: "yAxis1"                           
                            },
                        {
                            id: "yAxis2",
                            display: false,                                                           
                        }]
                    }                                           

                };
var ctx = $("#bar_chart_canvas");
var barGraph = new Chart(ctx, {
        type: 'bar',
        data: chartdata,
        animationSteps: 15,
        responsive: true,
        options: barGraph_options
                });

function move_bars() {
                    barGraph.data.datasets[0].data = deadline_date;
                    barGraph.data.datasets[1].data = num_of_days;
                    barGraph.data.labels = prj_name;

                    barGraph.data.labels.shift();
                    barGraph.data.datasets[0].data.shift();        
                    barGraph.data.datasets[1].data.shift();

                    barGraph.data.labels = prj_name;
                    barGraph.data.datasets[0].data = deadline_date;
                    barGraph.data.datasets[1].data = num_of_days;
                    barGraph.update();                        
                }
                    setInterval(function () {                          
                        move_bars();                           
                    }, 4000);
  }
     ,
    error: function (jqXHR, textStatus, errorThrown) {

        $("#cap_error").modal('show');
    }

});

What happens is that all bars move to the left with right time interval and disappear one by one and then it ends without restarting with the same data again. Is the code wrong or I'm applying wrong logic. If any one can help please I'm stuck here for many days. Thanks.

I have 2 tables. One table contains employee specialty and capacity information. The other table contains daily work amount for each specialty. How can I write query (or queries) to distribute work amount based on employees' capacity in each specialty, no matter if the work amount is more or less than the capacities? Work amount is fixed values, employees' capacity can be adjusted to match the work amount but should be adjusted according to the capacity ratio. My target result table shows this "adjustability".

Table 1: Employee_Capacity

Employee    Specialty   Daily_Capacity
---------------------------------------
Aron Baker  DB2         10
Aron Baker  Oracle       5
Aron Baker  SQL Server  10
Justin Ross DB2         20
Justin Ross SQL Server  30
Tom White   DB2          5
Tom White   Oracle      10
Tom White   SQL Server  10

Table 2: Daily_Work

Specialty   Daily_Total
------------------------
DB2             30
Oracle          10
SQL Server     100

I'm looking for a result data table where all specialty's total daily works are appropriately distributed to employees based on their daily capacity:

    Employee    Specialty   Daily_Work
    -------------------------------------
    Aron Baker  DB2          7
    Aron Baker  Oracle       3
    Aron Baker  SQL Server  20
    Justin Ross DB2         16
    Justin Ross SQL Server  60
    Tom White   DB2          7
    Tom White   Oracle       7
    Tom White   SQL Server  20

I tried the following code to change the date to end of the month on month change, but date is not changing.

here is my aspx code:

<div class="input-group date toDatePicker" id="toDate">
      <asp:TextBox ID="txt_todate" runat="server" TabIndex="2" class="form-control toDatePicker" placeholder="Select Date"></asp:TextBox>
            <span class="input-group-addon">
               <span class="glyphicon glyphicon-calendar"></span>
            </span>
</div>

and js used is:

$('.toDatePicker').datepicker({
                        orientation: "bottom left",
                        minViewMode: 1,
                        maxViewMode: 4,
                        autoclose: true,
                        format: "mm/dd/yyyy",                                                        
                    }).on('changeMonth', function (value) {

                        var endDate = new Date(value.date);

                        var mm = endDate.getMonth() + 1; //January is 0!
                        var yyyy = endDate.getFullYear();
                        var dd = endDate.daysInMonth(mm, yyyy);
                        if (dd < 10) {
                            dd = '0' + dd;
                        }
                        if (mm < 10) {
                            mm = '0' + mm;
                        }
                        endDate = new Date(yyyy, mm, dd);
                        $('.toDatePicker').datepicker('setDate', endDate).datepicker('update');

                    });
                    function daysInMonth(month, year) {
                        return new Date(year, month, 0).getDate();
                    };

I am develop a e commerce site.

Here the code for pass parameter from shopping cart (data table) to Order database.

        Dim con As SqlConnection
    con = New SqlConnection("Data Source=NBK012\ARPASQL;Initial Catalog=aCommerceDB;Integrated Security=True")
    con.Open()
    Dim cmd As New SqlCommand("INSERT INTO [aOrdini] (ID,NomeProdotto,PrezzoProdotto,Quantità,NumeroOrdine) values(@ID,@NomeProdotto,@PrezzoProdotto,@Quantità,@NumeroOrdine)", con)
    cmd.Parameters.AddWithValue("@ID", GridView1.Rows(0).Cells(1).Text)
    cmd.Parameters.AddWithValue("@NomeProdotto", GridView1.Rows(0).Cells(2).Text)
    cmd.Parameters.AddWithValue("@PrezzoProdotto", GridView1.Rows(0).Cells(3).Text)
    cmd.Parameters.AddWithValue("@Quantità", GridView1.Rows(0).Cells(4).Text)
    cmd.Parameters.AddWithValue("@NumeroOrdine", TextBox9.Text)
    cmd.ExecuteNonQuery()
    con.Close()

And this work fine but only with one item in the shopping cart. First question, how can i iterate that code ? so as pass all the shopping cart to order db. The second thing is that the order number arrive from another database that i use as counter. So i don't need to iterate the order number because all item in shopping cart has the same shopping number

Thanks for the help guys.

I tried to implement a new function in one of my programs. This feature allows to add and edit project overviews. I'm using a One-To-Many Foreignkey in the database where a "Project" has one project leader (User) and one "User" has many project leads (Project). Now in the web API the code actually reaches the "return Ok(projectList);". But on the client it says internal server error. I think it has something to do with the foreign key because the User class did already exist before I implemented the new feature. When I debug the API there aren't any errors and the propertys "ProjectLeader" and "ProjectLeads" are not null. What am I doing wrong here?

Here's the code:

User.cs

public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
public string Username { get; set; }
[Required(AllowEmptyStrings = false)]
public string PasswordHash { get; set; }
[Required(AllowEmptyStrings = false)]
[EmailAddress(ErrorMessage = "Invalid email format")]
public string EMail { get; set; }
[Required(AllowEmptryStrings = false)]
public DateTime Birthdate { get; set; }
public bool IsConfirmed { get; set; }
public bool FirstLogin { get; set; }
[Required(AllowEmptyStrings = false)]
public int ActivationCode { get; set; }
public UserRole UserRole { get; set; }
public byte[] ProfilePicture { get; set; }
public UserGroup UserGroup { get; set; }
public virtual ICollection<Project> ProjectLeads { get; set; }

Project.cs

public int Id { get; set; }
[Required(AllowEmptryStrings = false)]
[ForeignKey("ProjectLeader_Id")]
public virtual User ProjectLeader { get; set; }
[Required(AllowEmptyStrings = false)]
public string ProjectName { get; set; }
[Required(AllowEmptyStrings = false)]
public string GameTitle { get; set; }
[Required(AllowEmptyStrings = false)]
public string Description { get; set; }
public ProjectState ProjectState { get; set; }
public bool IsPC { get; set; }
public bool IsMac { get; set; }
public bool IsAndroid { get; set; }
public bool IsIOS { get; set; }

UserRole, UserGroup and ProjectState are enums.

The Method where I download the list of projects:

[HttpGet]
public IHttpActionResult GetProjects()
{
    var db = new DataBaseContext();

    try
    {
        if (db.Projects.Any())
        {
            var projectList = db.Projects.ToList();
            return Ok(projectList);
        }
        else
            return Ok(new List<Project>());
    }
    catch (Exception ex)
    {
        log.Fatal($"Ein Fehler ist aufgetreten beim Runterladen der Projekte: {ex.Message}", ex);
        return BadRequest();
    }
}

("Ein Fehler ist aufgetreten beim Runterladen der Projekte" means "An error occured while downloading the projects")

If it is important here's the DataBaseContext.cs:

public class DataBaseContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<License> Licences { get; set; }
    public DbSet<Project> Projects { get; set; }
}

I searched through multiple tutorials on websites or in books I have at home. I did it exactly like they said. Am I missing something?

I have a view named Index, and 2 partial views _Grid and _Project. The partialview _Project is a pop-up which is visible once the user clicks on the button to add data, think of it like adding a user. Now, I am trying to change a textbox value which is inside the partial view _Grid once the user click on the button inside the _Project pop-up.

Inside the _Grid partialview:

<input id="CurrentOrder" type="hidden" value=""/>

In javascript once the button inside the pop-up(partialview _Project) is pressed:

function AddTimeReg() {
//code 
if (date && shopdoc && ((convertedStartTime && convertedEndTime) || hours)) {
        $.ajax({
// more code 
// change the value of textbox
 $("#Grid #CurrentOrder").val(salesorder);

The input type is inside the Grid partialview in a div named Grid.

What exactly am I doing wrong here? I want the textbox have the value of salesorder.

I am looking to find the difference in days of two ajax calendar extenders that are linked to two separate text boxes. code snippet

I have completed this task using the asp calendar control previously but I am having issues when trying to achieve this using the ajax calendar extension.

the label output is stating " the two dates are 0 days apart " for numerous tested dates.

I would appreciate if anyone could give any guidance/help or let me know where i am going wrong.
Thanks!

I have a controller marked with [Route("api/entities")]. There is a method for getting all entities:

[Audit(ActionType.EntityList)] // custom annotation for audit
[Authorize]
[HttpGet]
public IActionResult GetEntities()
{
    // ...
}

As you can see, by using annotations I save the request to some audit and authorize the request only to allowed users.

Now, I want to enhance this endpoint so it can return the top N entities. Example request: /api/entities?top=5. I have found that I should use an optional parameter for the method and use if to detect the case.

However, I need to save such call in audit as differnt type (e.g. [Audit(ActionType.EntityTop)]) and I do not need an authorization there (everyone can fetch the top entities).

How can I map the /api/entities request to one method and /api/entities?top=N to another? In Spring from Java I would use a params field of @RequestMapping.

I do not want to change the URL of this endpoint, because the top parameter modifies only the list that is being returned so one should use GET parameters for that. By having the same URL I also do not change the semantic meaning of the response (it is still list of the same entities). It is important when using RESTful frontend framework like Restangular.

Again, after tiresome attempts to solve this annoying issue, I am back here. I am experiencing an "Object moved here" on my view in my MVC5 application after some return RedirectToAction("Index", "Roles", model); action on my controller.

I have considered solutions from the following links:

  1. RedirectToAction and "Object moved to here" error

  2. ASP.NET MVC Website: Object Moved to Here

  3. https://forums.asp.net/t/1643235.aspx?+Object+moved+to+here+problem but none are applicable to my problem.

Before anyone marks this as a duplicate, please consider the scenario below:

But now the weird thing is that after I have clicked on the 'here' link and it now renders my view - it has a horizontal split screen showing the correct display of my view on top and below the view that throws an Http Error Code - in this case its Error Code 500 : Internal Server Error.

The reason why I am getting the http status code error is due to this unanswered question here (one of many) :

Failed to load resource: Uncaught TypeError: $(...).select2 is not a function

But that is besides the point right now.

Controller:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Name,Description")] ApplicationRole model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var role = new ApplicationRole()
                    {
                        Name = model.Name,
                        Description = model.Description
                    };

                    var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
                    var result = await roleManager.CreateAsync(role);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Index", "Roles", model);
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //Below is my index method in my Roles controller which is the action that redirection needs to route to:

        [Route("/Roles")]
        public ActionResult Index()
        {
            if (TempData["StatusMessage"] != null)
            {
                ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
            }
            else
            {
                ViewBag.StatusMessage = "";
            }

            var roles = db.Roles.ToList();
            return View("Index", roles);
        }



        //GET method to create view
        public ActionResult Create()
        {
          return View();
        }

View:

@model IEnumerable<User_Manager_Interface.Models.ApplicationRole>
@{

    Layout = "~/Views/Shared/_Layout.cshtml";
}


@if (ViewBag.StatusMessage != null)
{
    if (ViewBag.StatusMessage != "")
    {
        string tmp = ViewBag.StatusMessage;
        if (tmp.Contains("error"))
        {
            <div class="notification msgerror">
                <a class="close"></a>
                <p>@ViewBag.StatusMessage</p>
            </div>
        }
        else
        {
            <div class="notification msgsuccess">
                <a class="close"></a>
                <p>@ViewBag.StatusMessage</p>
            </div>
        }
    }
}

<br />
@Html.ActionLink("Create New", "Create", "Roles", new object { }, new { @class = "stdbtn" })
<br />
<br />

<div class="contenttitle radiusbottom0">
    <h2 class="table"><span>Roles</span></h2>
</div>

<table cellpadding="0" cellspacing="0" border="0" class="stdtable" id="dyntable">
    <colgroup>
        <col class="con0" />
        <col class="con1" />
        <col class="con0" />

    </colgroup>
    <thead>
        <tr>
            <th class="head1">Name</th>
            <th class="head0">Description</th>
            <th class="head1">Options</th>

        </tr>
    </thead>
    <tfoot>
        <tr>
            <th class="head1">Name</th>
            <th class="head0">Description</th>
            <th class="head1">Options</th>
        </tr>
    </tfoot>
    <tbody>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Description)
                </td>

                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                </td>
            </tr>
        }
    </tbody>
</table>

@section Scripts {
    @Scripts.Render("~/bundles/tables")
}

Model:

    public class ApplicationRole : IdentityRole
    {
        [Display(Name = "Description")]
        [StringLength(100, MinimumLength = 5)]
        public string Description { get; set; }
    }

"Error" Controller:

    public class ErrorController : Controller
    {
        //
        // GET: /Error/
        public ActionResult Index(int statusCode, Exception exception)
        {
            Response.StatusCode = statusCode;
            return View();          
        }
    }

"Error" View:

@{
    ViewBag.Title = Response.StatusCode;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2 style="visibility:hidden">@ViewBag.Title</h2>

<div class="errorWrapper">
    <h2>An internal server error @ViewBag.Title has occurred</h2>
    <h1 class="pageErrorTitle" style="color:red">Error @ViewBag.Title - Page Not Found</h1>
    <h3 style="color:black">You may have clicked an expired link or mistyped the address.</h3>
    <br />
    <a class="default" href="javascript:history.back()">Back to Previous Page</a> &nbsp; <a class="default" href="http://localhost:53648">Return to Dashboard</a>
</div>

Please see screenshots for more visual clarity:

Landing page to create a new role

enter image description here

After role has been added

JavaScript error associated with create new role landing page

I want to retrieve student attendance from razor view to controller. In one row I want to access Radio Button value. And there are many rows. How can I access all rows data at once and send it to the controller?

My Razor view is:

 <table class="table">
                        <thead class="thead-inverse">
                            <tr>

                                <th>Full Name</th>
                                <th>Roll No</th>
                                <th>Status</th>

                                @*  <th>Status</th>*@
                            </tr>
                        </thead>
                        <tbody>
                            @using (@Html.BeginForm("Save", "Attendance", FormMethod.Post, new { @class = "form-horizontal" }))
                            {

                                foreach (var student in Model.Students)
                                {
                                    <tr>
                                        <td>@student.Name</td>
                                        <td>@student.RollNo</td>
                                        <td>

                                            <div data-toggle="buttons">
                                                <label class="btn btn-success active">
                                                    <input type="radio" name="options" id="1" autocomplete="off" checked> Present
                                                </label>
                                                <label class="btn btn-danger">
                                                    <input type="radio" name="options" id="2" autocomplete="off" checked> Absent
                                                </label>
                                                <label class="btn btn-primary">
                                                    <input type="radio" name="options" id="3" autocomplete="off" checked> On Leave
                                                </label>
                                                <label class="btn btn-warning">
                                                    <input type="radio" name="options" id="4" autocomplete="off" checked> Short Leave
                                                </label>
                                            </div>
                                        </td>
                                    </tr>

                                }
                                <div class="form-group">
                                    <div class="col-lg-10 col-lg-offset-2">
                                        <button type="submit" class="btn btn-success">Submit</button>
                                    </div>
                                </div>

                            }
                        </tbody>
                    </table>

I attached a screen shot of my web page so that you can see what I want to achieve.

My Web Page View

im trying to print a google chart using textsharp. The only step I don't know how to perform is how to set the value using jquery on the web client side and be able to read it from code behind. Does anybody know how to do this?

I have an asp button that performs a client click and a server click:

<asp:ImageButton ID="btnPDF" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/images/acroread.png" OnClick="btnPDF_Click" OnClientClick="return ExportToPDF(this)" ToolTip="Download PDF" ClientIDMode="Static"/>

This is the on client click event to set to the hidden field the image value from the chart:

$("[id*=btnExport]").click(function () {
$("input[name=chart_data]").val(div_chart.getImageURI());
});

This is how I am trying to get the hiddenfield value on c# codebehind (but keeps on getting null values):

string base64 = Request.Form["chart_data";

:)

I've just installed Microsoft Visual Studio 2017 Community and try to get heads up on the newest technology.

I'm not that familiar with MVC yet and definitely not familiar with EF Core 1.1.

I've taken a couple of courses on Pluralsight on ASP.NET Core and EF Core, but it seems there have been changes since these recordings where made.

When I run "Add-Migration Inital" to connect with the database, I always get :

System.InvalidOperationException: The entity type 'Category' requires a primary key to be defined.

at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message) at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model) at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model) at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value() at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_01.b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) The entity type 'Category' requires a primary key to be defined.

Here are some relevant code:

Category.cs

public class Category
{
    [Key]
    public int CategoryId;
    public String CategoryName;
}

ICategoryRepository.cs

namespace Dokumentbasen6.Model { public interface ICategoryRepository { IEnumerable Categories { get; } Category GetCategoryById(int CategoryId); } } CategoryRepository.cs

public class CategoryRepository : ICategoryRepository { private readonly DokumentbasenContext _context;

    public CategoryRepository(DokumentbasenContext context)
    {
        _context = context;
    }

    public IEnumerable<Category> Categories => _context.Categories;

    public Category GetCategoryById(int CategoryId)
    {
        return _context.Categories.FirstOrDefault(c => c.CategoryId == CategoryId);
    }
}

DokumentbasenContext.cs public class DokumentbasenContext : DbContext { public DokumentbasenContext(DbContextOptions options) : base(options) {

    }
    public DbSet<Document> Dokuments { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Standard> Standards { get; set; }
    public DbSet<Member> Members { get; set; }
}

When I build the project I used the target framework .NETCoreApp 1.0, but I have now changed target Framework to .NetCoreApp 1.1.

In advance, thank you very much for your support!

Kind regards,

Jon Haakon Ariansen