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

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.


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

Are action result must have Get to be available to call or not ?

$
0
0

Are action result must have Get to know the status is Get ?

when make web API controller on asp.net core 2.1 based on entity framework generated controllers functions 

i notice that function have get or post as example below :

public IEnumerable<Employee> GetEmployees()
        {
            return _context.Employees;
        }

suppose I make function Create 

are this will be available when call api or not ?

as api/create this will work or must have get name text as getemployee ?

what is different between return OK() and return view ?

$
0
0

what is different between return OK() and return view ?

i make wab api project on asp.net core 2.1 based on entityframwork core generated controller

i see result of every get method as 

return ok()

why no return return view()

what different between return OK() and return view()

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>

How to convert that code please from mvc project to web api

$
0
0

I work on mvc project in asp.net core 2.1

I create EmployeeController and inside it I make two function action result for create new employee and save it as following :

public IActionResult Create()
        {
var model = new Employee();
if (id == null)
{

model.EmployeeId = _repository.GetAll().Max(Employee => Employee.EmployeeId) + 1;
} return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(Employee employee) { if (ModelState.IsValid) { _context.Add(employee); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(employee); }

I decided to convert above functions to web api so that 

How to write create new employee page or form get and post according to actions above ?

EF Core 2.1 Versue EF6

$
0
0

I am starting a new asp.net core project and I miss using entity framework I gave up on it at version six cause of speed issues is ef core 2.1 any faster these days or should I stick to dapper.net?

Get files from node_modules with two shared projects

$
0
0

Hi everyone,

I need your help to know how I can import files from the "node_modules" folder.

I have this situation: I have a solution containing two separate projects that have to take the files in node_page. The node_modules folder is located in the root of the solution:

[folder SLOUTION]:

[folder] PROJECT 1

[folder] PROJECT 2

[folder] node_modules

Normally, if node_modules is inside the project, I would take the files with Gulp like this:

gulp.task('copy:bootstrap', function () {
return gulp.src(['./node_modules/bootstrap/dist/**/*'])
.pipe(gulp.dest(paths.lib + 'bootstrap/dist/'));
});

And now how do I do it?


Store data in masterdb as string or id of detail table?

$
0
0

Hi all,

Here is the situation,

Lets say I need to store State and Country data in a DB.

As you know I can store it as String as is, like (California /USA) or I can store it as States's Table ID and Countries' table ID (14/81)

The thing is the stored data is only one word and I don't want to store it as id (and get it with join).

Because in SPA application it is hard to construct a page from json data (you need to store id in a hidden input and send it etc. etc.)

What do you think?

Should I afraid of using strings  to store State/Country data? Because in 10 years record count can be million and that time strings can occupy lots of space and blow the db?

thanks

Unable to determine the relationship represented by navigation property ASP.NET

$
0
0

I'm trying to do a little personnal project, and I want to translate this uml class diagram into several class with the foreign key, primary key and so on.

enter image description here

But when I want to create a razor page (CRUD) I have this error:

enter image description here

I want to create it inside a folder, which is "Seances".

NB: I do not know how to use correctly the foreign key, my error is obviously from there...

Those are inside a Model folder.

Sorry its write in french, but here is a fast translate: Batiment = building

Salle = classroom

Seance = class session

UE = school subject (like math, english, IT class...)

Groupe = Group

Type Seance = kind of class session (CM = when all the class is here, TD = small group of the class in a classroom, TP = computer classroom for example)

Here is a total view of my project with the CRUD menu.

enter image description here

Here are my .cs file :

Batiment.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingSystem.Threading.Tasks;namespaceProjetAsi.Models{publicclassBatiment{//Primary keypublicintIdBatiment{get;set;}[Required]publicstringNomBatiment{get;set;}//Navigation link toward "salles"publicICollection<Salle>LesSalles{get;set;}}}

Salle.cs

namespaceProjetAsi.Models{publicclassSalle{//Primary keypublicintIdSalle{get;set;}[Required]publicstringNomSalle{get;set;}//foreign key for "batiment"publicint?IdBatiment{get;set;}//Navigation link toward séances publicICollection<Seance>LesSeances{get;set;}//Navigation link toward batimentpublicBatimentLeBatiment{get;set;}}}

Seance.cs

namespaceProjetAsi.Models{publicclassSeance{//Primary keypublicintIdSeance{get;set;}[Required]publicDateTimeJourSeance{get;set;}[Required]publicDateTimeHeureDebut{get;set;}[Required]publicintDureeSeance{get;set;}//foreign key for Salle publicint?IdSalle{get;set;}//foreign key for UE publicint?IdUE{get;set;}//Navigation link toward groupes publicICollection<Groupe>LesGroupes{get;set;}//Navigation link toward UEpublicICollection<UE> LUE {get;set;}//Navigation link toward group 0 or 1 publicICollection<Groupe>LeGroupe{get;set;}//Navigation link toward sallespublicICollection<Salle>LesSalles{get;set;}}}

TypeSeance.cs

namespaceProjetAsi.Models{publicclassTypeSeance{publicenumEnumTypeSeance{
        CM, TD, TP}//Primary keypublicintIdTypeSeance{get;set;}[Required]publicEnumTypeSeanceIntituleTypeSeance{get;set;}//Navigation link toward séancespublicICollection<Seance>LesSeances{get;set;}}}

UE.cs

namespaceProjetAsi.Models{publicclass UE{//Primary keypublicintIdUE{get;set;}[Required]publicstringNumeroUE{get;set;}[Required]publicstringIntituleUE{get;set;}//Navigation link toward GroupepublicICollection<Groupe>LesGroupes{get;set;}//Navigation link toward SeancepublicICollection<Seance>LesSeance{get;set;}}}

Groupe.cs

namespaceProjetAsi.Models{publicclassGroupe{//Primary keypublicintIdGroupe{get;set;}[Required]publicstringNomGroupe{get;set;}//foreign key for UE publicint?IdUE{get;set;}//foreign key for Seance publicint?IdSeance{get;set;}}}

Cordially

How To Sync Two Database in in Specificed Time Asp.net Core

$
0
0

Hi,
I have two database , i want sync these databases in specificed time for example at 23:00 PM .

How to do it in Asp.net Core ?

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).

Generate and download PDFs using Razor Pages.

$
0
0
Hello,

i made a mistake, i decided to use Razor Pages for a project one year ago.

Now i'm back working on this project because the customer wants new features, such as being able to generate PDF reports: i wanted to generate PDFs using html code, so i can easily create layouts and use templates which get injected by data and then downloaded as PDF files.

There are al ot of libraries, all of them don't (or are not meant) to work using Razor Pages: all of them have been created with MVC in mind.

Is there a way to easily implement PDF generation using razor pages without having to reinvent the wheel?

Thank you.

Stuff i tried:

http://nyveldt.com/blog/page/razorpdf

https://github.com/DesignLiquido/RazorPDF2

https://github.com/aaxelm/Rotativa.NetCore

PS. I'm using . NET Core 2.2

How to create a link to razorpage from mvc?

$
0
0

in a normal asp.net core controller i use urlhelper to create a link but the callback string is null every time:

string foo = "sometext"
string callbackUrl = Url.Page(
                    pageName: "/Test/Name",
                    pageHandler: null,
                    values: new { foo },
                    protocol: Request.Scheme);

This works from razor pages code behind, but not in normal controllers. How do I generate a link to my razor pages from a controller?

How can I host a .net core app with EF-MySQL in Azure

$
0
0

Hi all,

As far as I see deploying your .net core app in azure very easy and minutes job.

However I use mysql and I am not sure (and don't know how to do it) if I can upload mysql db into  azure and then web deploy my app.

Any help will be appreciated.


How to configure in startup.cs Default MapRoute login page

$
0
0

By default Asp.Net Core 2.2 has the following MapRoute that set the Home / Index the main page, I want to make the Login Page the primary one.

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

I tried that and I did not succeed ( Areas, Controller, Action  ).

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{areas=Identity}/{controller=Account}/{action=Login}/{id?}");
});

How to set Login as the home page of my ASP.NET CORE 2.2 application

AngularJS and the FormsModule

$
0
0

Hello everybody,

I am learning AngularJS on a .Net Core project, with this :

https://angular.io/tutorial/toh-pt1

As soon as I insert

import { FormsModule } from '@angular/forms'; // <-- NgModel lives here

nothing displays any more, except a blank web page.

Any idea what happens ?

data not display on browser although i get data on console.log(data)Angular

$
0
0

problem

data not display on browser although i get data on console.log(data)Angular ?

i need to show employee list of data but problem is not show on browser but if i make console.log(data)

it display as array of object and data show if you make inspect on browser

employeelist.component.html<div class="col-md-12"><h2>UserDetails</h2><div class="table-responsive table-container"><table class="table"><thead><tr><th>EmployeeId</th><th>BranchCode</th><th>EmployeeName</th><th>EmployeeAge</th><th>JoinDate</th><th>BirthDate</th><th>Active</th></tr></thead><tbody *ngFor="let doc of documents; let i = index"><tr *ngFor ="let emp  of doc.employees"><td>{{emp.EmployeeId}}</td><td>{{emp.BranchCode}}</td><td>{{emp.EmployeeName}}</td><td>{{emp.EmployeeAge}}</td><td>{{emp.JoinDate}}</td><td>{{emp.BirthDate}}</td><td>{{emp.Active}}</td></tr></tbody></table></div></div>

on apiservice file 
 getEmployees(){returnthis.http.get<Employee[]>('https://localhost:44326/api/Employee');}
on employeelist.component.ts})
export classEmployeeListComponentimplementsOnInit{
  employees:Employee[];
  constructor(private apiservice:ApiService,private toastr :ToastrService){}

  ngOnInit(){this.apiservice.getEmployees().subscribe((data:Employee[])=>{this.employees = data;
      console.log(this.employees)});}

Data show on console.log(this.employee) as following

employeelist.component.ts:18 (1) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {employeeId: 1, branchCode: 1, employeeName: "ahmed", employeeAge: 12, joinDate: "2018-12-12T00:00:00", …}

but on browser data is empty

https://www.mediafire.com/view/rw2lbkvweaojyus/Capture.JPG/file

How to structure an ecommerce site with the Areas

$
0
0

<div class="post-text" itemprop="text">

Hi everyone!

I have a question to ask you.

I'm trying to figure out how to structure an ecommerce site containing 2 sections: an administrative part and a visible part to the public (the part with the catalog, the cart, and all the pages of the site).

I would like to use the "Areas". The question is this, can the administration and site part be inserted into the Areas, as in the example below? Or should only the administrative part be included in the areas?

In case both the administrative part and the site visible to the public must be placed in the areas, the "Pages" folder in the root must be deleted, right?

As a programming language I use ASP.net Core 2.2 (C #) and when I can not use MVC.

I thought of a structure like this:

-Web- wwwroot-Areas--Admin---Pages-----Products-----Categories-----....---WebSite----Pages-----Home-----Products-----....-Pages(?)

Thanks in advance

An assembly specified in the application dependencies manifest (MyApp.Stock.UI.deps.json) was not found. Urgent Please help

$
0
0

When I run the published file  the following  error is coming.  

An assembly specified in the application dependencies manifest (MyApp.Stock.UI.deps.json) was not found:
package: 'Microsoft.AspNetCore.Antiforgery', version: '2.0.2'
path: 'lib/netstandard2.0/Microsoft.AspNetCore.Antiforgery.dll'
This assembly was expected to be in the local runtime store as the application was published using the following target manifest files:
aspnetcore-store-2.0.6.xml

 The file  'MyApp.Stock.UI.deps.json' is being already there on the folder   where I copied the published file

Please can you help me how to fix the error

Regards

Pol

Viewing all 9386 articles
Browse latest View live


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