Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

search by selectlist not working

$
0
0

I have added a selectlist and when I build the pages and try it out, nothing happens when I choose an option in the list.

I notice that the value = part is missing from the rendered html.

<form><p>        IPE Terminal ID: <selectid="IpeTerminalIdString" name="IpeTerminalIdString"><optionvalue="">All</option><option>2500</option><option>4000</option><option>5000</option></select><br />        Transaction Sequence Number: <inputtype="text" name="SearchString"><inputtype="submit" value="Filter" /><br />        Authorization Code: <inputtype="text" name="SearchString"><inputtype="submit" value="Filter" /></p></form>

This is the code for the select:

<select asp-for="IpeTerminalIdString" asp-items="Model.IpeTerminalIdList">
            <option value="">All</option>
        </select>


This is the code for the queries, etc.

namespace VicanaPaymentAuthorizationApp.Pages.TransactionListPage
{
    public class IndexModel : PageModel
    {
        private readonly VicanaPaymentAuthorizationApp.Models.TransactionListContext _context;

        public IndexModel(VicanaPaymentAuthorizationApp.Models.TransactionListContext context)
        {
            _context = context;
        }

        public IList<TransactionList> TransactionList { get;set; }
        public SelectList IpeTerminalIdList { get; set; }
        public string IpeTerminalIdString { get; set; }
        //public async Task OnGetAsync()
        //{
        //    TransactionList = await _context.Transactions.ToListAsync();
        //}

        public async Task OnGetAsync(string IpeTerminalIdString, string searchString)
        {
           // Use LINQ to get list of genres.
            IQueryable<string> IpTerminalIdQuery = from t in _context.Transactions
                                            orderby t.IpeTerminalId
                                            select t.IpeTerminalId;
           
            var transactions = from t in _context.Transactions
                               select t;
            
            if (!String.IsNullOrEmpty(searchString))
            {
                transactions = transactions.Where(s => s.TransactionSequenceNumber.Contains(searchString));
            }

            if (!String.IsNullOrEmpty(IpeTerminalIdString))
            {
                transactions = transactions.Where(x => x.IpeTerminalId == IpeTerminalIdString);
            }

            IpeTerminalIdList = new SelectList(await IpTerminalIdQuery.Distinct().ToListAsync());

            TransactionList = await transactions.ToListAsync();
        }
    }
}

Custom validator with localization from shared resources

$
0
0

Hi all,

I'm trying to get my custom validator to work with my shared resources localization files.

That's what I got so far and it takes the default error messages instead of using mine.

Part of the model:

 [Required(ErrorMessageResourceName = "ERRRequired", ErrorMessageResourceType = typeof(Resources.SharedResource))]
        [DateFormatValidator(ErrorMessageResourceName = "ERRBadDate", ErrorMessageResourceType = typeof(Resources.SharedResource))]
        [Display(Name = "LBLBirthDate", ResourceType = typeof(Resources.SharedResource))]
        public string BirthDate { get; set; }

The DateFormatValidator

public class DateFormatValidator : ValidationAttribute, IModelValidator
    {

        public new string ErrorMessage { get; set; }



          IEnumerable<ModelValidationResult> IModelValidator.Validate(ModelValidationContext context)
          {
            DateTime outDate;

            if (context.Model != null)
            {
                string date = context.Model.ToString();

                if (DateTime.TryParseExact(date, "dd-MM-yyyy", null, System.Globalization.DateTimeStyles.None, out outDate))
                {
                    return Enumerable.Empty<ModelValidationResult>();
                }
                else
                {
                    return new List<ModelValidationResult> { new ModelValidationResult("", ErrorMessage) };

                }
            }else
            {
                return new List<ModelValidationResult> { new ModelValidationResult("", ErrorMessage) };
            }

           
            

          }
    }

The adapter:

 public class DateFormatValidatorAdapter : AttributeAdapterBase<DateFormatValidator>
    {
        public DateFormatValidatorAdapter(DateFormatValidator attribute, IStringLocalizer stringLocalizer) : base(attribute, stringLocalizer) { }

        public override void AddValidation(ClientModelValidationContext context) { }

        public override string GetErrorMessage(ModelValidationContextBase validationContext)
        {
            return GetErrorMessage(validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName());
        }
    }

And finally the adapter provider:

 public class DateFormatValidatorAdapterProvider : IValidationAttributeAdapterProvider
    {

        private readonly IValidationAttributeAdapterProvider _baseProvider = new ValidationAttributeAdapterProvider();

        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (attribute is DateFormatValidator)


                return new DateFormatValidatorAdapter(attribute as DateFormatValidator, stringLocalizer);
            else
                return _baseProvider.GetAttributeAdapter(attribute, stringLocalizer);
        }

     
    }

Why this isn't working?

How to retain the list binded with Select control after a postback call using asp-page-handler

$
0
0

I have a Select  control in my page and its is mapped with a list property in the PageModel . When am doing a post call using asp-page-handler PageModel list values  is getting cleared and I have to do a DataBase call  on that Post Method (called by the asp-page-handler) to reload the PageModel property. I tried with putting the list values in TempData and it works with smaller list data, if List data is huge then its throws an error. Is there any other possibility to retain the list. Below is the sample code I tried

Razor Page:

<select  asp-for="MyModel.Emp"  asp-items=" Model.EmpList.Select( m => new SelectListItem { Text= m.Name, Value = m.ID})"></select>

PageModel:

[BindProperty]
public List<Employee> EmpList{ get; set; }

EF Core 2.1. Generic Repository Issues

$
0
0

Hi all,

I am writing in EF Core 2.1.

I am trying to create a generic repository and having problems.

When I scaffold a controller, one of the methods is:

public IActionResult Delete(int? id)        {            if (id == null)            {                return NotFound();            }            var inventory = _context.Inventory                .Include(i => i.UOM)                .Include(i => i.Vendor)                .FirstOrDefault(m => m.Id == id);            if (inventory == null)            {                return NotFound();            }            return View(inventory);        }

I am trying to use a repository for:

var inventory = _context.Inventory                .Include(i => i.UOM)                .Include(i => i.Vendor)                .FirstOrDefault(m => m.Id == id);

This is what I have so far, but I am having problems with the FirstOrDefault part.

IGenericRepository

TEntity FindSingleOrDefaultByIdIncluding(int id, Expression<Func<TEntity, bool>> match, params Expression<Func<TEntity, object>>[] includeExpressions);

GenericRepository

public virtual TEntity FindSingleOrDefaultByIdIncluding(int id, Expression<Func<TEntity, bool>> match, 
            params Expression<Func<TEntity, object>>[] includeExpressions)
        {
            if (includeExpressions.Any())
            {
                var set = includeExpressions
                  .Aggregate<Expression<Func<TEntity, object>>, IQueryable<TEntity>>
                    (_DbSet, (current, expression) => current.Include(expression));

                return set.SingleOrDefault(match);
            }

            return GetById(id);
        }

When I try to use this code in the controller, the error I am getting is:

Not all code paths return a value for lamda expression.

Only one person gets HttpContext Null error. [Updated]

$
0
0

Hi experts,

I have an Asp.Net Core 2.1 web application running on Windows Server 2008 R2.
Everyone have access to this web app but only one person gets "System.NullReferenceException: Object reference not set to an instance of an object." forHttpContext
Weird this is, he can access the same application that running on test server which is same Windows Server 2008 R2 
I indicated the line where error out in yellow highlight in Session class code.

I spent many days to fix it, but no luck yet.

Please help, and thank you in advance.

Here is my Startup.cs:

public class Startup {
	static public IConfigurationRoot Global { get; set; }
        public IHostingEnvironment HostingEnvironment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IHostingEnvironment env, IConfiguration configuration) {
            try
            {
                HostingEnvironment = env;
                Configuration = configuration;
                this.SetGlobals(HostingEnvironment);
            }catch(Exception ex)
            {
                //If failed in here, it needs special error handler
                Helper.errorMsg msg = new Helper.errorMsg();
                Helper.CreateRfs_LostHosting(ex, -1, msg).Wait();
            }
	}

	public void ConfigureServices(IServiceCollection services) {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

	    services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromHours(12);
            });
	    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
	}


	public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
	    if (env.IsDevelopment()) {
		app.UseDeveloperExceptionPage();
		app.UseBrowserLink();
	    } else {
		app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();

            app.UseMvc(routes => {
		routes.MapRoute(
		name: "default",
		template: "{controller=Home}/{action=Index}/{id?}");
	    });

            Session.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
	}
}

I have a Session Class:

public class Session
    {
		private static IHttpContextAccessor _httpContextAccessor;

		public static void Configure(IHttpContextAccessor httpContextAccessor) {
			_httpContextAccessor = httpContextAccessor;
		}

		public static void Initialize() {
			var sessionUser = Session.GetSessionObj<SessionUser>("SessionUser");
			if (sessionUser == null) {
				sessionUser = new SessionUser();sessionUser.Initialize(HttpContext);
				Session.SetSessionObj("SessionUser", sessionUser);
			}
		}

		public static HttpContext HttpContext { get { return _httpContextAccessor.HttpContext; } }
		public static SessionUser SessionUser { get { return Session.GetSessionObj<SessionUser>("SessionUser"); } }
		public static bool UserValidated { get {
                if (SessionUser == null)
                {
                    Initialize();
                }
                return SessionUser.Validated;
            } }

		public static void SetSessionVar(string key, string value) {
			_httpContextAccessor.HttpContext.Session.SetString(key, value);
		}

		public static void SetSessionObj(string key, object value) {
			_httpContextAccessor.HttpContext.Session.SetObject(key, value);
		}

		public static T GetSessionObj<T>(string key) {
			var sessionObj = _httpContextAccessor.HttpContext.Session.GetObject<T>(key);
			return sessionObj;
		}
    }

here is SessionUser class:

public class SessionUser
    {
	public void Initialize(HttpContext httpContext) {
		string userName = null;
		var identity = httpContext.User.Identity;

		if (identity.IsAuthenticated) {
			userName = identity.Name;
		} else {
			var basicCredentials = new BasicAuthenticationHeader(httpContext);
			userName = basicCredentials.UserName;
		}
        }
    }

Added on 7/25/2018:--------------------------------------------------------------------------------------

here is BasicAuthenticationHeader.cs:

public class BasicAuthenticationHeader
    {
        private readonly string _authenticationHeaderValue;
        private string[] _splitDecodedCredentials;

        public bool IsValidBasicAuthenticationHeaderValue { get; private set; }
        public string UserName { get; private set; }

		public BasicAuthenticationHeader(HttpContext context)
        {
			var basicAuthenticationHeader = context.Request.Headers["Authorization"]
				.FirstOrDefault(header => header.StartsWith("Basic", StringComparison.OrdinalIgnoreCase));

			if (!string.IsNullOrWhiteSpace(basicAuthenticationHeader))
            {
                _authenticationHeaderValue = basicAuthenticationHeader;
                if (TryDecodeHeaderValue())
                {
                    ReadAuthenticationHeaderValue();
                }
            }
        }
}

Detail Error message from asp.net built in error log:

System.NullReferenceException: Object reference not set to an instance of an object.
at Models.SessionUser.Initialize(HttpContext httpContext) in Models\SessionUser.cs:line 24
at Models.Session.Initialize() in Models\Session.cs:line 21
at Controllers.BaseController..ctor() in Models\BaseController.cs:line 16

here is BaseController.cs:

public class BaseController : Controller
	{
		public BaseController() {
            try
            {
                Startup.UpdateGlobals(Session.HttpContext.Request);
                Session.Initialize();
                if (!Session.UserValidated)
                {
                    ViewData["Error"] = "Unable to validate user permission.";
                }
            }
            catch (Exception ex)
            {
                Helper.errorMsg msg = new Helper.errorMsg();
                Helper.CreateRfs(ex, -1, msg).Wait();
            }
		}
}

##################################################---Added on 08/02/2018---##################################################
I changed the way accessing httpcontext by adding kind of middleware interface "UserRepositroy.cs". I don't have static httpcontextaccesor anymore.
It works for other people, but one specific user still appears to be null out on HttpContextAccessor though..

Here is the error message:

System.NullReferenceException: Object reference not set to an instance of an object.
at UserRepository.GetUserNetworkId() in UserRepository.cs:line 78
at UserRepository.GetUserPhoneKey() in UserRepository.cs:line 97
at UserRepository..ctor(IHttpContextAccessor httpContextAccessor) in UserRepository.cs:line 18
at lambda_method(Closure , ServiceProviderEngineScope )
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Models.ErrorHandlingMiddleware.Invoke(HttpContext context) in Models\ErrorHandlingMiddleware.cs:line 25 --- 8/2/2018 3:06:25 AM

Here is UserRepository.cs:

public class UserRepository : IUserRepository
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public UserRepository(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            Startup.UpdateGlobals(_httpContextAccessor.HttpContext.Request); <----------------Still httpContextAccessor is null from the user.
            Startup.Global["UserPhoneKey"] = GetUserPhoneKey().ToString();
        }
        public bool IsUserValidated()
        {
            string userName = null;
            string NetworkId = null;
            int PhoneKey;
            bool Validated = false;

            var identity = _httpContextAccessor.HttpContext.User.Identity;

            if (identity.IsAuthenticated)
            {
                userName = identity.Name;
            }
            else
            {
                var basicCredentials = new BasicAuthenticationHeader(_httpContextAccessor.HttpContext);
                userName = basicCredentials.UserName;
            }

            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development"&& Environment.GetEnvironmentVariable("USER_NETWORK_ID") != null) // used for testing in development by setting overriding environmental varibles
            {
                NetworkId = Environment.GetEnvironmentVariable("USER_NETWORK_ID");
            }
            else
            { // assume production
                NetworkId = userName.Split("\\").Last();
            }

            if (NetworkId.Contains("@"))
            {
                Validated = false;
            }
            else
            {
                var userInfo = UserInfo.GetUserInfo(NetworkId);
                PhoneKey = userInfo.userPhoneKeyId;
                Validated = PhoneKey > 0;
            }

            return Validated;
        }

        public string GetUserNetworkId()
        {
            string userName = null;
            string NetworkId = null;

            var identity = _httpContextAccessor.HttpContext.User.Identity;

            if (identity.IsAuthenticated)
            {
                userName = identity.Name;
            }
            else
            {
                var basicCredentials = new BasicAuthenticationHeader(_httpContextAccessor.HttpContext);
                userName = basicCredentials.UserName;
            }

            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development"&& Environment.GetEnvironmentVariable("USER_NETWORK_ID") != null) // used for testing in development by setting overriding environmental varibles
            {
                NetworkId = Environment.GetEnvironmentVariable("USER_NETWORK_ID");
            }
            else
            { // assume production
                NetworkId = userName.Split("\\").Last();
            }

            return NetworkId;
        }

        public int GetUserPhoneKey()
        {
            var userInfo = UserInfo.GetUserInfo(GetUserNetworkId());
            int PhoneKey = userInfo.userPhoneKeyId;
            return PhoneKey;
        }
}

Here is how I added HttpContextAccessor and interface UserRepository in the Startup.cs:

public void ConfigureServices(IServiceCollection services) {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

			services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromHours(12);
            });
            services.AddHttpContextAccessor(); //core 2.1
            services.AddTransient<IUserRepository, UserRepository>();
        }

	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
		if (env.IsDevelopment()) {
			app.UseDeveloperExceptionPage();
			app.UseBrowserLink();
		} else {
                        app.UseExceptionHandler("/Home/Error");
                        app.UseHsts();
                }

                app.UseMiddleware(typeof(ErrorHandlingMiddleware));

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseSession();

                app.UseMvc(routes => {
				routes.MapRoute(
					name: "default",
					template: "{controller=Home}/{action=Index}/{id?}");
		});
	}



Convert Html to PDF in Asp.Net Core 1.1

$
0
0

I have found alot of nuget packages for converting html to pdf, but everyone I have found requires Asp.Net Core 2.0. Does anyone have a solution for Asp.Net Core 1.1? I really don't want to go through the migration process for Core 1.1 to 2.0.

Thanks in advance
Brad

bootstrapdatetime picker v 4.17.45 not working on host provider.

$
0
0

i have used  bootstrapdatetime picker v 4.17.45 not working on host provider smarterasp.net. It is working on my local machine.

<div class="form-group">
<label asp-for="Doe" class="control-label"></label>
<div class='input-group date' id='datetimepicker1'>
<input name="Doe" class="form-control date" type="text" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<span asp-validation-for="Doe" class="text-danger"></span>
</div>

-layout.cshtml contains-

<environment include="Development">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.45/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.45/css/bootstrap-datetimepicker.min.css">
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
$(function () {
$('#datetimepicker2').datetimepicker();
});
</script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>

ASP core 2.1 Identity - Store does not implement IUserRoleStore.

$
0
0

Dears!

I coding asp.net core 2.1 Identity, running have problems: 

ContosoUniversity.Areas.Identity.Pages.Account.RegisterModel.OnPostAsync(string returnUrl) in Register.cshtml.cs

<div class="source">
  1. _userManager.AddToRoleAsync(user, "Admin").Wait();
</div>

In Register.cshtml.cs code:

if (await _roleManager.RoleExistsAsync("Admin"))
{
_userManager.AddToRoleAsync(user, "Admin").Wait();
}

https://github.com/waityou580/ContosoUniversity/blob/master/ContosoUniversity/Areas/Identity/Pages/Account/Register.cshtml.cs


How to get child value based on checkbox in Jquery

$
0
0

I have multiple checkboxes as I iterate them in loop and I need to get checked values of checkbox moreover based on 'checked' checkboxes I need to get its Name which is coming in subitem.MenuPages on button click

@foreach (var item in (List<Group<string, MenuVM>>)Model)
                    {<div class="card-header" id="item-@i"><h5 class="mb-0"><button type="button" class="btn btn-link" data-toggle="collapse" data-target="#item-collapse-@i" aria-expanded="true" aria-controls="item-collapse-@i"><label name="menu[@i]" id="menukey[@i]">@item.Key</label><span class="icon text-right"><i class="fa fa-caret-down"></i></span></button></h5></div><div id="item-collapse-@i" class="collapse" aria-labelledby="item-@i" data-parent="#accordion"><div class="card-body"><div class="pages-wrapper vh-h-half">
                                    @if (item.Key != "Pages")
                                    {
                                        var parenttender = item.Values.Where(q => q.ParentId == null).ToList();
                                        @foreach (var subitem in parenttender)
                                        {<div class="input-fancy"><input type="checkbox" name="menu[@i].SelectedMenu" id="id-@i" class="chk" value="true" />  <label for="id-@i"><span> @subitem.MenuPages</span></label><input type="hidden" name="item[@i].SelectedMenu" value="false" id="id-@i"></div>

                                            @*<div class="input-fancy"><input type="checkbox" id="id9" name="home"><label for="id9"><span>Home</span></label></div>*@i++;
                                        }
                                    }

And below is my jquery code

 function getValueUsingClass() {

    var chkArray = [];


    $(".chk:checked").each(function () {
        alert($(this).val());
        var value = $(this).find('span').text();
        alert(value);
        chkArray.push($(this).val());
    });


    var selected;
    selected = chkArray.join(',');


    if (selected.length > 0) {
        alert("You have selected " + selected);
    } else {
        alert("Please at least check one of the checkbox");
    }
}$(document).ready(function () {$("#addmenu").on('click', function (e) {
        getValueUsingClass();


    })
})

bootstrap.css not rendering properly

$
0
0

my _layout file is-

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - StaffExplorer</title>
<environment include="Development">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
<style>
table.table th {
background-color: #808080;
color: white
}
.jumbotron {
background-size: 100% 100%;
}
.navbar-nav > li > a, .navbar-brand, .navbar-nav {
padding-top: 5px !important;
padding-bottom: 0 !important;
height: 30px;
}
.navbar {
min-height: 32px !important
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">StaffExplorer</a>
</div>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
@if (User.IsInRole("Admin"))
{
<a asp-area="" asp-controller="User" asp-action="Index">Admin</a>
<a asp-area="" asp-controller="Departments" asp-action="Index">Department</a>
}
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Staff Menu</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a asp-area="" asp-controller="Staffs" asp-action="Index">Staff</a>
<a asp-area="" asp-controller="Certificates" asp-action="Index">Certificate</a>
<a asp-area="" asp-controller="Experiences" asp-action="Index">Experience</a>
<a asp-area="" asp-controller="Papers" asp-action="Index">Paper</a>
<a asp-area="" asp-controller="Personals" asp-action="Index">Personal</a>
<a asp-area="" asp-controller="Qualifications" asp-action="Index">Qualification</a>
<a asp-area="" asp-controller="ResProjs" asp-action="Index">Research/Project</a>
<a asp-area="" asp-controller="Salarys" asp-action="Index">Salary</a>
</div>
</li>
<li class="nav-item">
<a asp-area="" asp-controller="Reports" asp-action="Index">Reports</a>
</li>
</ul>
</div>
@await Html.PartialAsync("_LoginPartial")
</div>
</nav>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>&copy; 2018 - StaffExplorer</p>
</footer>
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.45/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.45/css/bootstrap-datetimepicker.min.css">
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
$(function () {
$('#datetimepicker2').datetimepicker();
});
</script>
@RenderSection("Scripts", required: false)
</body>
</html>

Concatenate dropdown texts and textbox value as single string

$
0
0

Hello Guys,

please help me to resolve this.

I have buttons using that I am trying to generate dropdowns and textbox, what I am trying to do is whenever

I clicked the button dropdown and textboxes get created. but while saving I am getting dropdown selected value but I actually I want to save selected text from dropdowns. I have implemented javascript but that is not working. 

Here is an example what I m trying to do, I have a model.name as "str_formula_value"  which a database column 

eg. dropdown1 value A,B / dropdwn2 value as +,-  and textbox entered value let say500

so if I have to save data as A + B + 500  in  str_formula_value what should I apply.

@model TestApp.ViewModels.CompanySalaryViewModel


@{
    ViewData["Title"] = "SalaryDefinition";
    Layout = "~/Views/Shared/_Layout.cshtml";
}<h2 class="text-center my-3">Salary Definition</h2><hr />
@section Scripts{<script type="text/javascript">
        function ShowHideDiv() {
            var Yes = document.getElementById("Yes");
            var No = document.getElementById("No");
            var dvPassport = document.getElementById("dvPassport");

            var dvPassport1 = document.getElementById("dvPassport1");
            dvPassport.style.display = Yes.checked ? "block" : "none";
            dvPassport1.style.display = No.checked ? "block" : "none";
        }</script><script type="text/javascript">
        var room = 2;
        function cmp_fields() {

            room++;
            var objTo = document.getElementById('divid');
            var divtest = document.createElement("div");
            var divselect = document.getElementById('selectc');
            var option = divselect.innerHTML;
            divtest.setAttribute("class", " removeclass" + room);
            var rdiv = 'removeclass' + room;
            divtest.innerHTML = '<div class="form-inline">  <select name="str_component"  id="str_component" class="form-control">' + option + '</select> <div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_mb_fields(' + room + ');"> - </button></div></div></div></div > <div class="clear"></div></td > ';

            objTo.appendChild(divtest)
        }
        function remove_mb_fields(rid) {
            $('.removeclass' + rid).remove();
        }
        var room = 3;
        function opr_fields() {

            room++;
            var objTo = document.getElementById('divid');
            var divtest = document.createElement("div");
            var divselect = document.getElementById('selectopr');
            var option = divselect.innerHTML;
            divtest.setAttribute("class", " removeclass" + room);
            var rdiv = 'removeclass' + room;
            divtest.innerHTML = '<div class="form-inline"><select  name="str_operator"  id="str_operator" class="form-control">' + option + '</select><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_mb_fields(' + room + ');"> - </button></div></div></div></div><div class="clear"></div></td>';

            objTo.appendChild(divtest)
        }
        function remove_mb_fields(rid) {
            $('.removeclass' + rid).remove();
        }
        var room = 4;
        function val_fields() {

            room++;
            var objTo = document.getElementById('divid')
            var divtest = document.createElement("div");
            divtest.setAttribute("class", " removeclass" + room);
            var rdiv = 'removeclass' + room;
            divtest.innerHTML = '<div class="form-inline"><input class="form-control" id="str_formulavalue" name="str_formulavalue" placeholder="value"/><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_mb_fields(' + room + ');"> - </button></div><div class="clear"></div></div></td>';

            objTo.appendChild(divtest)
        }
        function remove_mb_fields(rid) {
            $('.removeclass' + rid).remove();
        }</script>




}


        <div class="row"><div class="col-md-4"><div class="form-group required"><Label class="control-label">Value Type : </Label></b><input type="radio" name="is_formula" class="custom-radio" id="Yes" value="1" onclick="ShowHideDiv()" required="">
                    Fixed Value<input type="radio" class="custom-radio" name="is_formula" id="No" value="2" onclick="ShowHideDiv()">
                    Formula</div><div class="form-group" id="dvPassport" style="display: none"><label name="str_formulavalue" class="control-label">Fixed Value</label><input name="str_formulavalue" class="form-control" /></div></div></div><div class="row"><div class="col-md-12 font-weight-bold"><div id="dvPassport1" style="display: none"><div class="btn-group btn-group-toggle" data-toggle="buttons"><button class="btn btn-success active" onclick="opr_fields();">Operator +</button><button class="btn btn-success" onclick="cmp_fields();">Component +</button><button class="btn btn-success" onclick="val_fields();">Value +</button></div><br /><br /><div class="form-inline" id="divid"></div><div class="clear"></div></div></div></div><div class="row my-lg-3"><div class="col-md-4 "><div class="form-group"><input type="submit" value="create" class="btn btn-info" /></div></div></div></form></div><select id="selectc" name="num_emp_type" class="form-control" asp-items="@(new SelectList(@ViewBag.createdcomponent, "num_component_id", "SalaryComponent"))" required="" style="display:none"><option Value="" selected="">Salary Component</option></select><select id="selectopr" class="form-control" asp-items="@(new SelectList(@ViewBag.Operator, "num_id", "str_data"))" required="" style="display:none"><option Value="" selected="">Select Operator</option></select><input type="hidden" id="str_formulavalue" name="str_formulavalue" /><script type="text/javascript">$("#str_component").on("change", function () {$("#str_formulavalue").val($(this).find("option:selected").text());
    });</script><script type="text/javascript">$("#str_operator").on("change", function () {$("#str_formulavalue").val($(this).find("option:selected").text());
    });</script>

Kestrel - 'the application completed without reading the entire request body'

$
0
0

I'm using Asp.Net Core 2.1, and IdentityServer4.   I have a client calling my WebApi, but the controller never gets called.  However here is the log for the WebApi:

Below is the message the client gets:

{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Server: Kestrel X-Powered-By: ASP.NET Date: Fri, 03 Aug 2018 15:18:01 GMT Content-Length: 0 }}
Below here, is the log of the WebApi:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/1.1 PUT http://blablabla:8484/api/register/1 application/json; charset=utf-8 323 info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[2] Successfully validated the token. dbug: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[8] AuthenticationScheme: Bearer was successfully authenticated. info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] Request finished in 417.6401ms 404 info: Microsoft.AspNetCore.Server.Kestrel[32] Connection id "0HLFPAGHN1IQH", Request id "0HLFPAGHN1IQH:00000001": the application completed without reading the entire request body.

As you can see, the request is successfully authenticated, however Kestrel is reporting a problem but it contains virtually no information about what went wrong. Here is my controller signature (the deviceRegistraion is a POCO that is shared between the Xamarin client and the WebApi.)

        public async Task Put(string Id, [FromBody]DeviceRegistration deviceUpdate)
            // call api
            var client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.SetBearerToken(tokenResponse.AccessToken);

            HttpContent httpContent;
            if (postcontent == null)
            {
                httpContent = new StringContent("");
            }
            else
            {
                string json = JsonConvert.SerializeObject(postcontent);
                httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
            }

            var response = await client.PutAsync(endpointURL, httpContent);

Above is the client making the call:

Any ideas on how to find out what is wrong with my request?   

Thanks

</div>

Create views in special address with dotnet aspnet-codegenerator controller

$
0
0

Hey guys.

I am using aspnet-codegenerator to generate controllers and views but when i use this command :

dotnet aspnet-codegenerator controller -name MoviesController -m Movie -dc ApplicationDbContext --relativeFolderPath Areas/Admin/Controllers --useDefaultLayout

it creates MoviesController.cs in right address (Areas/Admin/MoviesController.cs) but it creates views in root/Views/Movies/Add,Edit,Delete,Index

how can i use the command to create views in Areas/Admin/Views/Movies?

and another question:

when this command creates controller and Views it sets DbSet like this: public DbSet<Movie> Movie {get; set;} as you can see it uses Movie for the name but i want to use Movies to create table name plural, how can i?

Unable to connect to web server 'IIS Express'

$
0
0

This problem keeps returning.  I seem to be able to get past it, then it starts again.   I set my .NET Core 2.1  WebApi project as the startup project.  I click "> IIS Express" which attempts to run the project and I get the following message:

"Unable to connect to web server 'IIS Express".  I click OK, and project never runs.

I did  a bunch of rediculous things like stopping Visual Studio and IIS Express, removing the .VS folder of the solution, then clear out  %USERPROFILE%\Documents\IISExpress\config folder,  then restarting everything.  Not sure how it occasionally gets fixed.  

My project debug properties:    Enable SSL -disabled ;    App URL:    http://10.0.252.83.44300

Does anyone have any ideas why this keeps happening? or any ideas how to fix?  

Cannot publish .net core 2.1 web api project to IIS

$
0
0

I created an out of the box project for .net core 2.1 web api (no authentication, no support for https).

If i hit f5 in vistual studio (2017), it loads up fine to the default values controller.

With no further changes, I created a web application in IIS 
- IIS has the core module installed
- I created an apppool with no clr specified and using local system as the identity

When I browse to that application running in IIS - the browser (chrome) always returns a 404.

With stdout logging enabled, it appears that it is 'found' though:
Hosting environment: Production
Content root path: C:\Path\ToApp
Now listening on: http://127.0.0.1:15361
Application started. Press Ctrl+C to shut down.

Am I missing something obvious (that's not obvious to me!).

Let me know if I need to elaborate on the above repro steps


navbar dropdown menu of boostrap 3 does not work on live hosting

$
0
0

navbar dropdown menu of boostrap 3 does not work on live hosting. I tried with <li>tag or <div>,<a> tag. Both combinations work on local machines.

# in these tags converts to controller call on url as site1.com/#. From 2 weeks, i am trying with all possibilities. Nobody is addressing it. 

IIS hosting ASP.NET Core application not pass query string to kestrel server

$
0
0

As title,I create an asp.net core app,i have one page need to get query string by name(Request.Query["a"]),when I test in visual studio 2017,it runs ok! But when I publish to IIS(window server 2016), it run like ok. But i can't get query string.But if I use localhost to visit site.It can get query string.but if visit this app by special domain, I can't get query string,I try to see .net core logs, It like iis not pass query string to kestrel when I user special domain? what's wrong about this?

Environment:
Windows server 2016
.NET Core Runtime 2.1.2

some log file:

Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost/vwzao/?a=b
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[1]
Route matched with {page = "/Index"}. Executing action /Index
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[101]
Executing handler method OnGet with arguments (b) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[2]
Executed action /Index in 98.6913ms

special domain log:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 2004.1323ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://st.XXXXXXX.com/vwzao/
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[1]
Route matched with {page = "/Index"}. Executing action /Index
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[101]
Executing handler method OnGet with arguments () - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[2]
Executed action /Index in 3.594ms

[sqlite] No migrations were applied. The database is already up to date.

$
0
0

I'm building a web app using razor pages, and EF with Sqlite. I'm developing under Linux with the CORE SDK

After adding an initial migration without problems dotnet ef migrations add InitialCreate. When I update the database I get a message sayingNo migrations were applied. The database is already up to date.. And when I check the database using sqlite command interpreter (or run the app), the database does not contain any tables except an empty migrations history table.__EFMigrationsHistory.

The info message I got when I run dotnet ef migrations add

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using '/home/vagrant/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.0.1-rtm-125 initialized 'AgentContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None
Done. To undo this action, use 'ef migrations remove

The output message I get when running dotnet ef database update.

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using '/home/vagrant/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.0.1-rtm-125 initialized 'AgentContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "__EFMigrationsHistory" (
"MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,
"ProductVersion" TEXT NOT NULL
);
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT "MigrationId", "ProductVersion"
FROM "__EFMigrationsHistory"
ORDER BY "MigrationId";
info: Microsoft.EntityFrameworkCore.Migrations[20405]
No migrations were applied. The database is already up to date.
No migrations were applied. The database is already up to date.
Done.

Return custom json response when Unauthorized / token expired

$
0
0

Hi,

I have implemented one .net core API project where i am using JWT for token authorization and it works fine in case of correct token but if token is expired or Unauthorized access, it gives status code inside POSTMAN but i wanted to return json response in POSTMAN body to show custom json on my api call result.

You can check my source code.

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace TestJWT
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "mysite.com",
                    ValidateAudience = true,
                    ValidAudience = "mysite.com",
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sdfoiweklmnjlk2#lkjadsfms.dcizdsdlkfjls@!1@dfsdf"))
                };
            });

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

AuthController

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace TestJWT.Controllers
{
    [Route("api/[controller]")]
    public class AuthController : Controller
    {
        [HttpPost("token")]
        public IActionResult Token()
        {
            string header = Request.Headers["Authorization"];
            if (header.StartsWith("Basic"))
            {
                var credValue = header.Substring("Basic".Length).Trim();
                var usernameAndPassenc = Encoding.UTF8.GetString(Convert.FromBase64String(credValue));
                var userNameandPassword = usernameAndPassenc.Split(":");

                if(userNameandPassword[0] == "Admin" && userNameandPassword[1] == "pswd")
                {
                    //var claimsdata = new[] { new Claim(ClaimTypes.Name, "userName"), new Claim(ClaimTypes.Name, "userId") };
                    var claimsdata = new[] { new Claim(JwtRegisteredClaimNames.Sub, "Pritesh"), new Claim(JwtRegisteredClaimNames.Sub, "Mehta") };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sdfoiweklmnjlk2#lkjadsfms.dcizdsdlkfjls@!1@dfsdf"));
                    var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

                    var token = new JwtSecurityToken(
                        issuer: "mysite.com",
                        audience: "mysite.com",
                        expires: DateTime.Now.AddMinutes(1),
                        claims: claimsdata,
                        signingCredentials: signInCred
                    );

                    var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

                    return Ok(new {
                        token = tokenString,
                        id = userNameandPassword[1],
                        expires = token.ValidTo
                    });
                }
            }
            return BadRequest("Wrong Request");
        }
    }
}

ValuesController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace TestJWT.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [Authorize]
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

Thank you.

how to debug cshtml file

$
0
0

How can I debug the cshtml file  from the line  @ foreach. Please can you help me

 

<div>
@if (ViewBag.Menu != null)
{
<ul class="nav nav-sidebar" >

<li class="navi">Navigation <a href="javascript:void(0);" class="side-menu-button"><i class="fas fa-ellipsis-h"></i></a></li>
<li class="item active"><a href="/Home/Dashboard" class="dropdown-toggle" ><i class="icon icon-home"></i> <span class="label-text">Home </span></a></li>
<!-- <li class="item"><a href="#"><i class="icon icon-dashboard"></i><span class="label-text">Dashboard</span></a></li>-->
@foreach (var menuItem in ViewBag.Menu)
{

<li class="item ">
@if (@menuItem.ChildMenu != null && (@menuItem.ChildMenu.Count > 0))
{
<a href="/@menuItem.ControllerName/@menuItem.ActionName" class="dropdown-toggle" data-toggle="dropdown"><i class="@menuItem.MenuIcon"></i><span class="label-text">@menuItem.MenuName</span><span class="sub-icon"><i class="fas fa-chevron-circle-right"></i></span></a>
<ul class="sub-menu nav nav-sidebar ">
@foreach (var subMenuItem in @menuItem.ChildMenu)
{
<li class="item"><a href="/@subMenuItem.ControllerName/@subMenuItem.ActionName" data-accesskey="@subMenuItem.ShortCutKey" class="accesskey"><i ></i><span class="label-text">@subMenuItem.MenuName</span></a></li>
}

</ul>

}
else
{
<a href@menuItem.="/ControllerName/@menuItem.ActionName" class="dropdown-toggle" data-toggle="dropdown" ><i class="@menuItem.MenuIcon"></i><span class="label-text">@menuItem.MenuName</span></a>
}


</li>

}

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>