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

How to compile using 2.2.6?

$
0
0

Hi,

I have my ASP.NET Web API project and in the project properties I selected target Framework as .NET Core 2.2 (because that's the latest listed in my Visual Studio 2019)

but I am having a problem with the project when I upload to my host so they asked me to recompile using 2.2.6

How can I do that please?

Thanks,

Jassim


How to check for null in var object

$
0
0

I have a var object as follows:

  var files = HttpContext.Request.Form.Files;

In my form, I'm allowing the user to state the local paths of 10 pictures I want uploaded to the form, where

the first 3 paths are set, and the remaining 7 are still null.

This doesn't work:

       if (!string.IsNullOrWhiteSpace(files[4].FileName)) files[4].CopyTo(filestream);

How can I get this right?

are model state require entityframework core installed to apply ?

$
0
0

Problem

Problem

Are  model state required install entity framework core  first to work or not ?

when i need to make validation i using data notation on model 

then on controller to validate data  using 

if(modelstate . valid)

{

}

so that my main question are model state depending on entity framework core or not ?

 

How to segregate Admin and Member view after login and throughout the system usage until logout?

$
0
0

Hello Net Core mastas!

I know this sound ridiculous for one to ask this simple question here. This is my first attempt on developing projects base on Net Core. I have no experience on Net Framework before.

I'm using Identity features of Net Core where I can have Admin and Member in the system.

What I am trying to achieve is to segregate view between Admin role and Member role, this what i'm trying to do currently. This code is generated using Identity scaffold.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");

                    var user = await _signInManager.UserManager.FindByEmailAsync(Input.Email);

                    var roless = await _signInManager.UserManager.GetRolesAsync(user);

                    //ViewData["UserInRole"] = roless[0];

                    _logger.LogInformation("User is in role ===================================> " + roless[0]);
                    _logger.LogInformation("Return Url ===================================> " + returnUrl);

                    if (roless[0] == "Admin")
                    {
                        // Return url to Admin controller
                        return RedirectToAction("Index", "Admin");
                    }
                    else if (roless[0] == "Member")
                    {
                        // Return url to Member controller
                        return RedirectToAction("Index", "Member");
                    }

                    //return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

Is this the correct approach? Or is there any proper approaches? 

Thanks in advance! Cheers \m/

Appears there is a controller conflict with the Route attribute

$
0
0

hi guys

I added  [Route("{Category"}] attribute to my Home Controller, so I can have products like this 

www.xyz.com/TShirts 

www.xyz.com/mugs 

which works fine, and other controllers too work fine, but I noticed that my users controller is hijacked, as I put a breakpoint and noticedwww.xyz.com/Users

goes to the breakpoint on the home page. here is my code

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

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

                 }).ToListAsync());

And the users controller has no code as of yet, as I cant seem to get it hit. But when I removed the route attribute on the HOme controller, it works

   public async Task<IActionResult> Index()
        {
return View()
}

An exception occurred during a WebClient request

$
0
0

Thanks in advance. I am getting error "An exception occurred during a WebClient request" on my .net core console application when I am trying to call web api, My code is as below.

public string Post(string url, SyncRequest request)
{
try
{
var settings = ReadConfigFile();
using (WebClient client = new WebClient())
{
string json = JsonConvert.SerializeObject(request);
Uri apiUrl = new Uri($"{settings.Api.DataSyncUrl.Replace("\"", string.Empty).Trim()}/{url}");
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
return client.UploadString(apiUrl, json);
}
}
catch (Exception ex)
{
logger.Error($"Error in POST request for URL : { url } , { ex.Message }");
return ex.Message;
}
}

public static AppSettings ReadConfigFile()
{
try
{
var fileName = Directory.GetCurrentDirectory() + "/\\appsettings.json";
AppSettings config = null;
using (StreamReader file = File.OpenText(fileName))
{
string jsonString = file.ReadToEnd();
config = JsonConvert.DeserializeObject<AppSettings>(jsonString);
}
return config;
}
catch (Exception ex)
{
logger.Error($"Error in reading json file , { ex.StackTrace }");
return null;
}
}

Is the performance of .net core differ much from windows and Linux?

$
0
0

I have a question below:

If there are two computers, all the hardware of them are the same.

One is runing .net core in Windows platform, the other is running .net core in Linux platform.

I think in Linux may be faster for Linux has no GUI.

Is that right? Can anyone tell me more about this? Thank you.

A compatible SDK version for global.json version: [2.2.6] was not found

$
0
0

Hi,

Why I am getting this error?

A compatible SDK version for global.json version: [2.2.6] from [D:\Inetpub\vhosts\jeccd.ae\httpdocs\alsadiq\global.json] was not found
Did you mean to run dotnet SDK commands? Please install dotnet SDK from:
https://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
A compatible SDK version for global.json version: [2.2.6] from [D:\Inetpub\vhosts\jeccd.ae\httpdocs\alsadiq\global.json] was not found
Did you mean to run dotnet SDK commands? Please install dotnet SDK from:
https://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409

My global.json is like this:

{"sdk": {"version": "2.2.6"
  }
}

Microsoft.AspNetCore.App is 2.2.6

Microsoft.AspNetCore.App is 2.2.6

Microsoft.EntityFrameworkCore is 2.2.6

Microsoft.NETCore.App is 2.2.6

Microsoft.NETCore.Platforms is 2.2.2

Kindly help..

Thanks,

Jassim


Range validation and error message

$
0
0

I have a validation for range for a property in my model and I'm trying to get the message to display when the range isn't 1 to 10 but it doesn't show on the page. This is what I have so far:

        [Required]
        [Range(1, 10, ErrorMessage = "Display Order be between 1 - 10")]
        [DisplayName("Display Order")]
        public int? DisplayOrder { get; set; }

How to create multiple lists of uploadable files

$
0
0

I have a form with the following:

         <input type="file" name="files" multiple class="form-control" />


I can capture the list of images like this:

        var files = HttpContext.Request.Form.Files;

My question is this:

What if I have two lines:

         <input type="file" name="files1" multiple class="form-control" />

         <input type="file" name="files2" multiple class="form-control" />

I don't think using HttpContext.Request.Form.Files will work, because it looks to me that it returns only one list.

If I'm right, what can I do to get both lists from one form?

I'd appreciate any advice!

Client Side MATBlazor

$
0
0

Hi,

I want to use MATBlazor through client side technique (webassembly)

what should i do for my blazor project ?

How to resolve SSIS Package Error "Login timeout expired"

$
0
0

I am loading & executing the SSIS package in Windows service and setting the necessary SSIS package parameters (Including connection string for OLEDB Connection Manager) from win service.

My SSIS package is reading the CSV file from one of directory of server and parsing it and inserting the data in staging database.

Everything was working fine with this algorithm. but from couple of days, i am getting the following error from SSIS package while processing CSV file:

Error message: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record is available. Source: "Microsoft OLE DB Provider for SQL Server" Hresult: 0x80004005 Description: "Login timeout expired". An OLE DB record is available. Source: "Microsoft OLE DB Provider for SQL Server" Hresult: 0x80004005 Description: "Invalid connection string attribute". SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Database Connection Manager" failed with error code 0xC0202009. There may be error messages posted before this with more information on why the AcquireConnection method call failed. Import the data in table "{tablename}" failed the pre-execute phase and returned error code 0xC020801C.

But when i try to re-process csv file after few time, then it is processing through SSIS without throwing any SSIS package error. I have tried every solutions found via googling. Even if i have tried to set ConnectionString of OLEDB Conecction Manager inside the SSIS.

Didn't working any solutions for me at this moments. Can anyone help me out?

Help would be more appreciated.

Web API routing doesn't appreciate non-public controllers

$
0
0

Pre-requirements

Create default netcoreapp2.2 web api project (I use Rider, but I believe it doesn't really matter).

Start the project.

Call an action in a controller and ensure that it works.

Change

Change the controller's access modifier from public to internal

Expected behavior

The same api call works

Actual behavior

The same api call return 404

Why I care

I used to close access modifiers as hard as I can. Once I saw developers that references anything from anywhere for no reason, and it was really hard to track. I'd love to have a flow that could warn me about wrong references.

If a class should not be referenced from another project, it's access modifier should be internal. Well, due to that's whatinternal means.

The actual flow seems weird to me: reflection should not think about access modifiers. For example, you are able to (de)serialize any class with any fields.

Unfortunately, I couldn't find a code where the route resolving happens. Could anyone link the file?

Asp.Net Core 2.2 targeting IIS and Linux

$
0
0

I would like to know if it is possible to create a ASP.Net Core API project that can target IIS in-process as well as Linux (krestel) ? Thank you.

Changing which form submit button responds to the enter key

$
0
0

Okay, so I have a Razor page CSHTML file, with a model backend for the page in C#. I have a form that for our purposes, had to have a second submit button. However, this second button is placed before the first, and pressing the enter key now moves forward with this new button rather than the old button I intended. Here's roughly the CSHTML I have for the form, where the button for "MoreInfo" is the new button I've added, and "Next" is the button I want to correspond to the enter key:

<form method="post" asp-route-returnUrl="@Model.ReturnUrl"><div class="form-group"><label asp-for="Input.Email">Email</label><input asp-for="Input.Email" class="form-control" autofocus /></div><div class="form-group"><button asp-page-handler="MoreInfo" class="btn-link">More Info</button></div><div class="form-group"><button type="submit" class="btn btn-primary pull-right text-uppercase" name="button" value="next">NEXT</button></div></form>

I've tried it where I use the attribute type="button", and while that makes the enter key work as intended again, the button no longer does anything, and it doesn't make any request. This is the corresponding C# function I have when the user presses this new button:

public IActionResult OnPostMoreInfo(string returnUrl = null)
{
    ReturnUrl = returnUrl;
    Username = Input.Email;

    return RedirectToPage("./MoreInfo", new { returnUrl = ReturnUrl });
}

And another thing I've thought of is to detect if the user triggered this function with the enter key, and then direct them appropriately. But I'm not sure I understand how to detect key presses in this context.

Any help is greatly appreciated.


How can I raw js&css more convenient by code?

$
0
0

I want to show different css&js  in different browsers.

I do it like this:

string APPJS = "";
string APPCSS = "";
if (G.IsIE == true)
{
APPJS = "<script type='text/javascript' src=/lib/jquery-1.12.4.min.js></script>";
APPJS += "<script type='text/javascript' src=/js/appIE.min.js></script>";
}
else
{
APPCSS = "<link rel='stylesheet' href = '/css/animate.min.css' >";
APPJS = "<script src=/lib/jquery-3.2.1.min.js></script>";
APPJS = "<script src=/lib/wow.min.js></script>";
APPJS += "<script src=/js/app.min.js></script>";
APPJS += "<script type='text/javascript' src=/js/app.min.js></script>";
}

Yes, it works. However, every time I add/edit some CSS or js, it will take me some minute to check if the string I add is right. What's more, I think my way is not the best way to achieve this.

Is there any way better to achieve this? Thank you.

Quick React learning guide for query developer

$
0
0
Hi,
I want to learn react quickly and develop an enterprise application.

I ll have to design UI as my own self.
Any guideness ll be appreciated. Thank you.
How react releases ll be handled and ended?

Could not load type 'System.Web.HttpContext' For FFMpegConverter

$
0
0

Hi,
In Asp.net core when i write this code

                var ffmpeg = new NReco.VideoConverter.FFMpegConverter();

its show this error , how to solve this problem?

TypeLoadException: Could not load type 'System.Web.HttpContext' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

How to convert json to create delete statement from header table and footer?

$
0
0

problem

How to convert json to create delete statement  for sql query?

I work on asp.net core 2.1 and i create class library generate SQL statement to execute on another layer 

i have json string as following

{
   "master" : {
       table: "",
       fields : {},
       keys: {}
       
   },
   "details" : [
       {
           table: "",
           fields : {},
           keys: {}
          
       }
   ]
}


Example:
{
   "master" : {
       table: "master_table",
       fields : {
           "name" : "bar",
           "address" : "fleet street",
           "phone" : "555"
       },
       keys{
           "id" : 1,
           "branch_id" : 1 
       }
       
   },
   "details" : [
       {
           table: "detail1_table",
           keys{
               "id" : 1,
               "branch_id" : 1 ,
               "LineNumber" : 1
           },
           fields : {
               "ItemCode" : item-5050,
               "Quantity" : 10 ,
               "Price" : 50 ,
               "Total" : 500 
           }
       },
       {
           table: "detail1_table",
            keys{
               "id" : 1,
               "branch_id" : 1 ,
               "LineNumber" : 2
           },
           fields : {
               "ItemCode" : item-9050,
               "Quantity" : 5 ,
               "Price" : 20 ,
               "Total" : 100 
           }
       }
   ]
}

here on json i need to make function c sharp as class library convert json to delete query from two tables

table header

and

table footer

Result of code deletefrom master_table where id=1and branch_id=1deletefrom detail1_table where id=1and branch_id=1and Linenumber=1

so that how to convert json string above to sql delete query ?

but really the main goal is to create dynamic sql string query

by depending  keys and fields on two tables header and footer meaning

if i change data above then it will do another query with fields or keys changed

scripts table

CREATETABLE[dbo].[detail1_table]([id][int]NOTNULL,[branch_id][int]NOTNULL,[LineNumber][int]NOTNULL,[ItemCode][nvarchar](50)NULL,[Quantity][int]NULL,[Price][decimal](18,2)NULL,[Total][decimal](18,2)NULL,CONSTRAINT[PK_detail1_table]PRIMARYKEYCLUSTERED([id]ASC,[branch_id]ASC,[LineNumber]ASC)WITH(PAD_INDEX =OFF, STATISTICS_NORECOMPUTE =OFF, IGNORE_DUP_KEY =OFF, ALLOW_ROW_LOCKS =ON, ALLOW_PAGE_LOCKS =ON)ON[PRIMARY])ON[PRIMARY]

GO
/****** Object:  Table [dbo].[master_table]    Script Date: 11-08-2019 07:42:49 ص ******/SET ANSI_NULLS ON
GOSET QUOTED_IDENTIFIER ON
GOCREATETABLE[dbo].[master_table]([id][int]NOTNULL,[branch_id][int]NOTNULL,[name][nvarchar](50)NULL,[address][nvarchar](50)NULL,[phone][nvarchar](50)NULL,CONSTRAINT[PK_master_table]PRIMARYKEYCLUSTERED([id]ASC,[branch_id]ASC)WITH(PAD_INDEX =OFF, STATISTICS_NORECOMPUTE =OFF, IGNORE_DUP_KEY =OFF, ALLOW_ROW_LOCKS =ON, ALLOW_PAGE_LOCKS =ON)ON[PRIMARY])ON[PRIMARY]

GO
INSERT[dbo].[detail1_table]([id],[branch_id],[LineNumber],[ItemCode],[Quantity],[Price],[Total])VALUES(1,1,1, N'item-500',10, CAST(50.00AS Decimal(18,2)), CAST(500.00AS Decimal(18,2)))INSERT[dbo].[detail1_table]([id],[branch_id],[LineNumber],[ItemCode],[Quantity],[Price],[Total])VALUES(1,1,2, N'item-500',5, CAST(50.00AS Decimal(18,2)), CAST(250.00AS Decimal(18,2)))INSERT[dbo].[master_table]([id],[branch_id],[name],[address],[phone])VALUES(1,1, N'michel plater', N'francw', N'1222222')INSERT[dbo].[master_table]([id],[branch_id],[name],[address],[phone])VALUES(2,1, N'sergio ram', N'german', N'1221111')

How to generate delete sql query to two tables ?

Enum model binding [FromRoute] behaves differently than [FromBody] in .net core

$
0
0

I am getting different behaviors in the bindind model with enum and I can't get the correct value when passing information that is out of the enumeration limit.

I have a TestEnum enumeration containing Test1 = 1, Test2 = 2, Test3 = 3.

In [HttpPost] or [HttpPut] using [FromBody], my DTO object correctly receives the enumeration value, even when I pass a different value like 5 for example.

However, in a Get/Put using [FromRoute], my DTO object correctly receives enumeration when the entered values are within the enumeration limit (1, 2, or 3).

If I pass 5, the value of the enumerator becomes zero, unlike [FromBody] which can receive the value 5 normally even though it is outside of the coded Test1, Test2, and Test3.

publicenumTestEnum{Test1=1,Test2=2,Test3=3}

It perfectly receives the values even being outside the enumeration limit.

[HttpPost]public async Task<ActionResult<NotificationResult>>Post([FromBody]TestCommand command)

Here, in [FromRoute] and [FromBody] values are perfectly received when they are within the enumeration boundary.

When out of range, [FromRoute] gets zero and [FromBody] gets 5.

[HttpPut("{id:int}")]public async Task<ActionResult<NotificationResult>>Put([FromRoute]TestEnum id,[FromBody]TestCommand command)

Here, in [FromRoute] values are perfectly received when they are within the enumeration boundary.

When out of range, [FromRoute] gets zero.

[HttpGet("{id:int}")]public async Task<ActionResult<TestQueryResult>>GetById([FromRoute]TestEnum id)

I would like to receive the value even if it is outside the encoded limit in enumeration.

Viewing all 9386 articles
Browse latest View live


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