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

Getting error "Hmmm...can’t reach this page Try this Make sure you’ve got the right web address: https://localhost:5001"

$
0
0

Hello everyone!

My first post. Was thrown in the ring to write a razor app...

The app implements the PRG pattern whereby a search page is presented, the user enters a criteria, hits the search button and the result of the search is presented at the bottom of the same page. The items listed in the results table have a link that open a detail page, which has a "back" link to the first page. All that was working...I made some changes along the way and now when I run the app for the first time, it comes up. I enter the search criteria, hit the submit button and the page fails with 

"Hmmm...can’t reach this page

Try this Make sure you’ve got the right web address: https://localhost:5001..."

Below is a simplified version of the code in the page model.

[TempData]
 public string FileSearchCriteriaAuto { get; set; }
//...more code here
public void OnGet()
        {
            if (!String.IsNullOrEmpty(FileSearchCriteriaAuto))
            {
                FileSearchCriteria = JsonConvert.DeserializeObject<SearchCriteria>(FileSearchCriteriaAuto);

                HasSearch = FileSearchCriteria.FileName.Length > 0 || FileSearchCriteria.Criteria.Exists(c => c.Trim().Length  > 0);

                ContentSearchCriteria = new List<string>();
                ContentSearchCriteria.AddRange(FileSearchCriteria.Criteria);

                if (!(TempData == null))
                {
                    FileSearchCriteriaAuto = JsonConvert.SerializeObject(FileSearchCriteria);
                    TempData["FileSearchCriteriaManual"] = FileSearchCriteriaAuto;

                    if (TempData.ContainsKey("MatchedFilesJson"))
                    {
                        MatchedFiles = JsonConvert.DeserializeObject<List<FileProcessed>>(TempData["MatchedFilesJson"].ToString());
                        TempData.Keep();
                    }
                }
                FileName = FileSearchCriteria.FileName;
            }
            else
            {
                FileSearchCriteria = new SearchCriteria(string.Empty, 3);
            }

        }

        public async Task<IActionResult> OnPostAsync()
        {
            FileName = Request.Form["fname"].ToString().Trim();
            var elements = Request.Form.Where(e => e.Key.Contains("criteria")).ToList();
            ContentSearchCriteria = new List<string>();
            foreach (var ele in elements)
            {
                ContentSearchCriteria.Add(ele.Value.ToString().Trim());
            }
            FileSearchCriteria = new SearchCriteria(FileName, ContentSearchCriteria.ToList());

            string criteria = JsonConvert.SerializeObject(FileSearchCriteria);

            await LoadFilesAsync(FileName);

            MatchedFilesJson = JsonConvert.SerializeObject(MatchedFiles);
            TempData["MatchedFilesJson"] = MatchedFilesJson;

            return RedirectToPage("/Index");
        }

NB: I have tried passing a parameter to the OnGet method, from a property decorated with the

[BindProperty(SupportsGet = true)]

. Then the browser cannot render the page, as if the link is broken. 

Does anyone know why the page won't open? Thank you in advance!


Re: Problem with batch updating for master-details entities.

Creating an Endpoint that can read any json. A generic endpoint API

$
0
0

So I have a requirement to have one endpoint that can read json payload that can hit it from different system. We have several partners that would be posting data to our system.  So we want one endpoint that would handle getting data from any of our partners posting data.

I have something like this already.

[HttpPost]
public string Getdata([FromBody]Object data)
{

  //how do I convert it to the specific class that sooths the  json payload.

  //Or how do I read the data attribute of the object data pasted without knowing the payload structure.
}

I need to be able to create a generic json reader like this system here

https://quicktype.io/csharp/

So when data hits me I can read the data.

Best Regards,

Thanks in Advance

How to read proxy setting ipv4/ipv6 in dotnet core ubuntu

$
0
0

Hi Experts,

please let me know how i can read proxy settings in ubuntu 20.04.

also how i can get the bypass list from the proxy settings.

please provide me snippet of code for the above.

Thanks in advance,

KK

Web Service running on port 80 required admin password

$
0
0

Hi Experts,

I have created a soap service using dotnet core SoapCore module.

This service i am trying to run in the port 80. If i want to run service password is required.

Is there any possibility to run service without providing admin password to run soap service service.

Please share me snippet of code if possible.

Thanks in advance,

KK

how to migrate 3rd prty dll in asp.net core

$
0
0

Hi Team,

how to migrate 3rd prty dll in asp.net core

below are dll

EAPDiscovery

Antlr

ICSharoCode

Lesi.collection

NETCerticli

Newtonsoft.json

syslog4net

I will be helpful for your suggestion

all dll are ther in asp.net 4.5 project

EntityFrameworkCore - Class with many list of the same class

$
0
0

Hi guys,

I have following class that have many List of the same classes :

public class EmailMessage
    {

        #region Lists

        
        public List<EmailAddress> FromAddresses { get; set; }
        public List<EmailAddress> BccAddresses { get; set; }
        #endregion

        [Key]
        public int Id { get; set; }
        public string MessageId { get; set; }
        public uint Uid { get; set; }
        public DateTimeOffset Date { get; set; }
        public MessageImportance Importance { get; set; }
        public MessagePriority Priority { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public bool IsHtml { get; set; } = true;
        public bool NeedReadReceipt { get; set; }
        public bool NeedDeliveredReceipt { get; set; }
        public string InReplyTo { get; set; }
        public string Sender { get; set; }
        public EmailMessageDirection  MessageDirection { get; set; }
        public User User { get; set; }

    }
 public class EmailAddress
    {
        private string _name;

        public EmailAddress(EmailAddress address)
        {
            _name = address.Name;
            Address = address.Address;
        }
        public EmailAddress(string name, string address)
        {
            _name = name;
            Address = address;
        }

        [Key]
        public int Id { get; set; }
        public string Name
        {
            get
            {
                if (string.IsNullOrEmpty(_name))
                {
                    return Address;
                }
                return _name;
            }
            set
            {
                _name = value;
            }
        }
        public string Address { get; set; }

        
        public EmailMessage FromEmailMessage { get; set; }
        
        public EmailMessage BccEmailMessage { get; set; }
        

    }

My data Context is following:

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<EmailMessage>()
                .HasMany(em => em.FromAddresses)
                .WithOne(fa => fa.FromEmailMessage)
                .IsRequired();


            builder.Entity<EmailMessage>()
                .HasMany(em => em.BccAddresses)
                .WithOne(fa => fa.BccEmailMessage)
                .IsRequired();

        }

When I do the migration it build only one Email Address Table with following Shadow properties:

FromEmailMessageId and BccEmailMessageId

with foreign key on EmailMessage Id.

This does not work because when I tra to add a message I get an error that On EmailMessage Table is missing FromEmailMessageId or BccEmilMessageId field

So the question is I can I force builder to make distinct tables for Each list in EmailMessage class , without shadow properties ?

Thankyou for help

How to pass the model data to Partial View in .NET Core

$
0
0

Hi All,

I have partial view in main Index.cshtml, How to pass model to Partial view using ASP.NET core 3.0 mvc

Many Thanks,

Shabbir


Static instance of Microsoft.Extensions.Configuration.IConfiguration thread safety

$
0
0

Hello all!

Does the 

private static IConfiguration Config;

guarantee thread safe access via several controllers instances? Do I need to use lock?

Thank you.

Problem with batch updating for master-details entities.

$
0
0

Hi

I have a master-detail view with 2 tables :

DefaultVisitProductHeaders -> Master table
DefaultVisitProductDetails -> Detail table

In my view, i've using ajax request to give end-user to add/update/remove details, then save them in tempData (not in _dbContext). Here is my master-detail view (for edit mode):

@model DefaultVisitProductHeaders<h4>Edit Drugs Package</h4><hr /><div class="row"><div class="col-md-6">        <form id="frmEditPackageHeaderItem" asp-action="Update" method="post"><div asp-validation-summary="All" class="text-danger"></div><input type="hidden" id="hdnDefaultVisitProductHeaderRowID" asp-for="DefaultVisitProductHeaderRowID" value="@Model.DefaultVisitProductHeaderRowID" /><div class="form-group"><label asp-for="DefaultVisitProductHeaderName" class="control-label"></label><input asp-for="DefaultVisitProductHeaderName" class="form-control" value="@Model.DefaultVisitProductHeaderName" /><span asp-validation-for="DefaultVisitProductHeaderName" class="text-danger"></span></div><br /><h4>Package Details List</h4><hr /><div id="divPackageDetails" class="container">
                @Html.RenderAction("GetPackageDetails", "Package", new { id = Model.DefaultVisitProductHeaderRowID })</div><div class="text-right"><button type="submit" id="btnUpdate" class="btn btn-success">Save</button>
                @Html.ActionLink("Back", "Index", "Package")</div></form></div></div><div id="divPopup"></div>

@section Scripts{
    <script src="~/js/jquery.validate.min.js"></script><script src="~/js/jquery.validate.unobtrusive.min.js"></script>
}

My problem is that when, click on save button to update database, i'm facing this error (for added entities) :

InvalidOperationException: The instance of entity type 'DefaultVisitProductHeaders' cannot be tracked because another instance with the same key value for {'DefaultVisitProductHeaderRowID'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap<TKey>.ThrowIdentityConflict(InternalEntityEntry entry)

Here is my update action :

[HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Update([Bind("DefaultVisitProductHeaderRowID, DefaultVisitProductHeaderName")] DefaultVisitProductHeaders packageHeader)
        {
            if (this.ModelState.IsValid)
            {
                var curPackageHeader = _dbContext.DefaultVisitProductHeaders.Find(packageHeader.DefaultVisitProductHeaderRowID);
                curPackageHeader.DefaultVisitProductHeaderName = packageHeader.DefaultVisitProductHeaderName;
                this.AttachPackageDetailsToDbContext(curPackageHeader);
                _dbContext.SaveChanges();

                return RedirectToAction("Index", "Package");
            }

            return View("Edit", packageHeader);
        }

And here is my helper methods (AttachPackageDetailsToDbContext, GetPackageDetailsList) :

private void AttachPackageDetailsToDbContext(DefaultVisitProductHeaders packageHeader)
        {
            List<DefaultVisitProductDetails> lstPackageDetails = this.GetPackageDetailsList();

            List<DefaultVisitProductDetails> lstItemsAdded = lstPackageDetails.Where(d => d.IranHealthEntityState == IranHealthEntityState.Added).ToList();
            List<DefaultVisitProductDetails> lstItemsModified = lstPackageDetails.Where(d => d.IranHealthEntityState == IranHealthEntityState.Modified).ToList();
            List<DefaultVisitProductDetails> lstItemsDeleted = lstPackageDetails.Where(d => d.IranHealthEntityState == IranHealthEntityState.Deleted).ToList();
            foreach (DefaultVisitProductDetails detailItem in lstItemsAdded)
            {
                _dbContext.DefaultVisitProductDetails.Add(detailItem); // Cause error!!
            }

            foreach (DefaultVisitProductDetails detailItem in lstItemsModified)
                _dbContext.Entry(detailItem).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            foreach (DefaultVisitProductDetails detailItem in lstItemsDeleted)
                _dbContext.Entry(detailItem).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
        }


private List<DefaultVisitProductDetails> GetPackageDetailsList()
        {
            List<DefaultVisitProductDetails> lstResult = null;
            #region Getting lstPackageDetails from tempData, if does not exists, generate new list!

            var tmp = TempData.Peek("_lstPackageDetails");
            if (tmp != null)
            {
                lstResult = JsonConvert.DeserializeObject<List<DefaultVisitProductDetails>>(tmp.ToString(), new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
            }

            if (lstResult == null)
            {
                lstResult = new List<DefaultVisitProductDetails>();
            }

            #endregion

            return lstResult;
        }

Where is my problem & how to solve it?
Thanks in advance.

Problem in JsonConvert.SerializeObject to serialize list of entities to TempData.

$
0
0

Hi

I have a main problem which i created in thread (please read it before this thread). Anyway, After a lot of digging & debugging my code, I Think the problem is related to serializing lstPackageDetails to TempData via this method :

private void SetPackageDetailsList(List<DefaultVisitProductDetails> lstPackageDetails)
{
	TempData["_lstPackageDetails"] = JsonConvert.SerializeObject(lstPackageDetails, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}

I call above method in my Edit action to serialize my packageDetails & store in TempData, :

public IActionResult GetPackageDetails(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Guid gidPackageHeaderRowID = Guid.Parse(id);
            List<DefaultVisitProductDetails> packageDetails = _dbContext.DefaultVisitProductDetails.Where(d => d.DefaultVisitProductHeaderRowID == gidPackageHeaderRowID).OrderBy(d => d.ProductID).Include(d => d.Product).ToList();            
            this.SetPackageDetailsList(packageDetails); // Call it!

            return PartialView("_PackageDetailsList", packageDetails);
        }

The problem is that, after calling 'SetPackageDetailsList' method, all packageDetails which have my productIDs being loaded into dbContext!

I think there is a bug in JsonConvert (or someThing else).

Can anybody have idea to store my packageDetails list into TempData without JsonConvert (or solve above problems)?

Thanks in advance

Fail to add multiple attachments to mail message in net core web app

$
0
0

Hi,

I try to construct and send an email message in a web net core app. The message need to have maximal 3 attachments, provided by the user who navigates the site. First is mandatory, and at least one from the two remaining attachments is also mandatory.

If I attach only one (e.g. first) attachment, all is ok. But when I attach at least 2 attachments, I have an error.

The relevant portions of code are bellow (the model, the view, and the controller). At the very bottom is the error:

/*Relevant part of model*/

public class Inscrieri.Inima.Models
{
//
        public IFormFile CopieCN { get; set; }
        public IFormFile CopieCIT { get; set; }
        public IFormFile CopieCIM { get; set; }
//
}


/*Relevant part of view*/

<div class="separator"></div><div><strong>Certificat de Nastere Copil</strong><p> (in format *.jpg sau *.png):</p></div><div>
                @Html.TextBoxFor(model => model.CopieCN, new { type = "file" })</div><div><strong>Act de Identitate Tata:</strong><p> (in format *.jpg sau *.png):</p></div><div>
                @Html.TextBoxFor(model => model.CopieCIT, new { type = "file" })</div><div><strong>Act de Identitate Mama:</strong><p> (in format *.jpg sau *.png):</p></div><div>
                @Html.TextBoxFor(model => model.CopieCIM, new { type = "file" })</div><div class="separator"></div><div class="clearfix"></div><div><input type="submit" value="Trimite" /></div><div class="separator"></div><span style="color:green">@ViewBag.Message</span>


/*Relevant part of controller*/

        [HttpPost]
        public IActionResult Index(EmailModel model)
        {
            using (MailMessage mm = new MailMessage("sender.email@gmail.com", "first.recipient@email.com, second.recipient@email.com"))
            {
                mm.Subject = "Cerere de inscriere pentru: " + model.Prenume + " " + model.Nume;
                mm.Body = "Va rog sa aprobati inscrierea copilului " + model.Prenume + " " + model.Nume + " nascut(a) la data de " + model.DataNasterii + ", avandu-i ca parinti pe " + model.NumeTata + " si " + model.NumeMama + " in grupa: " + model.Grupa+". "+ Environment.NewLine + "Locul de munca al parintilor: " + model.LocDeMunca;
                mm.IsBodyHtml = true;
                mm.Priority = MailPriority.High;


                //atasam CN copil
                if (model.CopieCN.Length > 0)
                {
                    string fileNameCN = Path.GetFileName(model.CopieCN.FileName);
                    Attachment file1 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCN, MediaTypeNames.Application.Octet);
                    mm.Attachments.Add(file1);
                    //file1.Dispose();
                    //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCN, MediaTypeNames.Application.Octet));
                }
                //atasam CI tata
                if (model.CopieCIT.Length > 0)
                {
                    string fileNameCIT = Path.GetFileName(model.CopieCIT.FileName);
                    Attachment file2 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCIT, MediaTypeNames.Application.Octet);
                    mm.Attachments.Add(file2);
                    //fie2.Dispose();
                    //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCIT, MediaTypeNames.Application.Octet));
                }
                //atasam CI mama
                if (model.CopieCIM.Length > 0)
                {
                    string fileNameCIM = Path.GetFileName(model.CopieCIM.FileName);
                    Attachment file3 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCIM, MediaTypeNames.Application.Octet);
                    mm.Attachments.Add(file3);
                    //file3.Dispose();
                    //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCIM, MediaTypeNames.Application.Octet));
                }

                //here we try another approach for multi attach
                //first we create a list of files
                List<string> AttachList = new List<string>();
                AttachList.Clear();
                if (model.CopieCN.Length > 0)
                {
                    AttachList.Add(Path.GetFileName(model.CopieCN.FileName));
                }
                if (model.CopieCIT.Length > 0)
                {
                    AttachList.Add(Path.GetFileName(model.CopieCIT.FileName));
                }
                if (model.CopieCIM.Length > 0)
                {
                    AttachList.Add(Path.GetFileName(model.CopieCIM.FileName));
                }
                //

                foreach (var filepath in AttachList) //this is commented in real life
                {
                    var attachment = new Attachment(filepath);   // here you can attach a file as a mail attachment  
                    mm.Attachments.Add(attachment);
                }
                //

                using (SmtpClient smtp = new SmtpClient())
                {
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential NetworkCred = new NetworkCredential("sender.email@gmail.com", "@Password@");
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;

                    try {
                        smtp.Send(mm);
                    ViewBag.Message = "Mesaj trimis cu succes."; }
                    catch (Exception ex) {
                        ViewBag.Message = ("S-a produs o eroare: {0}", ex.ToString());
                    }
                    finally
                    {
                        //Clear all the form's fields
                    }


            }
            }

            return View();
            //return new RedirectResult("https://www.some-site.com");
        }

Here comes the error:

/*Error rised*/

/*line 105 is: smtp.Send(mm); */

(S-a produs o eroare: {0}, System.Net.Mail.SmtpException: Failure sending mail. ---> System.InvalidOperationException: The inner stream position has changed unexpectedly. at Microsoft.AspNetCore.Http.ReferenceReadStream.VerifyPosition() at Microsoft.AspNetCore.Http.ReferenceReadStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Mime.MimePart.Send(BaseWriter writer, Boolean allowUnicode) at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer, Boolean allowUnicode) at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope, Boolean allowUnicode) at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message) at Inscrieri.Inima.Controllers.HomeController.Index(EmailModel model) in C:\Users\laurentiu\source\repos\Inscrieri.Inima\Inscrieri.Inima\Controllers\HomeController.cs:line 105)

Any hint will be appreciated.

Regards

Get data from active directory using react and asp.net core

$
0
0

Can someone share code to retrieve user details along with thumbnail image to be displayed basis the input SamAccountName. This has to be accomplished using asp.net core and react. I am pretty new to this technology, please help.

My trials till now:

Controller:
public Image ourTeam()
{
var userDetails = db.users.Where(x=>x.saMAccountName == "someUsername").FirstOrDefault();

Image image = GetImage(userDetails.CN); //I get image data
var stream = new System.IO.MemoryStream();

if (image != null)
image.Save(stream, ImageFormat.Jpeg);

return image;
}

Component
import * as React from 'react';
import { RouteComponentProps } from 'react-router';

interface FetchImageDataState {
imageList: ImageData[];
loading: boolean;
}

export class OurTeam extends React.Component<RouteComponentProps<{}>, FetchImageDataState> {
constructor() {
super();
this.state = { imageList: [], loading: true }; //initialize to default

fetch('api/Home/ourTeam')
.then(response => response.json() as Promise<ImageData[]>)
.then(data => {
this.setState({ imageList: data, loading: false });
});
}


public render() {

let contents = this.state.loading
? <p><em>Loading...</em></p>
: this.renderImageTable(this.state.imageList);
return <div>
<h1>Team</h1>{contents}
</div>;
}

private renderImageTable(imageList: ImageData[]) {
return <div className='table'>{
imageList.map(x =>
<img src={x.byteData} alt={x.CN} />)
}</div>;}
}

export class ImageData {
CN: string = "";
byteData: string = "";
}

how to make attempt login failed for user per no of try per period ?

$
0
0

problem

how to make attempt login failed for user per no of try per period ?

i work on asp.net core 2.2 web api 

i need to write function on login http post make count to failed login attempt within period of time

failed login within period  10 minutes the if it exceed it will redirect to url xxxx .

[HttpPost(Contracts.ApiRoutes.Login.UserLogin)]
public IActionResult PostUserLogins([FromBody]Users user)
{

if (isvalid)

{

}

else

{

}

}

my function structure as above ?

CORS Policy - driving me insane

$
0
0

Hey everyone.  

I'm learning .NET Core (currently using version 3.0.1, and ASPNETCORE_ENVIRONMENT is currently in development mode) for development and have built a project that uses the framework for a WebAPI backend, and Angular for the frontend.  Right now I'm running into an issue where no matter how I setup my CORS options, I constantly throw the following error when an API return event forwards the user to a new webpage.  

Right now, I have have method in my API that allows a user to create a new password (using Microsoft Identity) when they click the Forgot Password link in the email they receive.  When the click submit the password is changed and if successful, they are forwarded to the password changed successfully page. Here is that method from the API: 

        [HttpPost("ResetPassword")]
        public async Task<IActionResult> ResetPassword(PasswordResetDto passwordResetDto)
        {
            if (ModelState.IsValid)
            {
                var result = await _resetPasswordRepository.ResetPasswordAsync(passwordResetDto);
                if (result != null)
                    return BadRequest("Invalid details");
            }
            return Redirect($"{_configuration["ViewUrl"]}/#/passwordchanged");
        }

When the return Redirect is hit, the browser throws the following error and no redirect occurs: 

Access to XMLHttpRequest at 'http://localhost:5000/api/auth/forgotpassword' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In my startup.cs file I have the following entered (see the highlighted lines): 

public void ConfigureServices(IServiceCollection services)
        {
            // Add Microsoft Identity Services to the services method
            IdentityBuilder builder = services.AddIdentityCore<User>(opt => 
            {
                // Add weak password ability
                opt.Password.RequireDigit = false;
                opt.Password.RequiredLength = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = false;
                // opt.SignIn.RequireConfirmedEmail = true;
            }).AddDefaultTokenProviders();

            

            // Add the DbContext method to services so it can be called from other aread of the webapp, and call the database connection string.
            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores<DataContext>();
            builder.AddRoleValidator<RoleValidator<Role>>();
            builder.AddRoleManager<RoleManager<Role>>();
            builder.AddSignInManager<SignInManager<User>>();

            // Add the JWT Token Service
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)  // Add authentication as a service.  Tell DotNet Core the type of authentication
                .AddJwtBearer(options => {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                            .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });

            // Add roles based authorization policies
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireGlobalAdminRole", policy => policy.RequireRole("GlobalAdmin"));
                options.AddPolicy("RequireClientAdminRole", policy => policy.RequireRole("GlobalAdmin", "ClientAdmin"));
                options.AddPolicy("RequireLocationAdminRole", policy => policy.RequireRole("GlobalAdmin", "ClientAdmin", "LocationAdmin"));
                options.AddPolicy("RequireReportsOnlyRole", policy => policy.RequireRole("GlobalAdmin", "ClientAdmin", "LocationAdmin", "ReportsOnly"));
            });

            // Add all other services
            services.AddDbContext<DataContext>(x => x.UseSqlite
                (Configuration.GetConnectionString("DefaultConnection")));          // Make the DbContext service available to the rest of the application
            services.AddControllers(options => 
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddNewtonsoftJson();                                                   // Make the Controllers service available to the rest of the application
            services.AddCors();                                                     // Make the CORS policy service available to the rest of the application
            services.AddAutoMapper(typeof(ClientRepository).Assembly);              // Make AutoMapper service available to the rest of the application
            services.AddScoped<IClientRepository, ClientRepository>();              // Make the client repository service available to the rest of the application
            services.AddScoped<ILocationsRepository, LocationsRepository>();        // Make the locations repository service available to the rest of the application
            services.AddScoped<IOrganizationRepository, OrganizationsRepository>(); // Make the Organizations repository service available to the rest of the application
            services.AddTransient<IMailRepository, MailRepository>();               // Mail service from SendGrid
            services.AddScoped<IResetPasswordRepository, ResetPasswordRepository>();// Make the reset password service available to the rest of the application
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // This is the middleware that intracts with the app and the API.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // If in production mode, pass any errors so they can be read
                app.UseExceptionHandler(builder => {
                    builder.Run(async context => {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get<IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            // app.UseHttpsRedirection();

            // Routes all requests to the appropriate location 
            app.UseRouting();

            // Defines a CORS policyModify the http headers to prevent the 'Access-Control-Allow-Origin' error from blocking the API.  
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            // Controls authorization for logging users in and determines what areas they have access to
            app.UseAuthentication();
            app.UseAuthorization();

            // As the web applications starts up, this maps the controller endpoints into the web application so the web application knows how to route the requests.
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

To add context, the data is being passed to the API using from my angular Auth service using the following: 

  resetChangePassword(email: string, token: string, newPassword: string, confirmPassword: string) {
    return this.http.post(`${this.baseUrl}` + `resetpassword`, { newPassword, confirmPassword, token, email });
  }

Any ideas on what I am doing wrong here?  I have also tried reconfiguring the CORS policies using different methods with zero success such as:

ConfigureServices:

services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
); });

Configure:

app.UseCors("CorsPolicy");

I just cant seem to get around this.  Any insight will be greatly appreciated. 


what does [parameter] before method means?

$
0
0

what does [parameter] before method means?

How to access ViewData from external javascript ?

$
0
0

Hi

i've use this external javascript function to access ViewData variable(s) :

function deleteOrderItem(orderID) {
    if (confirm('Are you sure want to delete this item?')) {$.ajax({
            type: "POST",
            url: "DeleteOrder",
            data: { id: orderID },
            success: function () {
                setTimeout(function () {
                    debugger;
                    var personID = "@ViewData['_personID']";
                    viewItem(personID);
                }, 500)
            }
        });
    }
}

But at runTime, when i'm using developer tools, the personID contains @ViewData[_personID] as text and not accessing real viewData which i've set in my action method!

Here is my action method :

// POST: Orders/Delete/5
        [HttpPost]
        public async Task<IActionResult> DeleteOrder(int id)
        {
            var orders = await _dbContext.Orders.FindAsync(id);

            ViewData["_personID"] = orders.PersonId;

            _dbContext.Orders.Remove(orders);
            await _dbContext.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

Where is the problem & how to solve it?

Thanks in advance

guidance to choose appropriate web programming language

$
0
0

hi there, im phd student of entreprenership and i am 31 years old. in the past i used visual studio web form. after many years for developing my e-business ideas i decide to come back to web development world but im very dazzy about what framework to choose? here is my priorities:

1. i dont want to be a professional web developer just i want to implement my ideas to build small websites

2. i want a web programming framework that has huge free premade(third party) source codes or libraries or packages that i can use them in my project easily

3. its errors be very clear so that i can find whats wrong with my codes easily

4. with that language or framework i can write server side + client side codes!

5. has free tutorial or learning resources.

6. easily to learn and find.

Important: i hate developing environments that have very separate tools(i mean using terminal or cmd), i like environments like asp.net core that all of things are managlble in ONE place and you can do anything using mouse click not typing long commands in terminals or cmd

honestly i am confused between asp.net core, laravel and django.

please give me a guidance about this, thanks

Gmail API in asp.net core

$
0
0

Hi

Any one has any idea how to use the Gmail API to send the email from asp.net core with User Identity rather than Sendgrid application . 

Pol

The property 'JobTitle' is not a navigation property of entity type 'Job'. The 'Include(string)' method can only be used with a '.' separated list of navigation property names.

$
0
0

I am attempting to read related data across three tables in ASP.NET CORE MVC 2.2 with Entity Framework Core.

To be more specific I am using this tutorial to build my project https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/read-related-data?view=aspnetcore-2.2. I am using Eager Loading to read Job.JobTitle all the way from the Problem Index method. Reading this I realize I want to find where Problem navigation property that contains the Job entity of the JobTitle that the Problem is assigned to. But That would be a many to many relationship so I have thrown in a Result composite table to stop that.

From my research, adding the foreign key attributes can help. Which hasn’t. So how can I Render the JobTitle that the problem belongs too in the job index?

Job class:

public class Job
    {  

        public int ID { get; set; }
        public string JobTitle { get; set; }
        public string JobDescription { get; set; }
        public DateTime JobStartDate {get;set;}
        public DateTime JobDeadline {get;set;}
        public bool JobIsComplete{get;set;}
        
        public ICollection<Result> Results {get;set;}
    }

Result class:

    public class Result
    {        
        public int JobID {get;set;}
        public int ProblemID {get;set;}
        [ForeignKey("Job")]
public Job Job {get;set;} [ForeignKey("Problem")] public Problem Problem {get;set;} }

Problem class:

public class Problem
    {
        public int ID {get;set;}       
        public string ProblemTitle {get;set;}
        public string ProblemDescription {get;set;}
        public DateTime ProblemStartDate {get;set;}
        public string ProblemFileAttachments {get;set;}
        public int ProblemSeverity {get;set;}
        public bool ProblemComplete {get;set;}
public ICollection<Result> Result {get;set;} }

Index method of ProblemController (please see comment to find bug):

public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["ProblemIDSortParm"] = String.IsNullOrEmpty(sortOrder) ? "ProblemID_desc" : "";
            ViewData["ProblemTitleSortParm"] = String.IsNullOrEmpty(sortOrder) ? "ProblemTitle_desc" : "";
            ViewData["ProblemStartDateSortParm"] = sortOrder == "ProblemStartDate" ? "ProblemStartDate_desc" : "ProblemStartDate";
            ViewData["ProblemSeveritySortParm"] = sortOrder == "ProblemSeverity" ? "ProblemSeverity_desc" : "ProblemSeverity";
            ViewData["ProblemCompleteSortParm"] = sortOrder == "ProblemComplete" ? "ProblemComplete_desc" : "ProblemComplete";          
            ViewData["CurrentFilter"] = searchString;
            //READ RELATED DATA HERE
            var problems = from p in _context.Problems
                .Include(p => p.Result)
                    .ThenInclude(j => j.Job.JobTitle)                    
                            select p;
            //END OF READ RELATED DATA
            if(searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            if(!String.IsNullOrEmpty(searchString))
            {
                problems = problems.Where(p => p.ProblemTitle.Contains(searchString)
                                            || p.ProblemDescription.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "ProblemID_desc":
                    problems = problems.OrderByDescending(p => p.ID);
                    break;
                case "ProblemTitle_desc":
                    problems = problems.OrderByDescending(p => p.ProblemTitle);
                    break;
                case "ProblemStartDate":
                    problems = problems.OrderBy(p => p.ProblemStartDate);                    
                    break;
                case "ProblemStartDate_desc":
                    problems = problems.OrderBy(p => p.ProblemStartDate);                    
                    break;
                case "ProblemSeverity":
                    problems = problems.OrderBy(p => p.ProblemSeverity);
                    break;
                case "ProblemSeverity_desc":
                    problems = problems.OrderByDescending(p => p.ProblemSeverity);
                    break;   
                case "ProblemCompleteSortParm":
                    problems = problems.OrderBy(p => p.ProblemComplete);
                    break;
                case "ProblemCompleteSortParm_desc":
                    problems = problems.OrderByDescending(p => p.ProblemComplete);
                    break; 
                default:
                    problems = problems.OrderBy(p => p.ProblemTitle);
                    break;                 
            }

            int pageSize = 20;            
            return View(await PaginatedList<Problem>.CreateAsync(problems.AsNoTracking(), pageNumber ?? 1, pageSize));
        }

ProblemIndex view, (please see comment to find where I am having problem):

@model PaginatedList<Pitcher.Models.Problem>

@{
    ViewData["Title"] = "Problems";
}<h1>Index</h1><p><a asp-action="Create">Create New</a></p>
 @*COPY AND PASTE THIS TAG HELPER METHOD TEXTBOX CUSTOMIZATION INTO OTHER VIEWS TO ENABLE SEARCHING.*@<form asp-action="Index" method="get"><div class="form-actions no-color"><p>
            Find by name: <input type="text" name="SearchString" value="@ViewData["currentFilter"]" /><input type="submit" value="Search" button type="button" class="btn btn-primary" /> |<a asp-action="Index">Back to Full List </a></p></div></form><table class="table table-hover"><thead><tr><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemIDSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem ID</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemTitleSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem Title</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemStartDateSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem Start Date</a></th><th>
                Problem File Attachments</th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemSeveritySortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">ProblemSeverity</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemCompleteSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">ProblemComplete</a></th><th>
                Job Title</th><th></th></tr></thead><tbody>
@foreach (var item in Model) {<tr><td>
                @Html.DisplayFor(modelItem => item.ID)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemTitle)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemDescription)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemStartDate)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemFileAttachments)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemSeverity)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemComplete)</td>
            @* RENDER Job Title here *@
                @Html.DisplayFor(modelItem => item.Result)
            @* END render Job Title here *@<td><a asp-action="Edit" asp-route-id="@item.ID" button type="button" class="btn btn-primary btn-block" >Edit</a> <a asp-action="Details" asp-route-id="@item.ID" button type="button" class="btn btn-info btn-block">Details</a> <a asp-action="Delete" asp-route-id="@item.ID" button type="button" class="btn btn-primary btn-block">Delete</a></td></tr>}</tbody></table>
@{
    var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}<a asp-action="Index"
   asp-route-sortOrder="@ViewData["CurrentSort"]"
   asp-route-pageNumber="@(Model.PageIndex - 1)"
   asp-route-currentFilter="@ViewData["CurrentFilter"]"
   class="btn btn-secondary @prevDisabled"
   button type="button">
    Previous</a><a asp-action="Index"
   asp-route-sortOrder="@ViewData["CurrentSort"]"
   asp-route-pageNumber="@(Model.PageIndex + 1)"
   asp-route-currentFilter="@ViewData["CurrentFilter"]"
   class="btn btn-secondary @nextDisabled"
   button type="button">   
    Next</a>





Viewing all 9386 articles
Browse latest View live


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