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

Blazor - how to apply attribute to parent element from a component

$
0
0

I have the following cshtml page:

@inheritsBlazorLayoutComponent<NavMenuToggleComponent></NavMenuToggleComponent><div class="main"><div class="top-row px-4"><a href="http://blazor.net" target="_blank"class="ml-md-auto"><span class="col-md-1">About</span></a><NavLinkclass="nav-link pull-right col-md-2" id="logout" href="logout"><span class="fas fa-sign-out-alt" aria-hidden="true"></span><span class="col-md-1 pull-right">Logout</span></NavLink></div><div class="content px-4">@Body</div>

as you can see I have a component called NavMenuToggleComponent who's code is:

@inheritsBlazor.Web.Functions.MenuFunctions<div class="pl-4  navbar navbar-dark"><button class="navbar-toggler navbar-brand main-button" title="MENU" onclick=@ToggleNavMenu>
    MENU</button></div><div class="sidebar @(CollapseNavMenu ? "collapse" : null)"><NavMenu/></div>

I have a function on the button click event and this is declared in the MenuFunctions Class. This, function simply has :


public class MenuFunctions : BlazorComponent
{
public
voidToggleNavMenu() {CollapseNavMenu=!CollapseNavMenu; }…..

Now to keep it simple from this function I want to be able to add an attribute to the element on the parent that has the class content on it. so as an example I might want this to end up as<div class="content px-4" style="color:red"> so How would I attach the style attribute? The one caveat that also makes this more difficult is that I am not allowed to embed any `@functions` In my .cshtml page, hence my MenuFunctions class


How to use same form or page for insert and update . it edit but cannot insert ?

$
0
0

problem

How to use same form or page for insert and update . it edit but cannot insert ?

I have component name employees used for edit record 

i need to use it for insert but cannot do that .

it load data on case of passing record for edit or not meaning i need to prepare this form for two purpose insert and edit

so that please how to modify it for insert also ?

export class EmployeesComponent{
    employees = {}
    empformlabel: string = 'Add Employee';  
    empformbtn: string = 'Save';
    constructor(private formBuilder: FormBuilder ,private router: Router , private api:ApiService,private toastr: ToastrService){}
    addForm: FormGroup; 
    btnvisibility: boolean = true; 
    ngOnInit() {
      this.addForm = this.formBuilder.group({  
        employeeId: [],  
        employeeName: ['', Validators.required],  
        branchCode: ['', [Validators.required, Validators.maxLength(2)]]
      }); 
       let empid = localStorage.getItem('editEmpId'); 
       console.log(empid) ;
    if (+empid > 0) {  
      console.log("success") ;
      this.api.getEmployeeById( +empid).subscribe(data => {  
        this.addForm.patchValue(data);
        console.log(data);  
      })  
      this.btnvisibility = false;  
      this.empformlabel = 'Edit Employee';  
      this.empformbtn = 'Update'; 
    }  

      }


onSubmit() {  
  console.log('Create fire');  
  this.api.createEmployee(this.addForm.value)  
    .subscribe(data => {  
      this.router.navigate(['employeelist']);  
    },  
    error => {  
      alert(error);  
    });  
}  
onUpdate() {  
  console.log('Update fire');  
  this.api.updateEmployee(this.addForm.value).subscribe(data => {  
    this.router.navigate(['employeelist']);  
  },  
    error => {  
      alert(error);  
    });  
}  

}
<div class="col-md-6">  <h2 class="text-center">{{empformlabel}}</h2> <form [formGroup]="addForm" novalidate class="form">  <div class="form-group">  <label for="employeeId">employee Id:</label>  <input type="number" formControlName="employeeId" placeholder="employeeId" name="employeeId" class="form-control" id="employeeId">  </div>  <div class="form-group">  <label for="branchCode">Branch Code:</label>  <input type="number" formControlName="branchCode" placeholder="branchCode" name="branchCode" class="form-control" id="branchCode">  </div>  <div class="form-group">  <label for="employeeName">Employee Name:</label>  <input formControlName="employeeName" placeholder="Employee Name" name="employeeName" class="form-control" id="employeeName">  <div class="alert  alert-danger" *ngIf="addForm.get('employeeName').hasError('required') && addForm.get('employeeName').touched">  
          Employee Name is required  </div>  </div>  <button class="btn btn-success" [disabled]='addForm.invalid' *ngIf="btnvisibility" (click)="onSubmit()">Save</button>  <button class="btn btn-success" [disabled]='addForm.invalid' *ngIf="!btnvisibility" (click)="onUpdate()">Update</button>  <p>Form value: {{ addForm.value | json }}</p> </form>  </div>  

Uploading asp.net core 2.1 site to 1&1 shared hosting (windows hosting)

$
0
0
I have recently been playing around with asp.net core. I have built a site and have uploaded all the project files to my hosting account via FTP using FileZilla. When I then try to access the site I get a 403.14

I deleted the files from the server and tried to FTP it from visual studio and absolutely nothing happened. No files were uploaded.

In the end, I went back to FileZilla and re-uploaded the files but I am back to my original 403.14 error.

I probably should have said in the beginning that the site works fine when I run it on my local machine when I debug in visual studio.

Have I missed some step that I was previously unaware of? Am I being a dummy? I just don't seem to know what I am doing lol.

I have never done this before, I was up until a couple of weeks ago a webforms guy. Sadly webforms seems to be getting killed off by Microsoft, so adapt or die as they say. Sadly at this moment in time, I don't seem to be adapting all that well.

UserPrincipal has no way to set 'PhysicalDeliveryOfficeName' attribute

$
0
0

I am using UserPrincipal to create a new user in AD, however I cannot set the 'office' field. This is an application using asp.net core 2.2

I believe it should be called 'PhysicalDeliveryOfficeName', but it doesn't exist as part of UserPrincipal:

UserPrincipal usr = new UserPrincipal(ctx);

usr.GivenName = givename;
usr.Surname = surname;
usr.PhysicalDeliveryOfficeName = "New York"; //not found
usr.Save();

How can I set this field?

Help with authentication

$
0
0

Hi

I am looking to move over to .net core with EF core and angualr, and I am looking to implement authentication.

My current MVC project uses identity.

I have watch the pluralsight tutorials and read a lot of other bits and pieces on it, and alot of them are on older versions, and they all have very different ways of doing things,so i have a few questions.

Is Identity still a good option for authenticating users?

Should I been looking for jwt implementation, as apposed to cookies?

Are the implementations back end the same as mv, eg do u still build a userstore then return x to the user (not to worried about the front end right now, will up my focus on that later, i am looking at it now but can only focus on one bit at a time)

What information is stored in the token which authenticates, in the pluralsight example it saves a lis of claims and generates token from it, which seems a little weird, i thought it would be a reference to the user, then you reference the claims later for authentication.

If anyone also has a link to a tutorial or code sample it would be appriciated.

Culture cookie does not change the culture in browsers other than Firefox

$
0
0

Hi,

Thanks to Sherry Chen's help in this thread I've managed to get my page changing culture based on the cookie the user has set. At least I thought so as I checked this only in Firefox browser. Having published my page I discovered that his functionality doesn't work in Chrome and IE (haven't tested other browsers). I checked and in all browser the cookie IS created and it contains correct value etc., but only in Firefox it effects in changing the culture. Here's the method that's creating the cookie:

public async Task<IActionResult> OnGetSetCultureAsync(string culture)
        {
            HttpContext.Response.Cookies.Append("Culture", "c=" + culture + "|uic=" + culture,
                new Microsoft.AspNetCore.Http.CookieOptions
                {
                    Expires = DateTimeOffset.Now.AddMonths(3)
                });
            var returnUrl = Request.Headers["Referer"].ToString();
            if (returnUrl.Contains("?culture="))
            {
                var url = returnUrl.Substring(0, returnUrl.IndexOf("?culture="));
                return Redirect(url + "?culture=" + culture);
            }
            else
            {
                return Redirect(returnUrl + "?culture=" + culture);
            }
        }

Here's a github repository for the project. And my page is currently publishedhere, so you can test it there. Any help will be appreciated.

Regards,

Robert

ASP.NET Core - softwares required

$
0
0

Hi,

I have a windows server 2016.

What are the software and version required to work with ASP.NET Core ?  what version of Visual studio , edition and framework is required to be installed on the server ? Are there any other software / NuGet packages which are required as pre-requisite.

Thanks

Store data in masterdb as string or id of detail table?

$
0
0

Hi all,

Here is the situation,

Lets say I need to store State and Country data in a DB.

As you know I can store it as String as is, like (California /USA) or I can store it as States's Table ID and Countries' table ID (14/81)

The thing is the stored data is only one word and I don't want to store it as id (and get it with join).

Because in SPA application it is hard to construct a page from json data (you need to store id in a hidden input and send it etc. etc.)

What do you think?

Should I afraid of using strings  to store State/Country data? Because in 10 years record count can be million and that time strings can occupy lots of space and blow the db?

thanks


How should I keep UserId (in a hidden input or as session value)

$
0
0

Hi all,

In a SPA I need to use UserID to save related data.

I use  <input id="UserId" hidden value="@Model.Id" /> this technique to get it.

But what about havving a session and keep the UserId there?

Is it safer ?

But if connection is gone and come back while typing session data also may have gone and it may cause unwanted errors

If I am thinking right because I don't have experience in that area

Generate a success/failure message in Razor page

$
0
0

I want to return a razor page after a POST with a success popup (or maybe layout message, but I think a popup would be better). I am getting confused as many solutions I have found are designed to work with an MVC layout and not my Core 2.2 Razor Pages.

For Example:

publicasync Task<IActionResult> OnPostAsync()

        {

            if (!ModelState.IsValid)

            {

                setIds();

                return Page();

            }

            try           

{

            _context.MyObject.Add(TestModel);

            await _context.SaveChangesAsync();

            }

            catch (Exception e)

            {

                return Page(); //return popup with error message

            }

            setIds();

            return Page(); //return popup with success message

        }

Export Database Data In Excel File

$
0
0

hi 

i was building web application that connect to Database and this is my code 

[HttpPost]
        public IActionResult Index(int AccountID,DateTime StartDate, DateTime EndDate,string ReportNO)
        {
            var UserName = User.Identity.Name;
            SqlConnection connection = new SqlConnection(my connection string );
            connection.Open();
            SqlCommand command = new SqlCommand("SELECT * FROM [dbo].[tblReports]", connection);
            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
reader.read();

}
return view();
}
              

how i can export SqlDataReader in excel sheet file?

How to stop form resending data on refresh

$
0
0

Hi all,

How can I  stop form resending data on refresh?

Injecting services indiviually help

$
0
0

Hi

I have a lot of services which i need to inject, I don't want to have to go through them individually, is there a better way to add them in bulk?

(eg in my MVC5project i do something like:

builder.RegisterAssemblyTypes(Assembly.Load("Service"))

.Where(t => t.Name.EndsWith("Service"))

.AsImplementedInterfaces()

.InstancePerLifetimeScope();

)

Any suggestions?

Are this function written correct on web API or not ?

$
0
0

Problem

Are this function written correct on web API or not ?

I write function return scalar value as string but i dont know are this correct or not ?

this function get data of label text control from database ?

[HttpGet("{tableName}/{FieldName}")]
        [Produces("text/plain")]
        public string GetReferenceFileData([FromRoute] string tableName, [FromRoute] string FieldName)
        {
          var Result =  (from h in _context.ReferenceFiles
                          where h.TableName == tableName && h.FieldName == FieldName
                          select h.LabelText).FirstOrDefault();
            if(Result==null)
            {
                Result = "Not Exist";
            }

            return (Result);


        }

Are this function correct and are return type now i correct ?

i beginner on web API so that i ask you  ?

Moving over to angular, model validation in the UI

$
0
0

Hi

I am moving over to angular , from mvc 5, and I have notice that very few of the examples use model binding on the UI for error messages, and unobtrusive validation.

Is model binding still considered a good way to validate, or is building my own validation through typescript the way to go, or is there another best practice i should be looking into.

Any thoughts would be appriciated.


second page not reached on IIS

$
0
0

On IIS Express my application calls from a table like this 

<td><a href="/PageX?nata=@Html.DisplayFor(modelItem => item.theKey)" class="btn btn-info"   

and so forth ....

But when I published to the virtual machine the app & first page index runs fine but the next page does not HTTP error 500.0  I noticed the IIS page acts as if the requested URL is htttp://localhost:80/PageX?nata=2111 and Physical Path C:\innetpub\wwwroot\PageX   That physical path doesn't exist & the diagnostic may not be relevent

The event log looks fine   I even put an email to send me if the OnGet() fired on 'PageX' - but nothing happens at published    I cannot think this is unique....

ExecuteRequestHandler,  AspNetCoreModuleV2, aspNetCore, 0x80004005   and the link doesn't make sense ...to me.  https://support.microsoft.com/en-us/help/942031/http-error-500-0-internal-server-error-error-when-you-you-open-an-iis

Thanks !!!

Client Validation Error With Input Fields Containing Currency Values

$
0
0

I'm developing a web app using Asp.Net Core 2.1 and Code First.I've got a bunch of properties of type decimal and decorated them with the following attribute:

        [DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]

The problem is when the form goes in edit mode,the client validation throws the following error since the input field contains the currency symbol:

The field must be a number.

How can I tell asp.net core to treat an input field with currency symbol as decimal value?

Deploying ASP.NET Core 2.2 onto an IIS Server - Debugging and advice.

$
0
0

I deployed my test website onto a local IIS server by publishing it to a folder and making sure I had 'Windows Authentication' selected.

The page loads but my Authorisation policies are not working and I have no idea how to see why.

            services.AddAuthentication(IISDefaults.AuthenticationScheme);

            services.AddAuthorization(options =>

            {

                options.AddPolicy("Admin", policy =>

                    policy.Requirements.Add(new Check(newstring [] { "Admin" })));

                options.AddPolicy("User", policy =>

                    policy.Requirements.Add(new Check(newstring[] { "User" })));

            });            

            services.AddTransient<IClaimsTransformation, CustomClaimsTransformer>();

I can see that my user Claims were successful, and I can navigate to pages without a decorator, but I cannot see items with a

[Authorize(Policy = "Admin")] or [Authorize(Policy = "User")]

decorator.

I tried attaching the process to visual studio, but I don't get any messages. How do I debug a CORE 2.2 site when it is running on IIS?

Dotnet Core calling a soap service issue

$
0
0

I have a dotnet core 2.0 app which makes some calls out to some 3rd party soap services. The web references have been added to the project using a wsdl and connected services. Everything works fine but periodically it stops working and throws an error.

Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

System.TypeLoadException: Type 'generatedProxy_2' from assembly 'ProxyBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.

at SoapClient.GetDetailsAsync(GetDetailsRequest request) in Connected Services\SoapClient\Reference.cs:line 1146

This api runs on linux container and when i restart the api the error goes away and everything runs fine. There is no issue on the service side because the method it calls exists. Web reference has been updated to the latest. There is no outgoing call from the api when this error occurs.

Any help in debugging or fixing this issue?

Thanks

Angular, in memory HTTP

$
0
0

Hello everybody,

Is this the correct forum for a question about Angular ?

I am going through https://angular.io/tutorial/toh-pt6 (the HTTP section of the tutorial) and at a moment they say to introduce this in app.module.ts :

HttpClientModule,

// The HttpClientInMemoryWebApiModule module intercepts HTTP requests
// and returns simulated server responses.
// Remove it when a real server is ready to receive requests.
HttpClientInMemoryWebApiModule.forRoot(
  InMemoryDataService, { dataEncapsulation: false }
)

The tooltip on InMemoryDataService displays me a text, that I have to get through a screen copy, a picture display program, the keyboard and the notepad. This is how I translate it, followed by the original text in French  :

(TS) The argument of type 'typeof InMemoryDataService' cannot be assigned to the parameter of type 'Type<InMemoryDbService>'

Impossible to assign type 'InMemoryDataService' to type 'InMemoryDbService'.
  The property 'CreateDb' is missing in type 'InMemoryDataService'.
  (alias) class InMemoryDataService
  import InMemoryDataService
(TS) L'argument de type 'typeof InMemoryDataService' n'est pas attribuable au paramètre de type 'Type<InMemoryDbService>' Impossible d'assigner le type 'InMemoryDataService' au type 'InMemoryDbService'. La propriété 'CreateDb' est manquante dans le type 'InMemoryDataService'.

It seems the implementation of in memory HTTP has been modified in a way that two parts are incompatible.

Any hint about a way to get it run ?

Viewing all 9386 articles
Browse latest View live


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