.Net Core 1.0.0 - SDK Preview 2 (x64)

.Net Core 1.0.0 - VS 2015 Preview 2 (x64)

.Net Core 1.0.0 - Runtime (x64)

So, we updated an RC1 app to the latest versions above. After many hours of switching references, it's running. However, when logging in (AccountController/Login), I am getting an error at:

public class AccountController : BaseController
{
    public UserManager<ApplicationUser> UserManager { get; private set; }
    public SignInManager<ApplicationUser> SignInManager { get; private set; }
    private readonly IEmailSender EmailSender;

    public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        EmailSender = emailSender;
    }

    // GET: /Account/Login
    [HttpGet]
    [AllowAnonymous]
    public IActionResult Login(string returnUrl = null)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(ViewModels.Account.LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            // Errs this next line
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); // <-- ERRS HERE '.PasswordSignInAsync'
            if (result.Succeeded)
                return RedirectToLocal(returnUrl);

            ModelState.AddModelError("", "Invalid email or password.");
            return View(model);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

It blows up with the following error message:

InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

Here is the Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        // Add EF services to the services container.
        services.AddEntityFrameworkSqlServer()
           .AddDbContext<LogManagerContext>(options =>
              options.UseSqlServer(Configuration["Data:DefaultConnection:Connectionstring"]));

        services.AddSingleton(c => Configuration);

        // Add Identity services to the services container.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<LogManagerContext>()
            .AddDefaultTokenProviders();


        // Add MVC services to the services container.
        services.AddMvc();

        services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

        //Add all SignalR related services to IoC. - Signal R not ready yet - Chad
        //services.AddSignalR();

        //Add InMemoryCache
        services.AddMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = System.TimeSpan.FromHours(1);
            options.CookieName = ".LogManager";
        });

        // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
        // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
        // services.AddWebApiConventions();
        // Register application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();

    }

    // Configure is called after ConfigureServices is called.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSession();

        // Configure the HTTP request pipeline.
        // Add the console logger.
        //loggerFactory.MinimumLevel = LogLevel.Information; - moved to appsettings.json -chad
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        loggerFactory.AddNLog();

        // Add the following to the request pipeline only in development environment.
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
        }
        else
        {
            // Add Error handling middleware which catches all application specific errors and
            // sends the request to the following path or controller action.
            app.UseExceptionHandler("/Home/Error");
        }

        env.ConfigureNLog("NLog.config");

        // Add static files to the request pipeline.
        app.UseStaticFiles();

        // Add cookie-based authentication to the request pipeline.
        app.UseIdentity();

        //SignalR
        //app.UseSignalR();

        // Add MVC to the request pipeline.
        app.UseMvc(routes =>
        {
            routes.MapRoute(
             name: "default",
             template: "{controller}/{action}/{id?}",
             defaults: new { controller = "Home", action = "Index" }
             );

            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });
    }

And here's the Context:

public class ApplicationUser : IdentityUser
{
    // Add Custom Profile Fields
    public string Name { get; set; }
}

public class LogManagerContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<LogEvent> LogEvents { get; set; }
    public DbSet<Client> Clients { get; set; }
    public DbSet<LogEventsHistory> LogEventsHistory { get; set; }
    public DbSet<LogEventsLineHistory> LogEventsLineHistory { get; set; }
    public DbSet<LogRallyHistory> LogRallyHistory { get; set; }
    public DbSet<Flag> Flags { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {

        builder.Entity<LogEvent>().HasKey(x => x.LogId);
        builder.Entity<LogEvent>().ToTable("LogEvents");
        builder.Entity<Client>().HasKey(x => x.ClientId);
        builder.Entity<Client>().ToTable("Clients");
        builder.Entity<LogEventsHistory>().HasKey(x => x.HistoryId);
        builder.Entity<Flag>().HasKey(x => x.FlagId);
        builder.Entity<Flag>().ToTable("Flags");
        builder.Entity<LogRallyHistory>().HasKey(x => x.HistoryId);
        builder.Entity<LogEventsLineHistory>().HasKey(x => x.LineHistoryId);

        base.OnModelCreating(builder);
    }

I saw similar solutions on detecting and assigning actions when 'X' button pressed on type="search" textfield action upon pressing X button. I want to do using @Html.TextBoxFor(model => model.SearchTerm, new { id = "search-box", type = "search"}. However it cannot fire the event specifically on clearance button 'X' click.

So far I have managed to register all events:

            $('#search-box').on('click', function (e) {
            alert(e);

            System.Diagnostics.Debug.Write(e.target);
        });

Any help would be greatly appreciated

Is possible to change the view input class based on a model annotation. for instance:

[required]
[class("phone-class")]
public string Phone {get; set;}

and it would output

<input name="Phone" class="phone-class" />

I am simply trying to develop an MVC application with a worthy contact us page. All I am trying to do is create a model that asks for the users information and sends it to a certain e-mail address. I've seen tutorials on Web Forms but I'm not very good with that. This is your standard mvc web application using visual studio. The page should just ask for the users name, email address, company, phone number, email subject, and message. So far this is what I have. Is anyone familiar with this code?

here is my view

@model  Contacts.Models.Contact

@{

ViewBag.Title = "Contact Page";

}

<h2> Contact Page</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@Html.ValidationSummary(true, "Sending message was unsuccessful. Please correct the errors and try again.")


{

<h3>Your message was successfully sent!</h3>

  }

     @using (Html.BeginForm())
  {

<div>

    <fieldset>

        <legend>Contact Information</legend>

        <div class="editor-label">

            @Html.LabelFor(model => model.Name)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(model => model.Name)

            @Html.ValidationMessageFor(model => model.Name)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Email)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(model => model.Email)

            @Html.ValidationMessageFor(model => model.Email)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Phone)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(model => model.Phone)

            @Html.ValidationMessageFor(model => model.Phone)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Body)

        </div>

        <div class="editor-field">

            @Html.ValidationMessageFor(model => model.Body)

            <br />

            <textarea rows="10" cols="60" name="Body"></textarea>

        </div>

        <p>

            <input type="submit" value="Send" />

        </p>

    </fieldset>

</div>

}

Here is my Model

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Text;
 using System.ComponentModel.DataAnnotations;

  namespace Contacts.Models
  {
   public class Contact
   {
    [Required]

    [Display(Name = "Name *")]

    public string Name { get; set; }

    [Required]

    [DataType(DataType.EmailAddress)]

    [Display(Name = "Email address *")]

    public string Email { get; set; }

    [DataType(DataType.PhoneNumber)]

    [Display(Name = "Phone Number")]

    public string Phone { get; set; }

    [Required]

    [Display(Name = "Message *")]

    public string Body { get; set; }

    public DateTime SentDate { get; set; }

    public string IP { get; set; }



    public string BuildMessage()
    {

        var message = new StringBuilder();

        message.AppendFormat("Date: {0:yyyy-MM-dd hh:mm}\n", SentDate);

        message.AppendFormat("Email from: {0}\n", Name);

        message.AppendFormat("Email: {0}\n", Email);

        message.AppendFormat("Phone: {0}\n", Phone);

        message.AppendFormat("IP: {0}\n", IP);

        message.AppendFormat("Message: {0}\n", Body);

        return message.ToString();

    }
}
}

Here is my controller

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.Mvc;
 using Contacts.Models;
 using System.Net;
 using System.Net.Mail;
 using System.Collections;



 namespace Contacts.Controllers
 {
public class ContactController : Controller
{
    public ActionResult Index()
    {

        ViewBag.Success = false;

        return View(new Contact());

    }

    [HttpPost]

    public ActionResult Index(Contact contact)
    {

        ViewBag.Success = false;

        {
            try
            {

                if (ModelState.IsValid)
                {

                    // Collect additional data;

                    contact.SentDate = DateTime.Now;

                    contact.IP = Request.UserHostAddress;



                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = new System.Net.NetworkCredential
                    ("evanligon7@gmail.com", "********");

                    smtpClient.EnableSsl = true;

                    MailMessage mail = new MailMessage();
                    mail.From = new MailAddress("evanligon7@gmail.com"); // From
                    mail.To.Add(new MailAddress("evanligon7@gmail.com")); // To

                    mail.Subject = "Your email subject"; // Subject
                    mail.Body = contact.BuildMessage();



                    contact.BuildMessage(); // Body
                    ViewBag.Success = true;
                    smtpClient.Send(mail);
                }

            }

            catch (Exception e)
            {
                Response.Write("Success");

            }
        }



        return View();

    }

}
}

I need to have a custom view for an umbraco 7 form, that have a special column layout, but my problem is that I cannot output data from an umbraco field with .GetPropertyValue("formHeader")

I am rendering the form with

@Umbraco.RenderMacro("FormsRenderForm", new { FormGuid = "6189b8c2-980a-4f02-bcec-33b170020a22" })

Inside my Form.cshtml I would like to insert an umbraco field .GetPropertyValue("formHeader")

But I cannot seem to get it to work

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage 

will return

Error loading Partial View script (file: ~/Views/MacroPartials/InsertUmbracoForm.cshtml)

Is this even possible, the way I am thinking about it ?

I am using Umbraco Forms

I'd like to configure my MVC application to randomly challenge users with a 2-factor authentication check on 1-in-N visits to the site.

To start with, I just did this as part of the login:

int challengeFrequency = Convert.ToInt16(ConfigurationManager.AppSettings["ChallengeFrequency"]);
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
    case SignInStatus.Success:
        Random rnd = new Random();
        if(rnd.Next(challengeFrequency) == 1)
        {
            if (!await SignInManager.SendTwoFactorCodeAsync("Phone Code"))
            {
                return RedirectToAction("Error");
            }
            return RedirectToAction("VerifyCode", new { Provider = "Phone Code", ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        }
        return RedirectToLocal(returnUrl);
    // other cases
}

But it transpires I'd misunderstood the process, and that PasswordSignInAsync isn't called if the user has a valid cookie for the site. I was planning to change these settings so that users had to sign in every time in any case, so in Startup.Auth I added:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromSeconds(5),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromSeconds(0), 
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

So now users get challenged every time. But, of course, without a cookie, we never get a SignInStatus.Success result and the user is always challenged for both password and for a 2FA code.

How can I interrupt the process to ensure the user always has to sign in with a password, but is only occasionally asked for a 2FA code?

I've seen a number of posts about this on various sites, but I can't find an actual answer to it.

Apparently when you use dynDateTime jQuery plugin, it doesn't cooperate with Master pages. I implemented this on a test page with perfect results. When I added coding to bring in a Master page, it no longer works.

Here's my code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Defaulted.aspx.cs" Inherits="ClientDPL.WebForm2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">

    <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>  
    <script src="Scripts/jquery-ui-1.8.24.min.js" type="text/javascript"></script>  
    <script src="Scripts/jquery.dynDateTime.min.js" type="text/javascript"></script>
    <script src="Scripts/calendar-en.min.js" type="text/javascript"></script>
    <link href="Content/calendar-blue.css" rel="stylesheet" type="text/css" />

</asp:Content>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">

    <asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="2" BorderStyle="Solid" BackColor="#0f6fc6" Width="840px">
        <asp:TabPanel ID="tpMain" runat="server" HeaderText="Work Item" BackColor="#0f6fc6" BorderColor="Black">
            <ContentTemplate>
                <script type="text/javascript"> 
                    jQuery(document).ready(function() { 
                        jQuery("#txtEffDate").dynDateTime({
                            showsTime: true,
                            ifFormat: "%m/%d/%Y %I:%M:%S %p ",
                            daFormat: "%l;%M;%S %p, %e %m, %Y",
                            align: "Bl",
                            electric: false,
                            singleClick: false,
                            displayArea: ".siblings('.dtcDisplayArea')",
                            button: ".next()",
                            weekNumbers: false,
                            timeFormat: "12"
                            }); 
                    }); 
                </script> 
                The selected date is:  <br/> 
                    <asp:Panel ID="Panel1" runat="server">
                        <asp:TextBox ID="txtEffDate" runat="server" CssClass="textbox" Height="18px" Width="80px" Visible="True" Font-Size="Small" TextMode="Date" Wrap="False"></asp:TextBox>
                        <button type="button">PICKER</button>
                    </asp:Panel>
            </ContentTemplate>
        </asp:TabPanel>
    </asp:TabContainer>

</asp:Content>

I'm generating a JWT and I am using a p12 certificate file to sign it. This code works locally but deployed on AWS i get the following exception message: "The system cannot find the file specified".

Here's the code:

// Gets the projects path to App_Data/privatekey.p12
string path = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "privatekey.p12");


X509Certificate2 cert = new X509Certificate2();

// Throws System.Security.Cryptography.CryptographicException: The system cannot find the file specified
cert.Import(path, "SECRET PASSWORD HERE", X509KeyStorageFlags.Exportable); 

RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PrivateKey;

I've placed the 'privatekey.p12' file in the projects App_Data folder and included it, I've also set "Items to deploy" to "All files in this project" and I'm still getting the error.

I have a small Angular2 app built with the CLI, running through "ng s" at http://localhost:4200/ fine. I need to run it in an IIS site, in an "app" folder, so that it would be served at http://localhost/app. When I copy the dist files, after running "ng b -prod", into that app folder I am getting a variety of 404 errors. It looks like Angular is looking to the root of the web app to find resources when it should be looking in app. Here is an example URL that is not found:

http://localhost:3000/vendor/zone.js/dist/zone.js 

I have tried adding to the index.html file. I also tried changing the baseUrl for the CLI build (in environment.js) to be "/app".

What am I missing? How do I get my app to host in a sub folder of another site?

When I run the project through visual studio it works perfectly, however when I publish it to live via the file system option. it will not reference my class and as a result the page does not work. i can navigate to it but i cannot get to login because my validation for login depends on the class UserManager.

Visual Studio Community 2015 on Windows Server 2012 R2

Here is my class reference.

using UserManager;

Here is my C# Code before where it fails.

p.s. UserData.ValidateUser is highlighted light blue when i run it locally but when I attach to W3WS Process to debug it live it's white when it should be highlighted.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using UserManager;
using System.Data.SqlClient;

public partial class LoginPage : System.Web.UI.Page
{
    private static string conString = ConfigurationManager.ConnectionStrings["connStr"].ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            usernameTextBox.Focus();
        }
    }

    protected void loginButton_Click1(object sender, EventArgs e)
    {   
        UserManager.User u = UserData.ValidateUser(usernameTextBox.Text, GlobalFunctions.Encrypt(passwordTextBox.Text));

Here is the ERROR IMAGE within the C# Interactive window on my screen

Microsoft (R) Roslyn C# Compiler version 1.3.1.60621 Loading context from 'CSharpInteractive.rsp'. Type "#help" for more information.

    UserManager.User u = UserData.ValidateUser(usernameTextBox.Text, GlobalFunctions.Encrypt(passwordTextBox.Text));

. (1,9): error CS0246: The type or namespace name 'UserManager' could not be found (are you missing a using directive or an assembly reference?) (1,30): error CS0103: The name 'UserData' does not exist in the current context (1,52): error CS0103: The name 'usernameTextBox' does not exist in the current context (1,74): error CS0103: The name 'GlobalFunctions' does not exist in the current context (1,98): error CS0103: The name 'passwordTextBox' does not exist in the current context

I have website in asp.net in vb. I have made many pages which I want to perform dynamically. I have defined routes in global.asax. The problem is it gets routed to one page only hence I want them to route according to I have routed them..

Global.asax

<script RunAt="server">
    Private Sub Application_Start(sender As Object, e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub

    Private Shared Sub RegisterRoutes(routes As RouteCollection)
        routes.MapPageRoute("shop2", "{name}.aspx", "~/shop2.aspx")
        routes.MapPageRoute("DynamicPage", "{product_name}.aspx", "~/DynamicPage.aspx")
    End Sub
</script>

My Model Class is like this

  public class JobCategory
{
    public int ID { get; set; }
    public string Name { get; set; }
    [DefaultValue(0)]
    public int ParentID { get; set; }
    public string Details { get; set; }

}

Now, On my create view I want to show a drop-down list, which will show all category names whose parentID is equal to 0. I can create Linq Query to get those list of objects like this

 ApplicationDbContext db = new ApplicationDbContext();
List<JobCategory>    mainCategories = db.JobCategories.Where(x => x.ParentID == 0).ToList();

Now How can I embed this data in to an @Html.ListBoxFor ?

EDIT

Model in my razor view

@model WebApplication13.Models.JobCategory

Code In my Controller

  public ActionResult Create()
    {
        return View();
    }
 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Name,ParentID,Details")] JobCategory jobCategory)
    {
        if (ModelState.IsValid)
        {
            db.JobCategories.Add(jobCategory);
            db.SaveChanges();
            return RedirectToAction(actionName: "Index");
        }

        return View(jobCategory);
    }

I got that Error

There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCategoriesIds'.

My Model code:

   public class NewsViewModel
    {
        public int NewsId { get; set; }
        public string NewsTitle { get; set; }
        public string NewsBody { get; set; }
        public System.DateTime NewsDate { get; set; }
        public string NewsImagePath { get; set; }
        public HttpPostedFileBase NewsImageFile { get; set; }
        public int[] SelectedCategoriesIds { get; set; }

    }

My code in Controller:

var list = db.Categories.ToList();
ViewBag.CategoryList = from c in list 
                       orderby c.CategoryName 
                       select new SelectListItem 
                                 { 
                                   Value = c.CategoryId.ToString(), 
                                   Text = c.CategoryName.Trim() 
                                 };

and in Razor:

@Html.DropDownListFor(model => model.SelectedCategoriesIds,
                     (IEnumerable<SelectListItem>)ViewBag.CategoryList,
                        new 
                        { 
                          id = "dropdownOne", 
                          @class = "form-control", 
                          multiple = "true" 
                         }
                      )

When I clicks on form submit button it not hitting the controller post action method,I think the problem with layouts, I have checked removing layouts but i didn't work,please I will be thankful if anyone helps to me

View1 code:

@{
if (User.Identity.IsAuthenticated)
    {
        Layout = "~/Areas/Seller/Views/Shared/_SellerLayout.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
}
@using (html.beginform("addasset", "asset", formmethod.get, new { enctype = "multipart/form-data" }))
{  
    <a class="col-sm-1 text-right"><input type="submit" class="btn btn-primary gray-btn lineheight1" value="add assets" ></a>    
}

View2 code:

if (User.Identity.IsAuthenticated)
    {
        Layout = "~/Areas/Seller/Views/Shared/_SellerLayout.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
@using (Html.BeginForm("AddAsset", "Asset", FormMethod.Post, new  { enctype = "multipart/form-data" }))
        {
        <div class="row form-group">
            <div class="col-xs-8">
                <label class="col-sm-2 control-label" for="Email_address">*Asset Name</label>
                <div class="col-sm-10">
                    @Html.TextBoxFor(model => model.Asset_Name, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.Asset_Name)
                </div>
            </div>
        </div>
<div class="row form-group">
            <div class="col-sm-4">
                <label class="col-sm-4 control-label" for="Email_address">*Asset Type</label>
                <div class="col-sm-8">
                    @Html.DropDownList("Asset_Type_Id", AssetId, "Select", new { @class = "form-control", id = "AssetType" })
                    @Html.ValidationMessageFor(model => model.Asset_Type_Id)
                </div>
            </div>
}

controller Code:

[HttpGet]
public ActionResult AddAsset()
        {
            Asset Asset = new Asset();
            return View(Asset);
        }
[HttpPost]
        public ActionResult AddAsset(Asset collection)
        {
_context db = new _context();
db.add(collection);
db.saveChanges();
}

I have a utility where I am saving date and time in database. But my users are from different locations so I want to convert all times ti Arizona time (Phoenix, AZ (MST) using C#. How can I convert user's local time to Phoenix, AZ (MST) time ?

Regards, Asif Hameed

I generate a reset password token in one request, but then when I want to reset the password in the next request, it says invalid token.

    public async Task<string> GetResetToken(string userId)
    {
        var token = await _userManager.GeneratePasswordResetTokenAsync(userId);
        return token;
    }

    public async Task<IdentityResult> ResetPassword(string userId, string token, string newPassword)
    {
        var result = await _userManager.ResetPasswordAsync(userId, token, newPassword);
        return result;
    }

These two functions are called by their respective API endpoints. The flow of the whole process is:

1) Enter email on website

2) The API generates a token and an email gets sent with a reset link

3) The reset link takes you to a reset password page

4) The page hits the API again to reset the password

Everything works except step 4, because the API just comes back with invalid token. I've checked that the token being generated is exactly the same as the token received in step 4.

I've been debugging this the whole day.

I have an ASP.NET MVC project and a TinyMCE as an editor template, but basically the problem is that only the last TinyMCE is shown.

@Html.TextArea(string.Empty, new { id = textAreaId, value = ViewData.TemplateInfo.FormattedModelValue })

<script type="text/javascript">
    tinyMCE.init({
        mode: "exact",
        elements: "textarea#@textAreaId",
        theme: "modern",
        inline: true,
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "template paste textcolor colorpicker textpattern imagetools"
        ],
        toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
        toolbar2: "preview media | forecolor backcolor code | ltr rtl",
        image_advtab: true,
        templates: [
            { title: 'Test template 1', content: 'Test 1' },
            { title: 'Test template 2', content: 'Test 2' }
        ],
        file_picker_callback: function (callback, value, meta) {
            if (meta.filetype === 'image') {
                $('#@formId input').click();
            }
        }
    });
</script>

I'm calling the EditorTemplate like this:

@for (int i = 0; i < Model.Answers.Count; i++)
{
        @Html.EditorFor(
            model => model.Answers[i].Text,
            new
            {
                htmlAttributes = new { @class = "form-control" },
                textAreaId = string.Format("answer-textArea-{0}", i),
                formTargetId = string.Format("answer-formTarget-{0}", i),
                formId = string.Format("answer-form-{0}", i)
            })
}

So far I've been trying different modes, different selectors, even downgraded to TinyMCE 3.0 - no effect. All solutions I found so far on the Internet don't work for me. The only error I was getting in the console is that Theme is not a constructor, but since I changed to mode exact and elements in the config, even the last editor that used to be shown (probably because tinyMCE.init overrides the previous initializations or something) is not shown and so is the error. I honestly have no clue how to solve this. Any help is appreciated.

We have asp.net mvc website hosted in Azure Web Apps. Everytime we deploy the site takes literally couple of minutes to load. Also I've noticed that site generally performs slow.

When looking at BIN folder, I noticed quiet a lot of PDB files.

Wondering if this PDF files could be causing the performance issue. Any insights will be appreciated.

In my model I have a field that is a date, in my view I use the following to edit it:

@Html.TextBoxFor(m => m.Date, new { type = "date"})

While I get the proper value back in the Controller when the form is submitted, initial value is not properly set in the view (it's empty)

My view model:

    [DataType(DataType.Date)]
    public DateTime Date { get; set; }

I cannot really find what am I missing here...

We have got asp.net website.Web page is http://bargainvillasinturkey.com We are having trouble with all sublinks

Error Looks like

Error

We asked to host provider but they told its our mistake. When we try to add new web form pages there is different mistakes now

An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

This website is working on local but not working on live... If there is someone can help me I will be very thankful..

Hi I'm trying to do a filter to the page, that when it's pressed it will show only the checked items in the list

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.InUse)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model){
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.InUse)
        </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>
    }
</table>

the model.InUSE is checkbox. and I want (using jquery) to filter this list and show only the checked.

the html after rendering:

<table class="table">
                    <tr>
                        <th>
                            Name
                        </th>
                        <th>
                            InUse
                        </th>
                        <th></th>
                    </tr>

                        <tr>
                            <td>
                                foo 1
                            </td>
                            <td>
                                <input checked="checked" class="check-box" disabled="disabled" type="checkbox" />
                            </td>
                            <td>
                                <a href="/AdditivesNames/Edit/5">Edit</a> |
                                <a href="/AdditivesNames/Details/5">Details</a> |
                                <a href="/AdditivesNames/Delete/5">Delete</a>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                foo 2
                            </td>
                            <td>
                                <input checked="checked" class="check-box" disabled="disabled" type="checkbox" />
                            </td>
                            <td>
                                <a href="/AdditivesNames/Edit/3">Edit</a> |
                                <a href="/AdditivesNames/Details/3">Details</a> |
                                <a href="/AdditivesNames/Delete/3">Delete</a>
                            </td>
                        </tr>


                </table>