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

how to Convert and formatting iso dates in C#

$
0
0

I have this DateTime property in a DTO

 public DateTime Dob { get; set; }

and in my code I m running a for loop to match data and manipulate them as well,

 for (int i = 0; i < PatientInfo.Count; i++)

            {
                PatientInfo[i].Dob =
                DateTime.ParseExact(PatientInfo[i].Dob.ToString("MM/dd/YYYY"), "MM/dd/YYYY", DateTimeFormatInfo.InvariantInfo);

                PatientInfo[i].PartnerData = PartnerInfo.Where(a => a.FileId == PartnerInfo[i].FileId).ToList();

            }

I m trying to convert the iso date in Dob ("1984-04-26T00:00:00") to just a date as MM/dd/YYYY but the code above fails, keeps returning the same value. I tried also parse and TryParseExact but they failed too

what am doing wrong here?


ModelState.IsValid Equal to FALSE

$
0
0

Hello,

I need a little help to understand where is a problem. 

I have 4 tables: SparePart, SpareType, MachineType, Pdm

Relationship is next: SparePart has FK from SpareType and from MachineType, Pdm has FK from SpareType

Now,when I want to insert record into Pdm I'm getting some error related to SpareType and Machine Type are required, even if they are shown in viewModel parameters, whyModelState.IsValid is false ?

Here are code from all view models.

SparePartViewModel.cs

public class SparePartViewModel
    {
        public Int64? Id { get; set; }

        public DateTime CreateDate { get; set; }

        [Required]
        [StringLength(100)]
        public string InternalCode { get; set; }

        [StringLength(4096)]
        public string Description { get; set; }

        [StringLength(255)]
        public string NameOnFolder { get; set; }

        public decimal? Enter { get; set; }

        public decimal? Exit { get; set; }

        public decimal? Thickness { get; set; }

        public string Band { get; set; }

        public string Color { get; set; }

        public bool Elastic { get; set; }

        [Required]
        public virtual MachineType MachineType { get; set; }

        [Required]
        public virtual SpareType SpareType { get; set; }
    }

SpareTypeViewModel.cs

    public class SpareTypeViewModel
    {
        public Int64 id { get; set; }

        public DateTime CreateDate { get; set; }

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

MachineTypeViewModel.cs

    public class MachineTypeViewModel
    {
        public Int64 id { get; set; }

        public DateTime CreateDate { get; set; }

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

PdmViewModel.cs

    public class PdmViewModel
    {
        public Int64 Id { get; set; }

        public DateTime CreateDate { get; set; }

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

        [Required]
        public virtual SparePart SparePart { get; set; }
    }

Picture from debug:

Here is the code from controller method where is called post

        [HttpPost]
        public async Task<IActionResult> Post([FromBody] PdmViewModel viewModel)
        {
            string[] entities = { "MachineType", "SpareType" };

            viewModel.SparePart = _repoSparePart.SearchByName(w => w.InternalCode == viewModel.SparePart.InternalCode, entities);

            if (ModelState.IsValid)
            {
                var newPdm = Mapper.Map<Pdm>(viewModel);
                newPdm.CreateDate = DateTime.Now;


                var exist = _repoPdm.SearchByName(w => string.Equals(w.PdmCode, viewModel.PdmCode, StringComparison.CurrentCultureIgnoreCase));
                if (exist != null)
                {
                    TempData["pdm"] = "Pdm Already Exist.";
                }
                else
                {
                    _repoPdm.Insert(newPdm);
                    if (await _repoSparePart.SaveChangesAsync())
                    {
                        TempData["pdm"] = "Pdm Code successfully created.";
                        return Created($"pdm/{newPdm.PdmCode}", Mapper.Map<Pdm>(viewModel));
                    }
                }
            }
            return BadRequest("Failed to save.");
        }

Type Discriminator Configuration ASP.NET Core Web API

$
0
0

For a polymorphic Web API endpoint. Is there a way to configure the type discriminator?

I only found a solution with a JsonConverter. But the problem is the framework behaves then a bit different. E.g. the ValidationAttributes do not get evaluated any more.

Also the code feels like somehow "bypassing" the framework

[JsonConverter(typeof(ScheduleApiConverter))]
public class ScheduleBase
{
public string Type { get; set; }
// [...]
}

public class ScheduleApiConverter : ApiTypeConverter<ScheduleBase>
{
    protected override ScheduleBase Create(Type objectType,
      JObject jObject)
    {
        // TODO: read the raw JSON object through jObject to identify the type
        // e.g. here I'm reading a 'typename' property:

        var typeString = jObject.Value<string>("Type");
        if (ScheduleMongoConverter.WEEKLY_DISCRIMINATOR.Equals(typeString)) {
            return new ScheduleWeekly();
        }
        else if (ScheduleMongoConverter.DAILY_DISCRIMINATOR.Equals(typeString)) {
            return new ScheduleDaily();
        }
        else if (ScheduleMongoConverter.ONCE_DISCRIMINATOR.Equals(typeString)) {
            return new ScheduleOnce();
        }
        else {
            return new ScheduleOnce();
        }

        //now the base class' code will populate the returned object.
    }
}




public abstract class ApiTypeConverter<T> : JsonConverter
{
    // List<string> Errors = new List<string>();

    // this is very important, otherwise serialization breaks!
    public override bool CanWrite {
        get {
            return false;
        }
    }

    // Create an instance of objectType, based properties in the JSON object
    // objectType: type of object expected
    // jObject: contents of JSON object that will be deserialized
    protected abstract T Create(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType,
      object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        T target = Create(objectType, jObject);

        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }

    public override void WriteJson(JsonWriter writer, object value,
      JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Problem trying to use ViewModel to Scaffold Controller

$
0
0

Very new to ASP.net Core 2 MVC but trying to figure things out. 

I have created a ViewModel:

ublic class PeopleStateViewModel
    {
        public People People { get; set; }
        public StatesDictionary States { get; set; }

        public PeopleStateViewModel(People people)
        {
            People = people;
            States = new StatesDictionary();
        }
    }

I Have these two models:

    public class People
    {
        public int ID { get; set; }
        [StringLength(60, MinimumLength = 2)]
        [Required]
        public string FirstName { get; set; }
        [StringLength(60, MinimumLength = 2)]
        [Required]
        public string LastName { get; set; }
    }



        public static SelectList StateSelectList
        {
            get { return new SelectList(StateDictionary, "Value", "Key"); }
        }
        public static readonly IDictionary<string, string>
            StateDictionary = new Dictionary<string, string> {
                {"Choose...",""}
                , { "Alabama", "AL" }
                , { "Alaska", "AK" }
                , { "Arizona", "AZ" }
                , { "Arkansas", "AR" }
                , { "California", "CA" }
                // code continues to add states...
            };
    }

I try to create a controller using MVC  Controller with views, using Entity Framework.

I then get this error:

I want to be able to use data from both classes on a view... 

Any help is appreciated. 

Placeholder in Textbox

$
0
0

Hi there,

I'm using vs 2017 v15.3.3. How to put placeholder in textbox ? I just tried but unseen in "View".

for "Model",  put some code:

        [Display(Name ="No Project"]
        public string No_Project {
            get; set;
        }

Possible to undo "ConfirmEmailAsync" in Microsoft.AspNetCore.Identity?

$
0
0

Is it possible to undo "ConfirmEmailAsync" in Microsoft.AspNetCore.Identity? If you already confirmed a user's email address, can you make the system undo this whenever the user changes the user's email address? That way, the system would know for sure that the new email address the user inputted is reachable.

Also, is it possible for a user to correct the user's email address after registering for a local account or creating a local account after authenticating with an external account, e.g., an OpenID Connect account? This may be necessary if the user inputted an email address that is unreachable and cannot log in until the user confirmed the user's account by clicking the containing the account confirmation link in the email sent to the user's email address, which is unreachable.

That is what I am struggling with right now. Thanks!

Core 2 Framework error “FileNotFoundException” referencing libaries

$
0
0

Hello, this question is posted in StackOverflow without response in two days. For this reason I make a duplicate here.

I have a Core 2 Framework Project. I use Core 2 for performance and need to use Framework 4.6.1 for accesing hardware (printer, serial ports, etc...), I use 4.6.1 to target Windows 10 Aniversary Update.

The main Project is a Core 2.0 MVC Project (Core2FrameWork in the sample Project)

It references a .NET Framework 4.6.1 Library Project (FrameWork461 in the sample Project)

FrameWork461 Project references "System.Printer.dll" (I tested with other System.* libraries with the same error result)

When I call a method with "System.Printer" reference I got a "FileNotFoundException: Could not load file or assembly 'System.Printing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. El sistema no puede encontrar el archivo especificado."

The sample Project is available here

In this simple project, the Home/Index page calls FrameWork461.Working class, and it Works.

The home/NoWorking page calls FrameWork461.NoWorking class, and it do not Works.

As a workarround, I applied the solution exposed in this page: Cannot resolve assembly paths for reference compilation libraries #2981 (it's included in the sample project).

It happends running in IIS, in StandAlone .exe and publishing.

Sorry for my bad English!

Thanks for your help!

Error at publishing self-contained Core 2.0 application

$
0
0

Hi,

after creating a new asp.net core 2.0 application with vs 2017 (version 15.3.3) and trying to publish this application with

"dotnet publish -o dist -r netcoreapp2.0 -c Release"

I get the following error:

"C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\build\netcoreapp2.0\Microsoft.NETCore.App.targets(19,5): error : Project is targeting runtime 'netcoreapp2.0' but did not resolve any runtime-specific packages for the 'Microsoft.NETCore.App' package.  This runtime may not be supported by .NET Core."

What can I do??


ASP.NET Core 2.0 Identity Server changes

$
0
0

So I watch a great plural site video (Understanding ASP.NET Core Security by Roland Guijt) and read and study tutorials by the masters of Identity Server, Brock Allen & Dominick Baier.  I felt confident and ready to proceed with my cutting edge Azure Application. After a few false starts and fundamental changes, I manage to get an almost working Identity Server, Internal API and a Web Application Client.  I tell my boss it's only a matter of time before we can dump that nasty node/angular solution and the third party token service.  Then to my surprise, there is an upgrade to most of the Microsoft Nuget packages to .NET Core 2.0.  I think that it couldn't be better timing and that my solution will be that much better and even more cutting edge and impressive than originally thought.

I should have known better by now, but my application becomes inoperable and I find much of my startup code has now become obsolete or no longer works.  Yet, with an optimistic attitude I seek out those reliable sources of code changes and to my ultimate dismay, these are vague and don't seem to fit my scenario, which I thought was very standard practice. 

What's more, I cannot seem to find any up-to-date tutorials or instructions on how to fix my application and properly register my client web application and set my API resource correctly in the Identity server as well as in its own startup.

Anyway, if you decided not to waste your time with the above story of my troubles in ASP.NET core land, can someone just provide some resources or direction where I could turn to help guide me through these changes.  I know there is a page out there (https://github.com/aspnet/Announcements/issues/262) which is supposed to be crystal clear and should be more than adequate for someone with my intelligence and experience to follow along and clear up my issues.  However, I find it very vague and severely lacking in clear instruction on how to get my solution working again, even after reading and rereading its contents.

So I will be forever in your debt and your best friend if you can provide any good reference which might explain or better yet demonstrate how to update my code to operate within the confines of the changes that ASP.NET Core 2.0 has imposed on us loyal Microsoft Azure Web Solution designers and our standard Web, API, Identity Server solutions.

Thank you so very much in advance.

Acessing ViewData Using Variable Name

$
0
0

I'm still new to .NET, and am struggling with something I'm hoping someone here can help me out with...

I've got a number of ViewData objects that I'm sending from my Controller to my View. What I want to be able to do is to dynamically access them in JavaScript. I was thinking about having something like this in my Razor View page:

<script type="text/javascript">
   function GetMyViewData(dataWanted) {
      var data = '@ViewData["' + dataWanted + '"]';
      return data
   }</script>

So I could call it from an external JS file like this:

var usefulInfo = GetMyViewData('DesiredDataNugget');
var moreStuff = GetMyViewData('AnotherBitOfData');
var otherStuff = GetMyViewData('OtherInfo');

But of course, that doesn't work. What am I missing? How can I use a variable in place of the name for the specific ViewData object?

Right now I have a bunch of hard-coded statements to get me by, but it seems like there should be a more dynamic way to do what I want...

Thanks!

How can you set the form action to a variable in asp.net core mvc view

$
0
0

I have an ASP.Net Core MVC web application. I have a view that calls a controller in a project on a different server. In this view I have a form with a post that calls the api.
<form action="http://myapi/values/postdata" method="POST" enctype="mulitpart/form-data">

<div class="content wysiwyg-content">I want to set a global variable in something like a .config file to set the api location and use it for the form action.
<form action=myapilocation method="POST" enctype="mulitpart/form-data">
The idea is to be able to update the config file with the location if it changes and not have to change code in the view, or views when the same api is called from different views. ASP.Net web applications have a web.config file, but I ASP.Net core mvc apps do not seem to have them. How would I set a variable like this and then call it on my view/form? The location of the url will change, and once deployed I want to just change a config setting. Thanks.</div>

Asp.Net Core 2.0 Mvc templates error

$
0
0

Have an Asp.net core 1.1 Mvc app that I converted to 2.0 that includes a custom Templates/ folder.  When I attempt to add a controller w EF actions, I get the following error:

There was an error running the selected code generator:

mvcControllerWithContext.cshtml: Template processing failed: The type or namespace naem 'List<>' could not be found....


I assume there are updated templates for core 2.0 but don't know where to find them??

Dynamic Call to Database

$
0
0

I'm still digging in and learning .NET, and was wondering if someone can point me in the right direction on something?

Right now, in my Controller, I've got a number of hard-coded calls to some tables within my app's database. Something sort of like this:

if (suppliedTableName == "TableStuff")
{
   var model = await _appDbContext.TableStuff.ToListAsync();
   return View(view, model);
}
if (suppliedTableName== "MyRandomStuff")
{
   var model = await _appDbContext.MyRandomStuff.ToListAsync();
   return View(view, model);
}
if (suppliedTableName== "MySettings")
{
   var model = await _appDbContext.MySettings.ToListAsync();
   return View(view, model);
}

I'm wondering if there's a way to make it more dynamic? Something more like this:

var model = await _appDbContext.VariableSuppliedToControllerWhenCalled.ToListAsync();
return View(view, model);

Can someone give me a nudge in the right direction?

Thanks! And I have to take a quick minute and let all of you know that I appreciate everyone that has helped me in the past - not sure where I'd be without all of you!

I gotted lots of time one big error.. but until now i did not solve about that error. System.MissingMethodException occurred

$
0
0

System.MissingMethodException occurred
HResult=0x80131513
Message=Method not found: 'System.Collections.Generic.Dictionary`2<System.String,System.Object> Microsoft.Extensions.Configuration.IConfigurationBuilder.get_Properties()'.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>

Problem with ondisconnected method of signalr

$
0
0

HI All

ondisconnected method automaticaly calls without closing the window of browser right after onconnected how to fix it?


ASP.NET Core Razor page - refresh calculated field?

$
0
0

I come from the old ASP.NET WebForms and I have a question on the Razor Pages. Since ASP.NET Web Core Razor Pages are rendered on the server how would you do a simple calculated field that is automatically updated when user changes values on the form on Razor Pages?

For Example a simple calculator like Value1 * Value2 = Total and the user changes the Value1 or Value2 and Total is instantly recalculated on the screen.  In the old WebForms I used to use a trick but how would you do this in Razor Pages?

Thank you

Windows vs Linux hosting using ASP.NET Core 2.0

$
0
0

Hello all!

Who can recommend fastest platform - windows or linux use with ASP.NET Core 2.0 more productive (requests per second)?

Thank you.

ControlValidator on ASP.NET Core?

$
0
0

Hello,

I'm looking for a replacement for ControlValidator on ASP.NET Core since I'm trying to validate the following:

I have a modal window that is used to register or edit new objects (Machines).

These Machines have a property calledNumDevices (Number of Devices).

For the purpose of this project I have to validate that the input wrote for this property is not less than the current value shown in the input field.

Also, it would be necessary to shown a error message claiming that the entered number can't be less than X, being X the current number.

<div class="form-group"><label asp-for="NumDevices" class="col-md-2 control-label"></label><div class="col-md-10"><input id="NumDevices" asp-for="NumDevices" class="form-control" /><span asp-validation-for="NumDevices"  class="text-danger"></span></div></div>



I'm looking to construct this client-side but I'm open to any suggestion. What can I use instead of ControlValidator?

Kind regards,

asp.net core mvc - user specific fields edit with many dropdownlists and selected values

$
0
0

My Models:

public class Profile
    {
        public Profile() { FieldStatuss = new List<FieldStatus>(); }

        public int ProfileId { get; set; }
        public string OwnerID { get; set; }

        public string Name { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Email { get; set; }
        public string Facebook { get; set; }
        public string Twitter { get; set; }
        public string Department { get; set; }
        public string Office { get; set; }

        public virtual ICollection< FieldStatus> FieldStatuss { get; set; }

    }


    public class FieldStatus
    {
        public FieldStatus(){ Profile = new Profile(); }
        [Key]
        public int FieldStatusID { get; set; }

        public string ColumnName { get; set; }// for example :City
        public string EnumFieldStatusV { get; set; } //For example: EnumFieldStatus.OnlyMe

        public int ProfileId { get; set; }
        [ForeignKey("ProfileId")]
        public virtual Profile Profile { get; set; }
    }
 // EnumFieldStatus as a class if you need
    public enum EnumFieldStatus
    {
        [Display(Name = "Only Me.")]
        OnlyMe,
        [Display(Name = "Visible To Everyone.")]
        VisibleToEveryone,
        [Display(Name = "Visible To Office.")]
        VisibleToOffice,
        [Display(Name = "Visible To Department.")]
        VisibleToDepartment,
        [Display(Name = "Not Visible.")]
        NotVisible
    }

Controller

            Profile profile = new Profile();
            var props = profile.GetType().GetProperties();

            foreach (var item in profileFieldStatus)
            {
                var statusField = item.ColumnName;
                EnumFieldStatus statusName = item.EnumFieldStatusV;

                if (statusName==EnumFieldStatus.NotVisible )
                {
                    props.Where(a => a.Name == "statusField").FirstOrDefault().SetValue(profile, null);
                    //foreach (var propinfo in props)
                    //{
                    //    if (statusField == propinfo.Name)
                    //    {
                    //        propinfo.SetValue(profile, null, null);
                    //    }
                    //}
                }

Fo the Views cannot figure it out how to get them in edit view with selected values foreach textbox and save them with post. For example when user creates a profile for the first time he selects facebook, twitter - VisibleToAll and email - VisibleToOffice. Later if he decides to change only his facebook to NotVisible, other dropdowns for the textboxes will have their selected values from db in the view (so dropdowns for twitter and email will keep VisibleToAll and VisibleToOffice values) and will update only facebook field's visibility , or easier to delete all the values and resave them again as they will have selected values from the db even only one dropdown changed.

Email Already Taken Validation ASP.NET Core 2.0 Razor Pages

$
0
0

With the Microsoft solution out of the box it has the ability to tell me when I make a new user in my sight that if the username is the same as someone else's then it will say: "User name 'username' is already taken."

I would like to know the way to keep this validation and add one where it will same the same thing about User email. I want everyone's' email to be unique in the database. 

Viewing all 9386 articles
Browse latest View live


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