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

Deploy .net core 3.1 application

$
0
0

Hi All,

          How we publish .net core 3.1 application web hosting plan  with Godday, GrabWeb Hosting providers

I want to deploy api application and UI application. I already had domain and space. 


Oauth Token

$
0
0

Hi All,

We have a Asp.Net core webapi , which internally calls a 2nd api to get data from other systems.

To call the 2nd api we have to call the microsoft oauth url provided by the 2nd api team, below  are fields we are using to fetch the token

Currently for every 2nd api request we make from our api , we are  calling the oauth url to generate new token, but it look like it has expiry of 5 hours.

In that case can we store it in a memory IMemoryCache _cache and check the validadity time as well,  so once we generated the toke we  can reuse it until it expires

Please let us know your thoughts on this, we are using this for the first time.

private string ClientID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private string ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private string AuthUrl= "https://login.microsoftonline.com/{companyName}.onmicrosoft.com";
private string TenantId = "XXXXXXXXX.onmicrosoft.com";

Dynamic shorthand element tag helper

$
0
0

I'm working with .net Core 2.2 and trying to set the element tag at run time using a property on the view model class so that a tag helper can modify the html and it looks like the tag helper isn't triggered.

For testing purposes I have the following class in my view model:

public static IQueryable<DynamicField> IronMan => new List<DynamicField>
{
new DynamicField { DisplayName = "Key", TypeCode = "strong", SortOrder = 1, Value = "11132", },
new DynamicField { DisplayName = "FirstName", TypeCode = "string10", SortOrder = 2, Value = "Ironman", Tags = new List<string> {"Tag1", "Tag2"}},
new DynamicField { DisplayName = "Age", TypeCode = "number", SortOrder = 3, Value = "35", Tags = new List<string> {"Tag1", "Tag3"}},
new DynamicField { DisplayName = "MarvelVerse", TypeCode = "yesno", SortOrder = 4, Value = "1", Tags = new List<string> {"TagYesNo" }}
}.AsQueryable<DynamicField>();

I have the following tag helper setup:

using Microsoft.AspNetCore.Razor.TagHelpers;

namespace DynamicUi.Infrastructure.TagHelpers.View
{

    public class Strong : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.SetAttribute("class", "col-sm ");
            output.PreContent.SetHtmlContent("<b>");
            output.PostContent.SetHtmlContent("</b>");
        }
    }
}

In my page, if I use the tag helper directly, it is applied correctly:

<div><p>tag hard-coded</p><div class="container">
        @foreach (var dynamicField in FakeAPIRepository.IronMan)
        {<div class="row"><strong>@dynamicField.DisplayName</strong><div class="col-sm">@dynamicField.Value</div><div class="col-sm">@dynamicField.TypeCode</div><div class="col-sm">@dynamicField.SortOrder</div></div>
            }</div></div>

Result:

<div><p>tag hard-coded</p><div class="container"><div class="row"><div class="col-sm "><b>Key</b></div><div class="col-sm">11132</div><div class="col-sm">strong</div><div class="col-sm">1</div></div><div class="row"><div class="col-sm "><b>FirstName</b></div><div class="col-sm">Ironman</div><div class="col-sm">string10</div><div class="col-sm">2</div></div><div class="row"><div class="col-sm "><b>Age</b></div><div class="col-sm">35</div><div class="col-sm">number</div><div class="col-sm">3</div></div><div class="row"><div class="col-sm "><b>MarvelVerse</b></div><div class="col-sm">1</div><div class="col-sm">yesno</div><div class="col-sm">4</div></div></div></div>

However, what I would like to do is set the element type at run-time based on the data.  What I've tried is:

<div><p>tag dynamically used</p><div class="container">
        @foreach (var dynamicField in FakeAPIRepository.IronMan)
        {<div class="row"><@dynamicField.TypeCode>@dynamicField.DisplayName</@dynamicField.TypeCode><div class="col-sm">@dynamicField.Value</div><div class="col-sm">@dynamicField.TypeCode</div><div class="col-sm">@dynamicField.SortOrder</div></div>
        }</div></div>

But the strong tag helper doesn't transform the element into the div like it does when I use the tag helper explicitly and I end up with this:

<div><p>tag dynamically used</p><div class="container"><div class="row"><strong>Key</@dynamicField.TypeCode><div class="col-sm">11132</div><div class="col-sm">strong</div><div class="col-sm">1</div></div><div class="row"><string10>FirstName</@dynamicField.TypeCode><div class="col-sm">Ironman</div><div class="col-sm">string10</div><div class="col-sm">2</div></div><div class="row"><number>Age</@dynamicField.TypeCode><div class="col-sm">35</div><div class="col-sm">number</div><div class="col-sm">3</div></div><div class="row"><yesno>MarvelVerse</@dynamicField.TypeCode><div class="col-sm">1</div><div class="col-sm">yesno</div><div class="col-sm">4</div></div></div></div>

I've also tried it with a self-closing tag since the closing tag wasn't creating properly:

<div><p>tag dynamically used</p><div class="container">
        @foreach (var dynamicField in FakeAPIRepository.IronMan)
        {<div class="row"><@dynamicField.TypeCode text=@dynamicField.DisplayName /><div class="col-sm">@dynamicField.Value</div><div class="col-sm">@dynamicField.TypeCode</div><div class="col-sm">@dynamicField.SortOrder</div></div>
        }</div></div>

But that didn't work either.

Is there a way to do this without adding a huge case statement that has each TypeCode we will have in a partial/vc to generate the html?

Thanks

SleepyBadger

How to use System.Web in .Net Core

$
0
0

How to use System.Web in .Net Core

How to specify the address of a json file in a script in the view

$
0
0

I'm implementing asp.net core 3.1 project and have a script like the following and I now in the URL, I'm reading a json file from a an address but I downloaded the json file and put it into my project (wwwroot_>JS files) and I want the URL to read from that file. But I don't know how to specify the address of my json file which is lying in src="~/js/Persian.json" in my project. 

<script language="JavaScript" type="text/javascript" src="~/js/datatables.min.js"></script><script>

    jQuery(document).ready(function ($) {$("#myDummyTable").DataTable({

            //"searching": false,"language": {"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Persian.json"
            }
        });
    });</script>

How to delete cookie after closing the tab while other tabs are open

$
0
0

I'm implementing an asp.net core 3.1 project. My problem is I want when the user close the project tab meanwhile other tabs are open, the cookie goes to get deleted. Right now after running the project, while other tabs are open, after I close the tab that shows my program and rerun my project again, I don't need to login and the cookie isn't deleted. But I want in that situation to login as well. I appreciate if anyone tells me the expression I need to use to solve the issue. For implementing the project, I authenticate the user via ldap with the below expressions in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{

services.AddControllersWithViews();

services.AddDbContext<CSDContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CSDContext")));


services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
// Cookie settings

//set the cookie name here
options.Cookie.Name = "UserLoginCookie"; // Name of cookie
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);

options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/UserAccessDenied";
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
});

services.AddSession();
services.AddSingleton<MySharedDataViewComponent>();
services.AddHttpContextAccessor();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/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.UseSession();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

});
}

Now I used the below expression for deleting cookie after closing the browser.

var authProperties = new AuthenticationProperties
{

IsPersistent = false

}; 

Current User in ASP.NET Core is always null

$
0
0

Hello All,

I am trying to get the current user name who is logged in using windows authentication in .net controller and I am always getting null value in _userName on my localhost.

Below is my code:

<div>
public class AuthorizationController : ControllerBase
    {


        private readonly IHttpContextAccessor _httpContextAccessor;

        public AuthorizationController(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            string _userName = httpContextAccessor.HttpContext.User.Identity.Name;
        }
}
    
Below is my appsettings.json file:</div> <div></div> <div>
{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
    }
  },"AllowedHosts": "*","iisSettings": {"windowsAuthentication": true,"anonymousAuthentication": false,"iisExpress": {"applicationUrl": "http://localhost:44314/"
    }
  }
}
any help will be highly appreciated.</div>

Kendo Ui Cannot get the value field from multi column combo box

$
0
0

I am using the kendo multi column dropdown but I appear to be unable to get the value from the DatValueField I am using the value to then get the id of the person selected to be able to store that in another table.

https://demos.telerik.com/aspnet-core/multicolumncombobox/index

<form asp-action="LinkToCase" method="post" asp-controller="MISObjects"><div class="row"><div class="col-md-12"><div class="card card-success"><div class="card-header" style="background-color:#1e3f5a;color:white"><h3 class="card-title">Search and Tag</h3></div><div class="card-body"><div class="col-md-12"><div class="input-group"><select id="searchOptions" name="searchOptions" style="background-color: #1e3f5a; color: white; width: 140px; height: 45px"><option selected value="1">Poi</option><option selected value="1">Vessel</option></select>


                    @(Html.Kendo().MultiColumnComboBox()
                        .Name("tagItem")
                        .DataTextField("name")
                        .DataValueField("SearchId")
                        .Filter("contains")
                        .FilterFields(new string[] { "name", "ContactTitle", "CompanyName", "Country" })
                        .Columns(columns =>
                        {
                            columns.Add().Field("name").Title("Contact Name").Width("200px");
                            columns.Add().Field("dob").Title("Date Of Brith").Width("200px");

                        })
                        .FooterTemplate("Total #: instance.dataSource.total() # items found")
                        .HtmlAttributes(new { style = "width:80%;" })
                        .Height(400)
                        .DataSource(source => source
                            .Custom()
                            .Transport(transport => transport
                                .Read(read =>
                                {
                                    read.Action("SearchQuery", "MISObjects")
                                        .Data("onAdditionalData");
                                }))
                        )
                        )<button type="submit" class="btn-primary" value="Link To Case" style=" background-color:#1e3f5a;color:white">Link To Case</button></div></div></div></form>

The kendo combox calls this function.

[HttpPost]
public IActionResult LinkToCase(int SearchId,string updateInfo, int tagItem, string sesearchOptionsr, IFormCollection formItems) {
      Int32.TryParse(TempData.Peek("CaseId").ToString(), out int resultCaseId);
      var test = formItems;
        POI newPoi = new POI();
        newPoi =  _context.Pois.SingleOrDefault(w => w.Id == SearchId);

        newPoi.MISObjectId = resultCaseId;

        _context.Pois.Add(newPoi);

        _toast.AddSuccessToastMessage(
            $"You have linked {newPoi.FirstName} {newPoi.LastName} to case {resultCaseId:d8}");

        return RedirectToAction("Edit", new { id = resultCaseId });

    }
    private IEnumerable<SearchViewModel> GetSearchRecords() {
        return _context.Pois.Where(w => w.isActive == true && w.isDeleted == false).Select(person =>
             new SearchViewModel {
                 SearchId = person.Id,
                 Name = person.FirstName + "  " + person.LastName,
                 DOB = person.DOB
             }).ToList();

  }
}

But even when I inspect SearchId it is blank even if i set it to type int I put in a support ticket as I am on trail but saw their was a kendo tag here so thought might try here as well


How to set default value in select html

$
0
0

I have form

<form asp-page-handler="numberOfRows" method="POST" asp-area="" asp-page="/PagesWithTables/ShowProduktyTable" >
<button type="submit" class="btn btn-default">zmień</button>
<select asp-for="InputShowOnPage.ShowOnPage"
asp-items="Model.Items"></select>
</form>

also 

public string ShowOnPage { get; set; }

public IEnumerable<SelectListItem> Items { get; } = new List<SelectListItem>
{
new SelectListItem{Value= "10", Text="10"},
new SelectListItem{Value= "25", Text= "25"},
new SelectListItem{Value= "50", Text="50"},
new SelectListItem{Value= "100", Text="100"},
};

how can I create default value in select to 50?

Sharing Data Between ActionResult Using TempData

$
0
0

I am trying to share data between these two controllers:

Doing a foreach loop in the Index View works fine, but when I try to do a foreach loop in View "Two" I get the following error: "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

		public IActionResult Index()
		{
			List<string> lstStudent = new List<string>();
			lstStudent.Add("Debasis");
			lstStudent.Add("Samrat");
			lstStudent.Add("Rahul");
			TempData["StudentData"] = lstStudent;
			return View(); 
		}

		public IActionResult Two()
		{
			List<string> modelData = TempData["StudentData"] as List<string>;
			TempData.Keep();
			return View(modelData);
		}



This is the code for View Two:

@{
    ViewData["Title"] = "View Two";
    TempData.Keep();

}

<ul>
    @foreach (var data in Model)
    {<li>@data</li>
    }</ul>

Any assistance would be kindly appreciated.

Building an action link with model and selected option

$
0
0

In my TradingPartner model I have a property IsSelected.  Only one trading partner will be selected.  Then I populate the select options with all the trading partners that are not selected.  What I'm trying to do is send the targetId (from the model.IsSelected==true) and the sourceId (from the option list) back to the controller.  How would I go about doing this?

@model IEnumerable<ETL_Staging_UI.Models.TradingPartner>

@{
    ViewData["Title"] = "Copy Rules";
    Layout = "~/Views/Shared/_Layout.cshtml";
}<h4>
    Target trading partner
    @foreach (var item in Model)
{
    @if(item.IsSelected)
    {<label class="control-label">@item.Designation</label>
    }
}</h4><hr /><div><form><div class="form-group"><label class="control-label">Copy Rules From</label><select class="form-control" style="width:auto">
                    @foreach (var item in Model)
                {
                    @if(!item.IsSelected)
                    {<option value="@item.Id">@item.Designation</option>
                    }
                }</select>
                @Html.ActionLink("Copy", "CopyRules", new { sourceId = 3, targetId = 4 }, new {@class = "btn  btn-default"})</div></form></div><div><a asp-action="Index">Back to List</a></div>

https://ibb.co/9NfSkqd

Adding additional related Entities to ApplicationUser

$
0
0

I am working on streamlining the number of calls in my application and I want to add related entities to the ApplicationUser on login.

Right now the best I could come up with was to add properties I need to the Claims.  but having to call User.FindFirst("Value").Value gets to be a pain.

Example:

I have a related entity called CurrentAccount, and then also UserAccountAssociations.

These related entities are in my DBContext, but they aren't in my IdentityDbContext.  

I want to be able to access these properties anytime by using User.CurrentAccount.Id or User.CurrentAccount.Name, and so on, in a controller, razor page code behind or the .cshtml itself, anywhere in the application.

Is this possible?

What's going on under hood when instantiating an Interface?

$
0
0

I'm trying hard to understand interfaces beyond the basics. I have a tutorial that works great, but I don't understand something. First, a code snippet from the class:

    public class Repository : IRepository
    {
          private readonly ApplicationDbContext x;
    
          public Repository(ApplicationDbContext iapp)
          {
                x = iapp;
          }
    }

    Next is the code snippet for the Controller:

    public class MyController : ControllerBase
    {
        private readonly IRepository x2;
    
        public MyController(IRepository irep)
        {
            x2 = irep;
        }
    }

    Effectively, I now have two readonly variables, x, and x2.

    What's the point of creating the x2 variable from IRepository, since the class already has a variable "x" from the DbContext? In other words,

    it appears to me that data is being created twice, once by the class, and then by the controller. I'm sure I am missing something.

    What's going on under the hood in memory?

    I'd be grateful for any kind of explanation at all. You already know way more than I do!!

    Profile give error although I install auto mapper ?

    $
    0
    0

    I work on asp.net core 2.2 when i inherit from Profile I get error

    'Profile' is a namespace but is used like a type [D:\ReactApp\Application\Application.csproj](CS0118)

    so what I do to solve issue

    Having problem with updating IdentityUser - The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked

    $
    0
    0

    Hello.

    I am using ASP.NET Core 3.1.7 with Identity 3.1.7 and in my current project I didn't use any DTO for creating / updating  User.

    and I use the main entity User that derived from IdentityUser.. these codes are for updating the user but i have problem with ChangeTracker.

    this is my User Entity.

     public class User : IdentityUser<int>
        {
            public int DepartmentId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string NationalCode { get; set; }
            public string Address { get; set; }
            public string IPAddress { get; set; }
            public CorporateTitle CorporateTitle { get; set; }
            public string PhotoPath { get; set; }
    
            [NotMapped]
            public IFormFile Photo { get; set; }
    
            [NotMapped]
            public string[] Roles { get; set; }
    
    
            public DateTimeOffset DateCreated { get; set; }
            public DateTimeOffset DateModified { get; set; }
    
            [ForeignKey(nameof(DepartmentId))]
            public Department Department { get; set; }
    
            public ICollection<UserRole> UserRoles { get; set; }
    
    
        }

    this block of code is for getting the user and then showing it in view. and its ok and working properly.

     public async Task<IActionResult> EditUser(string id)
            {
                if (!string.IsNullOrEmpty(id))
                {
                    var usertoEdit =  await _userRepository.FindByIdAsync(id);
                    var userRoles = await _userRepository.GetAllUserRolesAsync(usertoEdit);
                    //
                    usertoEdit.Roles = userRoles.ToArray();
                    //
                    if (usertoEdit == null)
                    {
                        ViewBag.ErrorMessage = $"some error..";
                        return View("NotFound");
                    }
    
                    SelectLists();
                    return View(usertoEdit);
                }
                else
                {
                    ViewBag.ErrorMessage = $"some error.";
                    return View("NotFound");
                }
            }

      [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> EditUser(User user)
            {
                if (ModelState.IsValid)
                {
                    var editUserResult = await _userRepository.EditUserAsync(user); // here i have problem and after that showing error.
    
                    if (editUserResult.Succeeded)
                    {
                        await _userRepository.RemoveAllUserRolesAsync(user);
                        if (user.Roles != null)
                        {
                            await _userRepository.AddRolesToUserAsync(user, user.Roles);
                        }
    
                        TempData["UserEditedSuccessfully"] = $"some error.";
                        return RedirectToAction(nameof(Index));
                    }
    
                    foreach (var error in editUserResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
    
                    SelectLists();
                    return View(user);
    
                }
                else
                {
                    SelectLists();
                    return View(user);
                }
            }

    please help me to solve this problem without use any DTO or ViewModel thanks.


    Ingress works with sample python apps, but not ASP.NET MVC Core 3 Hello World

    $
    0
    0

    I'm following these instructions https://docs.microsoft.com/en-us/azure/aks/ingress-basic using Docker for Desktop/Kubernetes on Windows 10.

    This tutorial works great for the sample python webapps described in that tutorial. However, when I use Visual Studio 19 to create "Hello World" style web app with ASP.NET/MVC Core 3 ingress won't display it after it is deployed.

    I have copied the file aks-helloworld-one.yaml to kuberneteshelloaspnet.yaml and modified it accordingly for my new WebApp.

    This newly created WebApp is just the code generated by the the Visual Studio code generator that displays "Hello Kubernetes" and the current date & time.  I add this line of code to program.cs:

    webBuilder.ConfigureKestrel(serverOptions => { serverOptions.Listen(System.Net.IPAddress.Loopback, 80); });

    I compile this in release mode, test it (it works great) and publish to git hub.

    I add an entry to hello-world-ingress.yaml for my new WebApp.

    - backend:
    serviceName: kuberneteshelloaspnet
    servicePort: 80

    I use the following commands:

    kubectl create namespace ingress-basic # microsoft ingress example
    helm repo add stable https://kubernetes-charts.storage.googleapis.com/
    helm install nginx-ingress stable/nginx-ingress \
    --namespace ingress-basic \
    --set controller.replicaCount=2 \
    --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \
    --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux
    kubectl get service -l app=nginx-ingress --namespace ingress-basic
    kubectl apply -f ${WINOOP_EG}/kubernetes/ingress-basic/aks-helloworld-one.yaml --namespace ingress-basic
    kubectl apply -f ${WINOOP_EG}/kubernetes/ingress-basic/aks-helloworld-two.yaml --namespace ingress-basic
    kubectl apply -f ${WINOOP_EG}/kubernetes/ingress-basic/kuberneteshelloaspnet.yaml --namespace ingress-basic
    kubectl apply -f ${WINOOP_EG}/kubernetes/ingress-basic/hello-world-ingress.yaml

    I point my browser to localhost:helloworld-one and localhost:helloworld-two and they work! Great! However, when I point my browser to localhost:kuberneteshelloaspnet I get

    503 Service Temporarily Unavailable


    nginx/1.19.1

    What am I doing wrong? Why won't my application work with Ingress?

    Thanks

    Siegfried

    Adding and Editing Lists using Partial View

    $
    0
    0

    So I've this scenario, An objectA contains a list of ObjectB. And each item of the ObjectBList has an object (file) that is optional.

    I've the following Model for ObjectA and View Model for the create and edit.

    public class ObjectA
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public IList<ObjectB> ObjectBList { get; set; }
        }
    
    public class CreateEditObjectAViewModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public IList<ObjectBViewModel> ObjectBList { get; set; }
        }

    The View Model of the list is the following.

    public class ObjectB
        {
            public int Id { get; set; }
            public string Text { get; set; }
            public virtual Image Image { get; set; } 
        }
    
    public class ObjectBViewModel
        {
            public int Id { get; set; }
            public string Text { get; set; }
            public IFormFile ImageFile { get; set; } //for an image object
        }

    Create view: 

    @model TestApplication.Models.ViewModels.CreateEditObjectAViewModel<form asp-action="Create" method="post" asp-controller="Test" enctype="multipart/form-data"><div class="form-group row"><div class="col-2"><label asp-for="Name" class="col-form-label"></label></div><div class="col-5"><input asp-for="Name" class="form-control" /></div><span asp-validation-for="Name" class="text-danger"></span></div><div id="editorRows">
            @foreach (var item in Model.ObjectBList)
            {<partial name="_ObjectBEditor" model="item" /> 
            }</div><a id="addItem" asp-action="BlankRow" asp-controller="Test">Add Row...</a> <br /><input type="submit" value="Finished" /></form>
    
    @section scripts {
        <script>$("#addItem").click(function () {$.ajax({
                    url: this.href,
                    cache: false,
                    success: function (html) { $("#editorRows").append(html); }
                });
                return false;
            });</script>
    }

    The Partial View:

    @model TestApplication.Models.ViewModels.ObjectBViewModel
    @using HtmlHelpers.BeginCollectionItemCore;<div class="editorRow">
        @using (Html.BeginCollectionItem("list"))
        {<span>Text: </span> @Html.EditorFor(m => m.Text);<span> Image: </span> @Html.TextBoxFor(m => m.ImageFile, new { @type = "file" });
        }<a href="#" class="deleteRow">delete</a></div>
    
    @section Scripts {
        <script>$(document).ready(function () {$("a.deleteRow").on("click", function () {$(this).parents("div.editorRow:first").remove();
                    return false;
                });
            });</script>
    }

    Finally the controller

            public IActionResult BlankRow()
            {
                return PartialView("_ObjectBEditor", new ObjectBViewModel());
            }
    
            [HttpPost]
            public async Task<IActionResult> AddTwo(CreateEditObjectAViewModel model)
            {
                if (ModelState.IsValid)
                {
                    ObjectA modelToSave = new ObjectA()
                    {
                        Name= model.Name,
                        //ObjectBList= ??,
                    };
    
                    _db.Story.Add(modelToSave);
                    await _db.SaveChangesAsync();
                    return RedirectToAction("Index");
                }
                return View(model); 
            }

    What should happen is, in each row there should be a text and an image file (optional), and each image must be linked correctly to its text. Am I doing it this logic?

    For now when I'm posting an object for some reason the List is always empty, I've tried this previously using the models directly and everything worked fine.  And I also don't know how to deal with the ObjectBList because its a type of view model and can't be saved in the modelToSave directly. 

    Thanks.

    Implementing a Pool of object

    $
    0
    0

    My API calls third party api. Third party api has the concept of sessions. There is an api method to create session, session is denoted by session id. There is a limit to the number of session that can be created. Session has maximum life time of 15 minutes. If session has idle timeout of 3 minutes. If session not used for 3 minutes, the session become invalid. 15 minutes after the creation of session, it becomes invalid.

    I want to reuse the session id, just like db connection pooling. Also one session to be used by only one API call, If there are concurrent api calls, each call should use different session id.

    I read object pooling implementation pattern using queue. Also , QueueStore, StackStore. How to implement the idle timeout and global timeout. how can the concurrency be handled ?

    I have written the logic so far.

    1) A singleton factory class added to startup.cs

    2) inside the factory, create a queue, if count is zero, call the api to create session id and return

    3) once the purpose is over, add the session id back to queue, so when the next call comes in deque and return the session id.

    HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process

    $
    0
    0

    Hello.

    I am developing an app with .netcore 3.1 and entityframeworkcore with sql server databases.

    I upload the app to 3 subdomains (on the same server), each one with a different database. When I run the application from one of the subdomains everything works fine, but when I try to run the application simultaneously from another subdomain I get the following error:

    HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process.

    If I close the page that is active and wait a while, I can run the app from the other domain.

    Who knows how to fix this problem?

    If I run it from visual studio I have no problem.

    Thanks in advance.

    Greetings.

    Get count of total records in razor pages and using the List Function

    $
    0
    0

    Hi guys

    I started playing around with razor pages, and wonder how to get the total count of a record and also how to use List generic functions. 

    In my old MVC applications I simply added List to the model directive e.g.  Kindly note, I have edited the code and removed the lengthy unnecessary bits.

    My aim is to make dynamic content and display them in a div row of 3 horizontally and then as many vertically

    Hence I added the list function to the model directive

    @model IList<Xadosh.Models.Department.Departments>

    Here is my code, basic code

    --- ~Code Behind
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.EntityFrameworkCore;
    using VirtualMarkets.Models.Department;
    using VirtualMarkets.Web.Classes;
    
    namespace VirtualMarkets.Web.Pages.test
    {
        public class IndexModel : PageModel
        {
            private readonly VirtualMarkets.Web.Classes.MyDbContext _context;
    
            public IndexModel(VirtualMarkets.Web.Classes.MyDbContext context)
            {
                _context = context;
            }
    
            public IList<Tbl_Departments> Tbl_Departments { get;set; }
    
            public async Task OnGetAsync()
            {
                Tbl_Departments = await _context.Tbl_Departments.ToListAsync();
            }
        }
    }
    
    
    
    
    
    Razor page
    
    @page
    @model IList<VirtualMarkets.Web.Pages.Cart.IndexModel>
    
    @{
        ViewData["Title"] = "Index";
    }<h1>Index</h1><div class="text-center"><h5>General Department - (@(Model.Count()))</h5></div>
    
    
    @for (var i = 0; i < Model.Count(); i++)
    {<div class="col-md-4 text-center   classify"><a href="@Model[i].Description_Short">
                                    @Model[i].Department_Name<br /><div><img src="~/images/Department_Categories/@(Model[i].DepartmentID).png" alt="@(Model[i].Department_Name)" class="img-fluid" /><br />
    
                                      
                                        @Model[i].Description_Long
                                        <br /><div class="small">@Model[i].Description_Short</div></div></a><br /><hr /></div>
    
    
    
        }

     and my model

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace VirtualMarkets.Models.Department
    {
        public class Tbl_Departments
        {
          
                [Key]
                public int DepartmentID { get; set; }
            
                [Required]
                [StringLength(150, ErrorMessage = "First name cannot be longer than 150 characters.")]
                public string Department_Name { get; set; }
                [Required]
                public string Description_Long { get; set; }
                [Required]
                [StringLength(150, ErrorMessage = "First name cannot be longer than 150 characters.")]
                public string Description_Short { get; set; }
                public bool IsEnabled { get; set; }
    
    
    
    
              
          
        }
    }
    

    I get this error

    An unhandled exception occurred while processing the request.
    
    InvalidOperationException: A suitable constructor for type 'System.Collections.Generic.IList`1[VirtualMarkets.Web.Pages.Cart.IndexModel]' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
    
    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out Nullable<int>[] parameterMap)
    Stack 
     Query 
     Cookies 
     Headers 
     Routing 
    
    InvalidOperationException: A suitable constructor for type 'System.Collections.Generic.IList`1[VirtualMarkets.Web.Pages.Cart.IndexModel]' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
    
    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out Nullable<int>[] parameterMap)
    
    
    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateFactory(Type instanceType, Type[] argumentTypes)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelActivatorProvider.CreateActivator(CompiledPageActionDescriptor actionDescriptor)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelFactoryProvider.CreateModelFactory(CompiledPageActionDescriptor descriptor)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvokerProvider.CreateCacheEntry(ActionInvokerProviderContext context, FilterItem[] cachedFilters)
    
    
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
    
    
    Microsoft.AspNetCore.Mvc.Infrastructure.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
    
    
    Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory+<>c__DisplayClass7_0.<CreateRequestDelegate>b__0(HttpContext context)
    
    
    Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
    
    
    Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
    
    
    Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    
    
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
    
    
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    
    
    Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
    
    
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    
    
    
    
    
    Show raw exception details 
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
      
      
      
      
      
      
      
    
    
    
    
    
    
    
    
    
    
      
      
      
    
    
    
    
    
    
    
    
    
      
     

    Viewing all 9386 articles
    Browse latest View live


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