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

System.FormatException: 'String was not recognized as a valid DateTime.'

$
0
0

I am trying to convert the string variable into datetime 

string clockingTime = attlog.AttendanceDate + " " + attlog.Hrs + ":" + attlog.Mins + ":00";
DateTime clockDate = DateTime.ParseExact(attlog.AttendanceDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) But the error is coming is as given below

System.FormatException: 'String was not recognized as a valid DateTime.' The value  10/07/2019 7:10:00 is stored in the variable clockingTime . Please help me to convert it into datetime

Regards

Pol


How to unit test uploading file feature?

$
0
0

Hi,

I implemented a uploading file feature, it can work well. But I am trying use mock to do a unit test. 

Html is:

<input #profileImage type="file" (change)="uploadPofileImage(profileImage.files)"/>Upload

Js is :

public uploadPofileImage(files) {
	// some code here

	const formData = new FormData();
	for (let file of files)
		formData.append(file.name, file);
	
	const uploadReq = new HttpRequest("POST", "XXX/Upload", formData, {
		reportProgress: true,
	});

	this.http.request(uploadReq).subscribe(event => {

	// some code is here
}

Backend code:

public void Upload()
{
	var file = Request.Form.Files[0];
	try
	{
		using (var stream = new FileStream("d:\\aaa.txt", FileMode.Create))
		{
			file.CopyTo(stream);
		}
	}
	catch (Exception e)
	{
	}
}

I try to mock these objects and also googled something but all of them do not work. any idea? Thanks a lot

Session Id is changed when a request is coming.

$
0
0

hi,

When a request is coming, every time the session id is different. For example, same web page just refresh it, the session id is different.

So is there any way to make the id keeps same? 

Thanks a lot.

Working with .resx files programnatically in ASP.NET Core

$
0
0

Hello, I want to know if there is a way to work with .resx files programmatically like : add new ,resx file to project, edit existing .resx file or delete .resx files dynamically by code behind.

I have to mention that i don't use visual studio, I am using VSCode and as you know VSCode does not have Resource designer.

Is it a good idea to start using ASP.NET Core

$
0
0

I wonder if this is a good place to post my question but I could not find any convincing answers searching on the web.
I am thinking about starting to use ASP.NET Core for my future projects. Current version of .NET Core is 2.2 and version 3 will be released soon this year of 2019.
So, if I start a project now it will be using version 2.2 and I wonder how much difference will be with version 3. Is it a good idea to start using version 2.2 or should I wait for version 3? (Maybe version 3.1 which will be LTS). How hard would be to port a project from version 2.2 to version 3.?

Respectfully,
Jorge Maldonado

Mocking EF Core DBContext with ChangeTracker

$
0
0

I have a unit test that calls on a DBContext mocked using Moq. The function being tested does this before calling AddAsync and SaveChangesAsync:

context.ChangeTracker.Entries().Where(e => e.Entity != null).ToList().ForEach(e => e.State = EntityState.Detached);

In my unit test, I get an error that ChangeTracker is null. Is there a way for me to Moq this so it's not null?

This is the test I have tried, but it does not work. I get an error that the constructor argument for mockChangeTracker is not the correct type. 

var mockSet = new Mock<DbSet<DataFile>>();

            var mockContext = new Mock<DataModelerContext>();
            mockContext.Setup(m => m.DataFile).Returns(mockSet.Object);
            mockContext.Setup(m => m.AddAsync(It.IsAny<DataFile>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult((EntityEntry<DataFile>)null));
            mockContext.Setup(m => m.SaveChangesAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(1));

            IEnumerable<EntityEntry> entries = new List<EntityEntry>();
            var mockChangeTracker = new Mock<ChangeTracker>(MockBehavior.Strict, mockContext.Object);
            mockChangeTracker.Setup(c => c.Entries()).Returns(entries);
            mockContext.Setup(m => m.ChangeTracker).Returns(mockChangeTracker.Object);

            var mockServiceProvider = new Mock<IServiceProvider>();
            mockServiceProvider.Setup(sp => sp.GetService(It.IsAny<Type>())).Returns(mockContext.Object);

            DatabaseRepository databaseRepository = new DatabaseRepository(mockServiceProvider.Object);

            bool succesfullyAddedToDbSet = await databaseRepository.AddNewEntryToDatabaseAsync(new DataFile(), "DataFile");
            Assert.True(succesfullyAddedToDbSet);

I realize I shouldn't mock the class directly, but I haven't had any luck trying to do the interface that ChangeTracker implements (IInfrasctructure<IStateManager>). Is there a better way to do this?

Thank you!

Multiple Authentication and Authorization options

$
0
0

Hi 

I wonder if i use multiple authentication and authorization option in the single project. I have a user with in our azure directory but their have user outside the directory and have not microsoft account or use other email like gmail and yahoo. Can use the AD authentication option and other option together ?

Please give me an example or idea that i can start with it.

Thanks

ViewState error on Logout page after clearing out session cookies and then clicking button

$
0
0

Hi,

My application has a Logout page, which tells the user 'You have been logged out". So, on Page_load, I clear out all the session variables cookies. But this page also has a 'LOGIN AGAIN' button. When I click this, it gives me 'invalid Viewstate' error'. If I comment out the cookie  and session variable clearing in Page_Load, the error does not occur.  How can I ignore the change in the ViewState, so it actually redirects to the Home page when button is clicked, still clearing out session and cookies. Attaching my code.

-Rashmi

public partial class Admin_Logout : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Request.QueryString["Error"] != null)
                {
                    if (Request.QueryString["Error"].ToString().ToUpper() == "YES")
                    {
                        lbllogout.Text = "Please contact administrator.";
                        //creates a log file or appends to existing log file and writes the error output to the file                
                    }
                }
                if (Request.QueryString["ErrorValue"] != null)
                {
                    lbllogout.Text = "Please contact administrator.\n";
                    lbllogouttxt.Text = Sanitizer.GetSafeHtmlFragment(Request.QueryString["ErrorValue"].ToString());
                }

                Session["LoginEmplId"] = null;
                Session["LoginFullName"] = null;
                Session.Abandon();
                Session.Clear();
                Session.RemoveAll();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Buffer = true;
                Response.Cache.SetNoStore();
                Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
                Response.Expires = -1000;
                Response.Cookies.Clear();
                Response.CacheControl = "no-cache";
                string[] cookies = Request.Cookies.AllKeys;
                foreach (string cookie in cookies)
                {
                    if (Request.Cookies[cookie] != null)
                    {
                        HttpCookie myCookie = new HttpCookie((cookie).Replace("\r", string.Empty)
                            .Replace("%0d", string.Empty)
                             .Replace("%0D", string.Empty)
                             .Replace("\n", string.Empty)
                             .Replace("%0a", string.Empty)
                             .Replace("%0A", string.Empty)
                            );
                        myCookie.Expires = DateTime.Now.AddDays(-1d);
                        Response.Cookies.Add(myCookie);
                    }
                }
                if (Response.Cookies["SMSESSION"] != null)
                {
                    HttpCookie myCookie = new HttpCookie("SMSESSION");
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                    Response.Cookies.Add(myCookie);
                }


            }
            catch (HttpRequestValidationException)
            {
                Response.Redirect("~/Home.aspx");
            }
        }
        protected void loginbutton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string[] cookies = Request.Cookies.AllKeys;
                foreach (string cookie in cookies)
                {
                    if (Request.Cookies[cookie] != null)
                    {
                        HttpCookie myCookie = new HttpCookie(cookie);
                        myCookie.Expires = DateTime.Now.AddDays(-1d);
                        Response.Cookies.Add(myCookie);
                    }

                }
                Session["LoginEmplId"] = null;
                Session["LoginFullName"] = null;
                Session.Abandon();
                Session.Clear();
                Session.RemoveAll();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Buffer = true;
                Response.Cache.SetNoStore();
                Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
                Response.Expires = -1000;
                Response.CacheControl = ("no-cache");
                Response.Cookies.Clear();
                Response.Redirect("~/Home.aspx");
            }
        }
    }
}




Where clause yields no results

$
0
0

hi guys

in my home controller, I am trying to filter out database products e.g. mugs or tshirts

HOwever my code yields no results when I add the include and where clause, at runtime. It shows the results panel and all values exist, but nothing is displayed in the razor view.

If however I remove the include and where clause, then I get all the results from the db. Please advise

Ehi

  [Route("/{C}")]
        public async Task<IActionResult> Product(String C)
        {

            return View(await _context.Departments_SubCategory_Registration.Include(c => c.Departments_Category_Registration)


                .Where(d => d.Departments_Category_Registration.Category_Name == C)

                  .Where(r => r.IsEnabled == true).Select(u => new Departments_SubCategory_Registration



                 {

                     CategoryID = u.CategoryID,
                     SubCategory_Name = u.SubCategory_Name

                 }).ToListAsync();



//and my razor view


@model IEnumerable<Root.Models.Department.Departments_SubCategory_Registration>

@{
    ViewData["Title"] = "Index";
}<h1>Index</h1><p><a asp-action="Create">Create New</a></p><table class="table"><thead><tr><th>
                @Html.DisplayNameFor(model => model.CategoryID)</th><th>
                @Html.DisplayNameFor(model => model.SubCategory_Name)</th><th>
                @Html.DisplayNameFor(model => model.EntryDate)</th><th>
                @Html.DisplayNameFor(model => model.Description_Short)</th><th>
                @Html.DisplayNameFor(model => model.Description_Detailed)</th><th>
                @Html.DisplayNameFor(model => model.Notes)</th><th>
                @Html.DisplayNameFor(model => model.UniqueId)</th><th>
                @Html.DisplayNameFor(model => model.IsEnabled)</th><th></th></tr></thead><tbody>
        @foreach (var item in Model)
        {<tr><td>
                    @Html.DisplayFor(modelItem => item.CategoryID)</td><td>
                    @Html.DisplayFor(modelItem => item.SubCategory_Name)</td><td>
                    @Html.DisplayFor(modelItem => item.EntryDate)</td><td>
                    @Html.DisplayFor(modelItem => item.Description_Short)</td><td>
                    @Html.DisplayFor(modelItem => item.Description_Detailed)</td><td>
                    @Html.DisplayFor(modelItem => item.Notes)</td><td>
                    @Html.DisplayFor(modelItem => item.UniqueId)</td><td>
                    @Html.DisplayFor(modelItem => item.IsEnabled)</td><td><a asp-action="Edit" asp-route-id="@item.SubCategoryID">Edit</a> |<a asp-action="Details" asp-route-id="@item.SubCategoryID">Details</a> |<a asp-action="Delete" asp-route-id="@item.SubCategoryID">Delete</a></td></tr>
        }</tbody></table>

my model

  public class Departments_SubCategory_Registration
    {
        [Key]
        public int SubCategoryID { get; set; }              // This is the PK


        public int CategoryID  { get; set; } // this is a FK
        [ForeignKey("SubCategoryID")]
        public Departments_Category_Registration Departments_Category_Registration { get; set; }
        public string SubCategory_Name { get; set; }
        public DateTime EntryDate { get; set; }
        public string Description_Short { get; set; }
        public string Description_Detailed { get; set; }
        public string Notes { get; set; }

        public Guid UniqueId { get; set; }
        public bool IsEnabled { get; set; }
        

    }

Adding references to of system under test to MSunit test project in asp.net core

$
0
0

How project reference should be added in asp.net core testproject for project system under test.<br>
Should it be a .dll or it should be project file?
We are using asp.net core 2.2, for main project as well as it's Unit test project with MSTest.

Image resize and crop

$
0
0

Hello

How I can crop and resize images in .net core?

Its any chance use Webimage from asp.net mvc ? 

How to match the changed url segment

Two models in one view

$
0
0

I have two models: Response and Item. I want to use properties from both models. How do i do that:

public partial class Response
    {

        /// <summary>
        /// Gets or sets a specific/unique ID for a certain response (Primary Key --> Integer)
        /// </summary>
        public int ResponseId { get; set; }

        /// <summary>
        /// Gets or sets a specific ID for a specific discussion (Integer)
        /// </summary>
        public int DiscussionId { get; set; }

        /// <summary>
        /// Gets or sets a specific ID for a certain User (Integer)
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// Gets or sets the response text (Varchar)
        /// </summary>
        public string Responses { get; set; }

        /// <summary>
        /// Gets or sets the date in which a response is created (Date)
        /// </summary>
        public DateTime DateCreated { get; set; }

       
        /// <summary>
        /// Gets or sets Discussions of type Discussion 
        /// </summary>
        public Discussion Discussions { get; set; }
    }
public partial class Item
    {
        public Item()
        {
            Discussions = new HashSet<Discussion>();
            Votes = new HashSet<Vote>();
        }

        /// <summary>
        /// Gets or sets a specific/unique ID for a certain item (Primary Key --> Integer)
        /// </summary>
        public int ItemId { get; set; }

        /// <summary>
        /// Gets or sets a specific ID for a certain Packet (Foreign Key --> Integer)
        /// </summary>
        public int? PacketId { get; set; }

        /// <summary>
        /// Gets or sets a specific ID for a certain category (Foreign Key --> Integer)
        /// </summary>
        public int? CategoryId { get; set; }

        /// <summary>
        /// Gets or sets a specific ID for a certain Voting Type (Foreign Key --> Integer)
        /// </summary>
        public int? VotingTypeId { get; set; }

        /// <summary>
        /// Gets or sets a specific Title for am Item (Varchar)
        /// </summary>
        public string ItemTitle { get; set; }

        /// <summary>
        /// Gets or sets a specific order in which an item will be displayed (Integer)
        /// </summary>
        public int? DisplayOrder { get; set; }

        /// <summary>
        /// Gets or sets a specific File name for a certain item (Varchar)
        /// </summary>
        public string ItemFileName { get; set; }

        /// <summary>
        /// Gets or sets a specific File URL for a certain item (Varchar)
        /// </summary>
        public string ItemFileUrl { get; set; }

        /// <summary>
        /// Gets or sets a specific HTML URL for a specific item (Varchar)
        /// </summary>
        public string ItemHtmlUrl { get; set; }     

    }

I know using the two @model tags at the top is not the correct way but don't know how to bring in two models in one view.

View:

@model F.E.Domain.Models.Response
@model F.E.Domain.Models.Item

@{
    ViewData["Title"] = "Board Meeting";
    //Layout = "~/Views/EditProfile/Index.cshtml";
}<h2>Current Board Meeting</h2><div class="row"><div class="col-md-4"><div class="form-group"><label asp-for="DateCreated" class="control-label"></label><input asp-for="DateCreated" type="date" asp-format="{0:MM/dd/yyyy}" class="form-control" /></div><div class="form-group"><label asp-for="ItemTitle" class="control-label"></label><input asp-for="ItemTitle" class="form-control" /></div></div></div><div>
        @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |<a asp-action="Index">Back to List</a></div>

Problem posting form

$
0
0

There all this sound simple but it got me all thinking.

I created a simple form and am suppose to post values to the controller but it just not working. I dont know what the problem is. Each time I submit the form just does not show sign that it redirecting or submitting to the view.

 [Bind("PromptID,Email,Password")]
    public class Setquery
    {
        [Required]
        public string PromptID { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
     
    }


 <form asp-action="activate" asp-controller="home" method="post"><h4>Use a local account to log in.</h4><hr /><div class="form-group"><label  asp-for="PromptID" class="control-label ">Promptfinder Subdomain:</label><div class="input-group"><div class="input-group-addon">http://</div><input asp-for="PromptID" class="form-control" placeholder="Username" aria_label="Username" aria_describedby="basic-addon1" required="required" /><div class="input-group-addon"><b>@Backupserver</b></div></div><span asp-validation-for="PromptID" class="text-danger"></span></div><div class="form-group"><label asp-for="Email"></label><input asp-for="Email" type="email" class="form-control"  required/><span asp-validation-for="Email" class="text-danger"></span></div><div class="form-group"><label asp-for="Password"></label><input asp-for="Password" class="form-control" required /><span asp-validation-for="Password" class="text-danger"></span></div><div class="form-group"><button type="submit" class="btn btn-primary">Log in</button><button type="reset" class="btn btn-default">Reset</button></div></form>



This is inside Homecontroller

  [HttpPost]
        [ValidateAntiForgeryToken]
        public Possetupobj Activate(Setquery model)
        {
            Response.WriteAsync(model.Email); return null;

}

Startup.cs

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

Foreach statement in .Net Core View

$
0
0

I want to loop thru each item for a View in the code below and not sure how to do it. This is what I have so far.

I haven't tried anything except this and have researched examples but none that meet this specific example.

<div class="row"><div class="col-md-4"><div class="form-group"><label asp-for="Packet.Meeting" class="control- 
        label">Date/Time Of Meeting:</label><input asp-for="Packet.Meeting" type="date" asp-format=" 
       {0:MM/dd/yyyy}" class="form-control" /></div>
        @foreach (var item in Model.Item)
        {<div class="form-group"><label asp-for="Item.ItemTitle" class="control-label"> </label><input asp-for="Item.ItemTitle" class="form-control" /></div>}            </div></div>

I want to show all of the item titles from the item model


Confused: How do I Get the count of each product ???

$
0
0

hi guys,

I have a hierarchy of categories to the product listing. 

How do I get the count of each product in my code below

something like this 

products = u.Department_Category_Registration.Products.Count();  (For each unique product e.g. TShirts(12 in stock) , Trousers (200 in stock) , shoes (100 in stock)

which has been commented out in the code below

thanks

return View(await _context.Departments_SubCategory_Registration.Include(c => c.Departments_Category_Registration)
                .Where(d => d.Departments_Category_Registration.Category_Name.Contains(C))
                  .Where(r => r.IsEnabled == true).Select(u => new Departments_SubCategory_Registration
                  {
                      CategoryID = u.CategoryID,
                      SubCategory_Name = u.SubCategory_Name,
                      EntryDate = u.EntryDate,
                      Description_Detailed = u.Description_Detailed,
                      Description_Short = u.Description_Short 

                    // e.g. I am trying to get 
                    // products = u.Department_Category_Registration.Products.Count();

                  }).ToListAsync());

Angular , asp.net core web api, azure active directory

$
0
0

Hi !!!

Please help me on how to got in this. Before I use azure ad as may authentication and it is easy to set up in the later asp.net mvc. But today is different story cause my team are using angular as FE and me the .net core web api following the MVVM pattern. The problem is how can i authenticate using azure ad i mean i have no idea to do that when integrate in angular. I tried to register my web api in azure ad, assigned user then when i test my api in postman i always got the error. Please have me a tutorial and other stuff to help to do this.

something wonder in my mind

the angular send me username and password then i pass it to azure ad then what happen ? should i throw token.

Please guide me i the step by step manner

Thanks and god bless

Are function return string can used when routing after controller or not controller/action ?

$
0
0

PROBLEM

can I use string function inside controller and replace action or not on asp.net core 2.1 ?


on asp.net core 2.1 when link to any web application i use default route
controller/action
can i use function return string as function ShowText() after controller
meaning employee/ShowText or must use Action Result ?
and when route to link employee/ShowText 
are this route will work ?

What I have tried:

employeecontrollerpublicstring ShowText()
{string show = "welcom ";return show ;
}

Windows Authentication in ASP.NET Core with Kestrel On Linux Plateform

$
0
0

Hello,
I am not a developer but I work with others on the implementation of windows authentication in net.core on Linux platform. Apparently, this is now possible directly with Kestrel in version 3 preview
So I tried, but without success. However, I followed the official MS documentation

"https://docs.microsoft.com/fr-fr/aspnet/core/security/authentication/windowsauth?view=aspnetcore-3.0&tabs=visual-studio=aspnetcore-3.0&tabs=visual-studio"

I tried the SDK 3.0 on two linux VMs, one in Debian 10 and the other in centOS 7.6.

I have configured my krb5.conf file correctly

I have registered my VM on my AD domain with success

I created a dot.net project with the command "dotnet new webapp --auth Windows".

I added the package "dotnet add package Microsoft.AspNetCore.Authentication.Negotiate --version 3.0.0-preview6.19307.2"

I created my SPN and keytab

setspn -S HTTP/mywebservice.coolcorp.priv pocvm

setspn -S HTTP/mywebservice@COOLCORP.COM pocvm

ktpass -princ HTTP/mywebservice.coolcorp.priv@COOLCORP.PRIV -pass myKeyTabFilePassword -mapuser COOLCORP\pocvm$ -pType KRB5_NT_PRINCIPAL -out c:\temp\pocvm.HTTP.keytab -crypto AES256-SHA1

When I test my keytab with the kinit command, it works.
kinit HTTP/mywebservice.coolcorp.priv@COOLCORP.PRIV -k -t /etc/keytab/pocvm.HTTP.keytab

I do have a kerberos ticket.

I set the location of my keytab as an environment variable.
export KRB5_KTNAME=/etc/keytab/pocvm.HTTP.keytab

I updated the startup file

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
            });
        services.AddMvcCore(options =>
    {
        options.EnableEndpointRouting = false; // TODO: Remove when OData does not causes exceptions anymore
    });

            services.AddRazorPages();
            services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseAuthentication();
            app.UseMvc();
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthorization();



            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

I launch my application: dotnet run

But when I display my site "mywebservice.coolcorp.priv", my username does not appear next to Hello.

Does anyone have any ideas or could they help me?

Asp.Net Core 2.2 - HTTP Error 500.0 - ANCM In-Process Handler Load Failure

$
0
0

I'm developing an application in Asp.Net 2.2.
I made the application public via FTP.
When I access the service with my application I get the following error.
The hosting service tells me that something is missing for me to do, and that the fault is not from the server.
The application works perfectly on localhost.

I'm waiting

HTTP Error 500.0 - ANCM In-Process Handler Load Failure
Common causes of this issue:
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.
Troubleshooting steps:
Check the system event log for error messages
Enable logging the application process' stdout messages
Attach a debugger to the application process and inspect
For more information visit: https://go.microsoft.com/fwlink/?LinkID=2028526

Viewing all 9386 articles
Browse latest View live


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