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

ApplicationPoolIdentity is not working when I publish the application. Pls help

$
0
0

Hi

I published the site  and it working fine after creating the website in IIS manager using the following method

  1. .Net CLR Version - No Managed Code
  2. Identity : Local System

In Binding : I bind with my  All Unassigned option Then The application would be working fine.

But  when I changed  Identity as  ApplicationPoolIdentity, the following error will come in my windows 10 system

Cannot read configuration file due to insufficient permissions  c:\Exe\web.config.


@Html.Raw(Model.Test()) returning garbage

$
0
0

Hello everyone,

I am having this problem. In database I am storing pure HTML strings (Example: <script>document.GetElementByID("test").value = "test";</script> or <div style="background-color: pink;">test</div>), NO encoding before storing, just as IS.

When I try to display it in the razor page via @Html.Raw(Model.Test()) it shows something like this in the browser.

� �\[o�u~��P�VCD�3�/���ME�%��VQ��t���������(X`��l6 �<F`#����1ld��X���/y��@�b�g䫾���Zbs{ Q�Lwu�9U�νNs�O6�֏���$M�2W�����71��X�1;�0j�eu~���t���bQ4�bE[����,ỴDoRW2o9�{��|����b˹3�ڎp�х�1������;�:+7� ��ǩY�:5�rY+%�y�3��1�I�1B ���R����e�������.ΰ �Ja��$�4E��R1�3:E�I���Dž����a��I����ۄ�K���ڴ��8c.p���<1��p�Pg�� �xM.�cR�i��FgB�dK�8����B0���w�ȡ0}5_9��c��ԡ�Hv��ң�/ 5���3��U��Ln�����'|������z�H���+��8`��6���K��z���uq�����jT�dr�|����J�s%S4D���ک�x}0���9~�Y`7�z]H�$V)����\m> ~����m�6�#�κ0���ֽ�g��W@^�N�v���ܙH��q �X�7F). ��n�5i� ��� �ȋjE�X�;}�߀Q����uuP*�ߕ�05��*B20�w�$�������L�T.2����pe����&h&9حW�_���\�zɑ��y��ud��u����d؆�#e֑u7��&�:�{YG�Ҭ#��ɻ��̴u2陸�B.l@Ƒ~֑23�v֑^f�~fN�d����$/�ks�t�I���E��x�� -�+�h:���½ic<���'(���b=͕��ʑO,���h���8[�g�=�=٢eg�IS<[�T贐ޭn���'��s��|瑘/:ہ�/��%�F��x�I<��� �)�Y*�pR]Ԅщa���&�R�6�e{�fn���l���KD ��*������f����e�#z��ji�}����y���X��0��(��9��#�h�l9��ԑ,nV��~b��m@\ ��8�r��f�h�p�̀���������0[��7'�X�����-H�������RQu�T 9J�ľx��+�`��M�u�Cxk.�C�B�� #��í��������(M�A���F��@�GZ��Aa2�˹J�/X*ґca���78����sc�&���o�_�:FR��\�R���|,� �(�â����Vr����`� b��� �T:��e }6�aU&&�C!�Sf��to�S'��dF�3q�)4�K���d^,��+�r��r�a������kqL 9�O������� �����T���J��‹��Y7��e�6��jT��v|K����� ����Q1V5㟙|���h�}W��ɯ�:pY7�u�5�V���s)���pS��7���]d�% �Ot���'���������.�����0��� ؏�n��KOX����&� 8n1����j|�FL&����^�����+|G&VC–��/o�`��O��������� ��0�lf�^wS��Cj����_c� ����ԯ1{f�@��/~�������_|��G��4y �����_���/?������O>Ȏ�{)��$ъW�!��to��;\�@C4E������BL� �j]n�ѥ���G;���n-�eX��k��S�s�D�������M!P��i�R1|�6m�W � �)1o9�s0�먺�ɝ@�C��Y7�o�y�L�^��q��u���;�ŝ��YM�cuoS�Y$�{��GMc�*��_�zRO����IC�_j��M�G愡�jrgH|\=��s�PY�~�b�9#�������%��Qdn����e�4��%�Fx��@�� �h�NR�V��i�Wh�q�k� ���vS�VeUp��Z4m ��h��XV'v8^�%[����0%�����I@��J�&v��m��͞BUe`'SeRy� �=�l��}�����7�OS��څ�*G�^�G�F��Rg����VA��V�����t�|��/T��w�~u�"�!�5E��W�ať[��1Wׁг�ʞ�mפ�~�� ���m4��Ã�s�,.,`�AU�-P9�J ��T��½�2\H.a���&mg����9G�XqF+��1���I�{D�% ������;��ȅ5����js��e�4EL�b�>T��Hm���-f i��''w����s6���a�N�K�]�����0�&��R6�*����?�*K�;�|�vHА�U�pyv^+i�养�;� �U��,�ZUU;6�x�*���r�L��TY$��E���s�!�a�a6j�aL��UM����€[~��mU��D=V�4�$�a�cRk$�����",p�+��-��m��0���p�z���^[���"�Px2=�\ݸ�ތ��2��X���s��tʟ�c� ,�+@��1=��l���3���r�H� �2��ʎ���c�!ٺM�l�2�X��8�& f��y4��!���-ց����O3� c�NB����, <�δT�ͪ�æjk�BہB�Oa����Sԓ��|�n��F ��+N`�iJ� �Ȃ����۹��م��{�{bo�������)��^�G��D�LeN�̒����������B�⢌�87 -[����ʥ��5�8���e���GTa�.|��$U�� ���߅�>�@J-m�7�����i��jJ4��#p�A�y�R�J�ڰ�6�"��eV���؇�-�����۪0��-����~� ��6r���ᤜ? �;�q�T��y�� 0?D5t ]���BO%U�3���6'�ϴMۇ7���C�����J-:8 ߆��m�A��gNXx%c=���k�,�0����@��l��\�������e�{/?��U��.Xh�j'�P��眲�܆�F irc��:�)U��m/^�@SI`u��n�*Q����&J�{��^8����!���#H^=�\���1�1J���7�o�S5�������������Ǝ���Z�yǬ<\/=y��w�;�w� �;�Ĵ�~�9��;o�?/�̽g��n��ΝM~�觕c{�کKk{����_7=i���y��9�nˣj�^����F���6x�ў[;h��ֶ|��7=�4��s��j��*��P��_�C�\�<��\Y�W>��r?��0���N�:�VA+� �Q~_ZF��lJ�幉��}GO���5���[u�T4�.�NPxC����t �N�����uQx�O����g�вI q���Wk���i����zU���������N�X�Z�������g������m�9{�6������j�( ��[� � ;}���g�^������������{�`��*���\u�pmg�h��3���xk���2y��o)Bq� ��������(���A:��U�0_J�(k� [�J��[�Iݷ��: %~�6�V�_c��BC��[S���O6����� �~ �n,^C^sdc�䇦><�{}�5�!6H�G*��P��~ �è۞��B��!�VR-N�'.dy"�#����&͂ԟ�C��,,��]��F�ޟ�N���[T�� �:L���*!;2�(x�Gad��h$�y�6���IR.V27^���nl�Fu��q?2t1�?��9��c͍'6��7�S�zm�:$�0��{�xq]�����$|�1M

I've already try to use HttpUtility.HtmlDecode etc. no luck so far.

The Test() method returns string, I've try to return HtmlString as well ... same garbage result. I think it is some kind of encoding problem... anyhow I am stuck. Any help highly appreciated.

Thanks.

Creating roles for production using Razor

$
0
0

Hello, I'm a starter to Razor/MVC/.net-core. I've made very simple C# apps before with visual studio e.g. Xamarin.

Using Microsoft's Razor tutorials I've been working on making a Razor app with a basic CRUD system for editing/updating student details. I'm just a bit stuck on setting up roles for production now.

This tutorial https://docs.microsoft.com/en-us/aspnet/core/security/authorization/secure-data?view=aspnetcore-2.2 talks about authorization setup with seeded data and on MVC (not using Razor conventions). I'd just like to setup 2 roles: Administrator (full rights) and Reviewer (can view, not edit/delete), and only the homepage/about are accessible without login.

So far I've setup authorization as follows in startup:

            services.AddMvc()
                .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AuthorizePage("/Students");
                    options.Conventions.AllowAnonymousToPage("/private/PublicPage");
                    options.Conventions.AllowAnonymousToFolder("private/PublicPages");
                })

So you need to be registered to access "Students" directory. That's fine. Now I just don't understand the concept of how roles can be divided in production. For example, say I want to add a new administrator or reviewer, how would I do this when the app is live? Provided that the same database records users (and not an external Azure identity tool).

The only people using this app will be people I always add manually (staff members) and I'll be assigning them Admin/Reviewer role.

And then I just need to know how I can ensure only "edit" and "delete" processes and buttons are available to administrators. In MVC I've seen this done using this snippet above the part of the CS you want accessible to the specified role:

[Authorize(Roles = "Administrator")]

As far as I know, I think this works for MVC but not Razor.

Any suggestions?

Thank you so much.

.Net core Application Development in Windows using VS 2017 and Hosting in Mac os and Linux

$
0
0

I was new to .Net core and on googling i got that it was used to develop an .net application that can run in corss platform other than windows i.e. Linux, Mac Osx.

I was having few questions on this,

  1. What are pre-requistes softwares that i need to install to run .net application with respectivie specific OS i.e in Linux and in Mac os to run .net Core
  2. Can we develop .net core application in Windows and host it in Mac and Linux if yes than how can we host.
  3. Already Developed .net application, how can we migrate it to .net core without doing any changes and deploy in different env i.e Linux/Mac.
  4. Can some one please address above questions,

As i was in a sutiation where i need to use existing .net application with signalR running in Windows has to be made compatiable for Mac OSX and run it, Which was high priority. For this, Which one i need to Use weather .net core or Mono Project?

Regards,

Siva

How to release/unload unmanged native dylib from .net core while closing the app

$
0
0

Hi All,

We would like to know how to release/unload unmanged native dylib from .net core while closing the app in Mac?

Scenario: We are using native mac dynamic library (dylib) from .net core using [DllImport], in which it was able to load the dylib library and working fine, when we closes the application the dylib that has already been loaded was not unloading, when we start the app agian it is getting crashed due to that issue and we need to restart the meachine and run the app once agian.

Please help me resolving this problem.

Regards,

Siva.

Cant get details of the user who has logged in immediately after Signing In.

$
0
0

Hi guys I am trying to achieve redirections immediately after Login in a .Net Core 2.1 application using Identity Core.

The redirections are dependent on roles of the logged in user.

I am getting a Null Reference exception.

I read a few stack overflow questions and Git Issues and understood that this is because the user is not stored to the database right after sign in:

var result =await _signInManager.PasswordSignInAsync(Input.Email,Input.Password,Input.RememberMe, lockoutOnFailure:true).Result;

I tried the following to retrieve the role of the logged in user:

Method-1:

string userRole =_signInManager.Context.User.FindFirst(ClaimTypes.Role).Value;

Method-2:

To determine if a user exists in a given role:

User.IsInRole("RoleName")

Method-3:

_userManager.GetClaimsAsync(user)

I am getting a Null reference exception in all cases; I understand this is because of the request not being completed.

However I don't understand the fundamentals.

If not a solution, need direction:)

Thank you:)

This my startup.cs:

publicclassStartup{publicStartup(IConfiguration configuration){Configuration= configuration;}publicIConfigurationConfiguration{get;}// This method gets called by the runtime. Use this method to add services to the container.publicvoidConfigureServices(IServiceCollection services){
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<IdentityUser,IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

            services.Configure<CookiePolicyOptions>(options =>{// This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded= context =>true;
                options.MinimumSameSitePolicy=SameSiteMode.None;});

            services.ConfigureApplicationCookie(options =>{// Cookie settings  
                options.Cookie.HttpOnly=true;
                options.ExpireTimeSpan=TimeSpan.FromMinutes(30);
                options.LoginPath="/Identity/Account/Login";
                options.LogoutPath="/Identity/Account/Logout";
                options.AccessDeniedPath="/Identity/Account/AccessDenied";
                options.SlidingExpiration=true;});

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env){if(env.IsDevelopment()){
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();}else{
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();}

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

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

Login - Page controller of Identity core:

publicasyncTask<IActionResult>OnPostAsync(string returnUrl =null){
    returnUrl = returnUrl ??Url.Content("return path");if(ModelState.IsValid){var result = _signInManager.PasswordSignInAsync(Input.Email,Input.Password,Input.RememberMe, lockoutOnFailure:true).Result;if(result.Succeeded){var usera =User.IsInRole("Role1");var users =User.IsInRole("Role2");//string userEmail = _signInManager.Context.User.FindFirst(ClaimTypes.Name).Value;//string userRole = _signInManager.Context.User.FindFirst(ClaimTypes.Role).Value;if(User.IsInRole("Admin")){returnRedirectToAction("path1");}elseif(User.IsInRole("Supervisor")){returnRedirectToAction("path2");}elseif(User.IsInRole("Member")){returnRedirectToAction("path3");}else{returnRedirectToPage("/Identity/Account/AccessDenied");}}if(result.RequiresTwoFactor){returnRedirectToPage("./LoginWith2fa",new{ReturnUrl= returnUrl,RememberMe=Input.RememberMe});}if(result.IsLockedOut){
            _logger.LogWarning("User account locked out.");returnRedirectToPage("./Lockout");}else{ModelState.AddModelError(string.Empty,"Invalid login attempt.");returnPage();}}returnPage();}

</div>

Custom css file is missing in published app

$
0
0

Hi,

I've published my asp.net core 2.2 app and can see my Style.css file is missing in "css" folder in wwwroot. Any ideas why it's that? Am I supposed to use custom css file or all css must be in site.css? I found a bit similar topic but there the poster used site.css and found that publishing wasn't updatinng site.css.min file. The solution was to use BundlerMinifier. Since I'm not using site.css I don't think this might work for me too. Did anyone else encountered that?

I also used resources files to customizing my app to different cultures (like english, german, etc.) and I see there are appropriate folders created (like "en-US") with Texas.resources.dll file in each, but I can't change the culture the way I did in debug environment on my pc. Here's the method I'm using to change the culture, apparently it's not triggering in published app:

public async Task<IActionResult> OnGetSetCultureAsync(string culture)
{
HttpContext.Response.Cookies.Append("Culture", "c=" + culture + "|uic=" + culture);
var returnUrl = Request.Headers["Referer"].ToString();
if (returnUrl.Contains("?culture="))
{
var url = returnUrl.Substring(0, returnUrl.IndexOf("?culture="));
return Redirect(url + "?culture=" + culture);
}
else
{
return Redirect(returnUrl + "?culture=" + culture);
}
}

Btw, you can github my project here

OnPost handler not being called

$
0
0

I am trying to call an onpost method from a razor page, however I am getting 'page not found' on https://localhost:44873/MyPage/create

Razor page:

      @page"{handler?}"

            //display stuff

      <formasp-page-handler="create"method="post">

      <inputtype="hidden"name="id" value=@Html.DisplayFor(modelItem => item.Id) />

      <buttonclass="btn btn-default">Create</button>

      </form>

Which generates:

    <form method="post" action="/MyPage/create"> //I have tried create and Create
    <input type="hidden" name="id" value="2012">
    <button class="btn btn-default">Create</button></form>

In PageModel:

       public async Task<IActionResult> OnPostCreateAsync(int? id)

        {

                     \\Breakpoint that is never hit

            var myobject =await _context.MyObject.FindAsync(id);

            if (ModelState.IsValid)

            {

                return NotFound();

            }

            // Do stuff

            return Page();

        }


Creating a cron job in asp.net core web application

$
0
0

Dear All,

I am trying to create a cronjob that would enable me populate the database of my website at the first time the web application is set up. This cron job is also suppose to backup data from this web application to another cloud platform.

The web application is running offline at the client premise or office environment.  So the web application is suppose to back up data online.

Here is my question.

From my experience with cron job. Cronjobs are more like external scripts that performs background operations. could be in any language. Please is this the same way in asp.net core.

If I am creating a cronjob do all this I have listed above, do I need to create a asp.net core exe that would run this .

Or do I just have a Background Task within my webapplication which would run with a scheduler.

Please if you have sample codes please share I would appreciate.

I just want to be sure that I am doing things the proper way so my application does not fail at the client location. Cos the cron job operations is very very important.

Thanks alot.

ASP.NET Core 3 Web Application, Azure App Service, and a ANCM In-Process Handler Load Failure

$
0
0

I am really new to working with all of these different technologies so pardon me if I am missing some knowledge. In any event, I have a bit of ASP.NET MVC architecture under my belt but I have yet to really grasp the framework, tooling, or what the scaffolding of any given ASP-type web application is doing.

tl;dr;

At the moment, I am working on hosting an ASP.NET CORE (3) web application with Azure and I have setup a plan for the App Service. The project is very simplistic and I just want to get it to run from Azure so it can field requests.The problem, is that it builds fine on my machine but when I publish it to Azure I am met with an HTTP Error 500.0 denoting that I am probably missing one of these requirements:

  • The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.
  • The in process request handler, Microsoft.AspNetCore.Server.IIS, was not referenced in the application.
  • ANCM could not find dotnet.

I think the issue boils down to that I am not doing something with IIS properly either on my local machine or in the cloud.
I will change the logging level of the application as suggested in error message I am getting when I hit the web page AND I have configured a service for Application Insights on Azure so hopefully that will help my case. I have tried a number of StackOverflow suggestions regarding web configs and such but those just regenerate on build.

Any help would be so, so, greatly appreciated as this is a portfolio piece for me and I spent a fair amount of time working on it - I think I may have just missed something basic. Thank you.


IsInRoleAsync gives a runtime error

$
0
0

Hi,

Following view model and controller:

{

    public class User
    {
        public string UserName { get; set; }
        public bool IsUser { get; set; }
        public bool IsAdmin { get; set; }
    }

    public class UserListModel : PageModel
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<ApplicationUser> _userManager;

        public UserListModel(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        public IList<User> Users = new List<User>();

        public async void OnGetAsync()
        {
            List<ApplicationUser> AppUsers = _context.Users.ToList();
            foreach (ApplicationUser U in AppUsers)
            {
                User X = new User  //Runtime error here!!
                {
                    UserName = U.UserName,
                    IsUser = await _userManager.IsInRoleAsync(U, "Member"),
                    IsAdmin = await _userManager.IsInRoleAsync(U, "Admin")
                };
                Users.Add(X);
            }
        }
    }
}

it's building OK, but when I run it I get A runtime error:

System.ObjectDisposedException
HResult=0x80131622
Message=Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'ApplicationDbContext'.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_StateManager()
at Microsoft.EntityFrameworkCore.Query.QueryContextDependencies.get_StateManager()
at Microsoft.EntityFrameworkCore.Query.QueryContext.get_StateManager()
at Microsoft.EntityFrameworkCore.Query.QueryContext.BeginTrackingQuery()
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider._TrackEntities[TOut,TIn](IAsyncEnumerable`1 results, QueryContext queryContext, IList`1 entityTrackingInfos, IList`1 entityAccessors)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<ExecuteSingletonAsyncQuery>d__21`1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<IsInRoleAsync>d__37.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Identity.UserManager`1.<IsInRoleAsync>d__113.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at RoosterApp.Areas.Identity.Pages.Account.UserListModel.<OnGetAsync>d__4.MoveNext() in F:\rooster\Rooster\RoosterApp\RoosterApp\Areas\Identity\Pages\Account\UserList.cshtml.cs:line 39

Please can someone tell me what is wrong in my code.

VSProject.References.Add method is not working properly in netcore project

$
0
0

Hi All,

Currently I am trying to add the assembly references in netcoreapp project by using the below method. The below function working properly when we add the single assembly in the project. But I have faced the problem when I have tried to add the two or more assemblies one by one and this method is confused to add the next assemblies and my status bar message also not given the right content. I think the netcoreapp project has been tried to load after I have added the first assembly. 

foreach (string assembly in _assemblies)
                    {
                        try
                        {
                            string assemblyName = assembly.Contains("\\") ? Path.GetFileName(assembly) : assembly.Split(',')[0];
                            string projectname = Project.Name;
                            if (!ExistingReferences.Contains(assemblyName.ToLower()))
                            {
                                dte.StatusBar.Text = "VS Extensions: " + projectname + ", " + "Adding " + assemblyName + " assembly to the project reference...";
                                vsProject.References.Add(assembly);
                            }
                        }
                        catch (Exception e)
                        {

                        }
                    }

Could you please suggest me how can i resolve this issue? Also, is there any easy way to add the assembly reference in netcoreapp project by pro-grammatically ?

Thanks,

Ganesan R.

How can i add a third attribute to identify my user in user-role table?()

$
0
0

Hi everyone, we use the user-role based for authorization user in our project. we need to add an attribute to our table (user role table),which results in the user having the role when that attribute established. for example we want to say user A in location X has a special role but same user in location Y has another roles. in another words, if we have a user that have diffrent roles in two companies, if we want to delete company A, the role of user destroyed in in just company A, and this user stay in company B.
Asp.net core mvc - Asp.net core Identity

when edit record i get error on function editemp

$
0
0

Problem

When click button edit on employee list it not open page or form of edit  and show error 

ERROR TypeError: Cannot read property 'toString' of undefined
    at EmployeeListComponent.push../src/app/employeelist.component.ts.EmployeeListComponent.editEmp (employeelist.component.ts:35)
this is error on line localStorage.setItem('editEmpId', employee.EmployeeId.toString());

on employeelist.component.ts i have function editemp as following

editEmp(employee: Employee): void {  
   localStorage.removeItem('editEmpId'); 
    console.log(employee.EmployeeId) ;
    localStorage.setItem('editEmpId', employee.EmployeeId.toString());  
    this.router.navigate(['employees']);
  }  

on employeelist.component.html

<tr *ngFor = "let emp of employees"><td> {{emp.employeeId}}</td><td> {{emp.branchCode}}</td><td> {{emp.employeeName}}</td><td><button (click)="editEmp(emp.employeeId)" class="btn btn-sm btn-outline-danger">Edit</button></td>
and this form employees.component.ts

import { Component } from '@angular/core'
import { ApiService } from './api.service'
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { Router } from "@angular/router"; 
@Component({
    selector :'employees',
    templateUrl : './employees.component.html'
})
export class EmployeesComponent{
    employees = {}
    empformlabel: string = 'Add Employee';  
    empformbtn: string = 'Save';
    constructor(private formBuilder: FormBuilder ,private router: Router , private api:ApiService,private toastr: ToastrService){}
    addForm: FormGroup; 
    btnvisibility: boolean = true; 
    ngOnInit() {
      this.addForm = this.formBuilder.group({  
        EmployeeId: [],  
        EmployeeName: ['', Validators.required],  
        JoinDate: ['', [Validators.required, Validators.maxLength(20)]], 
        BirthDate: ['', [Validators.required, Validators.maxLength(20)]], 
        EmployeeAge: ['', [Validators.required, Validators.maxLength(3)]],
        BranchCode: ['', [Validators.required, Validators.maxLength(2)]],
        Active: ['', Validators.required]  
      }); 
        //this.resetForm();
       let empid = localStorage.getItem('editEmpId');  
    if (+empid > 0) {  
      this.api.getEmployeeById( +empid).subscribe(data => {  
        this.addForm.patchValue(data);  
      })  
    }  
    this.btnvisibility = false;  
    this.empformlabel = 'Edit Employee';  
    this.empformbtn = 'Update';
      }


}

How to solve this error please ?

Dotnet Core calling a soap service issue

$
0
0

I have a dotnet core 2.0 app which makes some calls out to some 3rd party soap services. The web references have been added to the project using a wsdl and connected services. Everything works fine but periodically it stops working and throws an error.

Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

System.TypeLoadException: Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

at SoapClient.GetDetailsAsync(GetDetailsRequest request) in Connected Services\SoapClient\Reference.cs:line 1146

This api runs on linux container and when i restart the api the error goes away and everything runs fine. There is no issue on the service side because the method it calls exists. Web reference has been updated to the latest. There is no outgoing call from the api when this error occurs.

Any help in debugging or fixing this issue?

Thanks


Adding model with DateTime property results with default value (00001-01-01) in SQL Server

$
0
0

Hi guys,

I'm using ASP.NET Core 2.1 MVC. I have a Post model which has CreateDate property. I used input type="date" in View. When creating post after filling all inputs, it always addsDateTime property value as default (0001-01-01 00:00:00.0000000) though I pick various dates in DateTime field of the post creation form. The format in SQL is datetime2.    I also used attribute to format property. Here is the details to see:

In Post Model

public class Post
{
public int Id { get; set; }
[Required]
[MaxLength(55)]
public string Title { get; set; }

public string Image { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreatedDate { get; set; }

}

in ViewModel

public int Id { get; set; }
public Post Post { get; set; }

In View

<form method="post" asp-action="Postadd" asp-controller="Post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Post.Title" style="width: 45px">Title</label>
<input asp-for="Post.Title" class="postinput" type="text"><br>
<span asp-validation-for="Post.Title"></span><label asp-for="PostImage.FileName" >Upload Image</label>
<input asp-for="PostImage.FileName" class="forupload" type="file" name="file">
<label asp-for="Post.CreatedDate" style="width:80px">Start Date</label>
<input asp-for="Post.CreatedDate" class="postinput" type="date" name="date"><br>
<span asp-validation-for="Post.CreatedDate"></span>

</form>

Action

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Postadd(Post post, IFormFile file)
{
if (ModelState.IsValid)
{
if (file == null || file.Length == 0)
{
ModelState.AddModelError("", "No file selected");
return View();
}

string mypath = Path.Combine(_env.WebRootPath, "images", Path.GetFileName(file.FileName));

using (var stream = new FileStream(mypath, FileMode.Create))
{
await file.CopyToAsync(stream);
}

AdminPostModel postModel = new AdminPostModel();
postModel.Companies = await _offerDbContext.Companies.ToListAsync();

post.Image = file.FileName;
_offerDbContext.Posts.Add(post);
await _offerDbContext.SaveChangesAsync();
return RedirectToAction("Admin", "Admin");
}
else
{
ModelState.AddModelError("", "Couldn't create");
return View();
}

}

What is the problem?

(please focus on datetime parts of the code I provided, others I may share here incomplete, but ignore them as I know that they work).

Adding a display claim

$
0
0

I want to grab a users real name and be able to use it anywhere without repeatedly querying AD. Claims looks like the best way to do this.

My original authorization worked and was done using policy:

services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy =>
policy.Requirements.Add(new GetGroup(new string [] { "Admin"})));
options.AddPolicy("User", policy =>
policy.Requirements.Add(new GetGroup(new string [] { "User"})));
});

I found a post suggesting the below should work to add claims (in startup.cs):

app.UseAuthentication();

app.Use(async (context, next) => {

if (context.User != null&& context.User.Identity.IsAuthenticated)

   {

        context.User.Claims.Append(new Claim("DName", GetDName())));

    }   

     await next();

});

I don't get an error, but it doesn't seem to append the claim. What else do I need to do?

I want to be able to use 'User.Claims.First(c => c.Type == "DName").Value'

Dotnet Core calling a soap service issue

$
0
0

I have a dotnet core 2.0 app which makes some calls out to some 3rd party soap services. The web references have been added to the project using a wsdl and connected services. Everything works fine but periodically it stops working and throws an error.

Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

System.TypeLoadException: Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

at SoapClient.GetDetailsAsync(GetDetailsRequest request) in Connected Services\SoapClient\Reference.cs:line 1146

This api runs on linux container and when i restart the api the error goes away and everything runs fine. There is no issue on the service side because the method it calls exists. Web reference has been updated to the latest. There is no outgoing call from the api when this error occurs.

Any help in debugging or fixing this issue?

Thanks

Use Multi Regular Expression For a Property

$
0
0

Hi,
I want get email or phone number in one textbox but how to set regular expression for
phone number and email together ?

 [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
        [RegularExpression(@"^\(?([0-9]{4})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "incorect phone")]
        public string Username { get; set; }


 

when pass id value of put(update) from postman it passed as 0 although it have value on link

$
0
0

problem

when pass id value of put(update) from postman it passed as 0 although it have value on link ?

i select key from post man as contenttype application/json

and this is my url

https://localhost:44326/api/Employee/put?id=5

and when put breakpoint in function put and run app

it hit breakpoint but id return with 0 although i have 5 in my link

and 5 also exist on database 

  [Produces("application/json")]
[Route("api/Employee")]
public class EmployeeController : Controller
{
[HttpPut("{id}")] public IActionResult PutEmployee(int id, [FromBody] Employee employee) { if (id != employee.EmployeeId) { return BadRequest(); } try { _repository.Update(employee); } catch (DbUpdateConcurrencyException) { if (!EmployeeExists(id)) { return NotFound(); } else { throw; } } return Ok(); }

when run API update from angular 6 it give me bad request because id is passing by 0 ?

why is pass id as 0 and how to solve this problem ?

I work with asp.net core 2.1 visual studio 2017

and I have this function above on controller Employee

this is only function update (put) for my controller 

so that how to solve problem passing 0 and 

what is correct link if above is wrong ?

Viewing all 9386 articles
Browse latest View live


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