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

Migration of asp.net web application 4.5 framework project to .net core 3.1

$
0
0

Hi Team,

I am migrating asp.net web application 4.5 framework project to .net core 3.1 so what would be architecture do i need to follow please find my observation below

1> Do i need to register all services in ConfigureServices below as I have many services

publicvoid ConfigureServices(IServiceCollection services) {services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));services.AddControllers(); }

2>Do I need to write all function inside Configure

publicvoid Configure(IApplicationBuilder app, IWebHostEnvironment env) {if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }


Show User Logged to All Users in Asp.net core

$
0
0

Hi,
when user login to site (for example test-user) its save session for all user means when other user open site they cant see the test-user information and go to his profile.
i have this problem with asp.net core 3.0   i just change startup.cs

startup.cs 

   services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), c => c.MigrationsAssembly("DataLayer")));

            services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
            {
                options.Password.RequiredLength = 6;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = false;
            })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddTransient<DbContextSeedData>();
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = TimeSpan.FromDays(1);
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            // Add application services.
            services.AddControllersWithViews(options =>
            {
                options.Filters.Add(typeof(DynamicAuthorizationFilter));
            }).AddRazorRuntimeCompilation();

            services.AddMvc(options => options.Filters.Add(typeof(DynamicAuthorizationFilter)));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();

            }


            FileExtensionContentTypeProvider contentTypes = new FileExtensionContentTypeProvider();
            contentTypes.Mappings[".apk"] = "application/vnd.android.package-archive";

            app.UseHttpsRedirection();

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    // Cache static file for 1 year
                    if (!string.IsNullOrEmpty(context.Context.Request.Query["v"]))
                    {
                        context.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=31536000" });
                        context.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddYears(1).ToString("R") }); // Format RFC1123
                    }
                }
            });

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseSession();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                endpoints.MapControllerRoute(
                name: "areas",
                pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");



            });



        }

Can't Run my app has IIS Express

$
0
0

Ok so I did some settings when trying to deploy asp.net core web app locally sometimes ago. Suddenly i just noticed that on vs when I try to run my app.

I can not run app with the IIS Express option. I have to pick the the name of the app when I want to debug.

https://pasteboard.co/J54l9V9.jpg   check that link for a snapshot so you understand what am saying

This is a snapshot of my vS to explain the problem.  Please this is a problem for me. Cos if I have multiple website on my solution I I cant run every thing at once.

How do I fix this problem. Got a problem with multiple sites and I need to run every thing at once so I can monitor all from IIS instance cos they all depend on each other to work well.

Error In Packages

$
0
0

hi, in my project i have these layers 

- Api (my apis that use in app)
- Data  (my data layer)
- Domain Classes (my models) 
 - Xamarin_App

- Xamarin_App.Android

my api layer is .net core 3.0 but i want use models in api layer (and identity tables (AspNetUsers, AspNetRoles , ...... )) and xamarin layer  but i have this error 

and i cant use domain classes layer in xamarin and api toghether 


<div> <div></div> <div>Error NU1202 Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 3.0.0 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package Microsoft.AspNetCore.Identity.EntityFrameworkCore 3.0.0 supports:</div> <div>  - netcoreapp3.0 (.NETCoreApp,Version=v3.0)</div> <div>  - netstandard2.1 (.NETStandard,Version=v2.1) Xamarin_App H:\work-project\Xamain_Toturial_1\Xamarin_App\Xamarin_App\Xamarin_App.csproj 1</div>

</div> <div></div> <div>Error NU1202 Package Microsoft.EntityFrameworkCore.SqlServer 3.0.0 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package Microsoft.EntityFrameworkCore.SqlServer 3.0.0 supports: netstandard2.1 (.NETStandard,Version=v2.1) Xamarin_App H:\work-project\Xamain_Toturial_1\Xamarin_App\Xamarin_App\Xamarin_App.csproj 1</div>



how can i use doamin classess as cross platform layer ?

i want to understand oauth2 and open id connect a little more

$
0
0

can i just confirm there is no docs on the oauth site and i should just look through these:

https://openid.net/specs/openid-connect-core-1_0.html

Problem to change active state of ul elements via jquery.

$
0
0

Hi

In my layout view, i have ul element with some li as follow :

<ul id="lstItems" class="list-unstyled components"><li class="active"><a href="~/Home/Index"><i class="fa fa-chart-line"></i>
                        Dashboard</a></li><li><a href="~/Patient/Index"><i class="fa fa-user"></i>
                        Patients</a></li><li><a href="~/Visits/Index"><i class="fa fa-pen"></i>
                        Visits</a></li></ul>

As you can see, The first li element has active class. i want to change this state when user click on other li elements. To do this, i've used this jquery code :

$('#lstItems li').on('click', function () {$(this).parent().find('li.active').removeClass('active');$(this).addClass('active');
        });

This code works when i set breakpoint on my browser debugger, but when the page refreshed, it returns back to set first li active!

Where is my problem & how to solve ?

Thanks in advance

Where to modify form request on generated code

$
0
0

Here is some generated code, not modified:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using pcore31.Models;

namespace pcore31
{
    public class AddpetModel : PageModel
    {
        private readonly pcore31.Models.DatabaseContext _context;

        public AddpetModel(pcore31.Models.DatabaseContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            return Page();
        }

        [BindProperty]
        public Pet Pet { get; set; }

        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Pet.Add(Pet);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }
    }
}

Referring to these lines:

    _context.Pet.Add(Pet);  // all fields are in this already????
    await _context.SaveChangesAsync();

If a user enters a pet name in the petname field, all small letters, but I want to have the first letter upper case (changed in code), where do you do that, since the generator doesn't generate individual fields?

Like

string newname = UppercaseFirst(Pet.petname);
// Or would I have to request petname separate?
// Something like that.

// Then new name is inserted instead of what user entered.

Again, I'm old school, normally wrote my own code / classes.  I'm new to having to modify generated code.

Problem with init dbContext : No database provider has been configured for this DbContext.

$
0
0

Hi

In my project, i've setup my db context, now when i want to work with database, i've got this error :

System.InvalidOperationException: 'No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.'

Here is my startup class for configure service method :

...
public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }        

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<Models.MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbContextConnectionString")));
        }
...

And here is my appsettings file :

{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
    }
  },"AllowedHosts": "*","ConnectionStrings": {"MyDbContextConnectionString": "Data Source=.;Initial Catalog=MyDb;Integrated Security=True;MultipleActiveResultSets=true"
  }
}

And here is my action method :

public class PatientController : Controller
    {
        private MyDbContext _dbContext = new MyDbContext();

	...

        public IActionResult SearchPatient(string q)
        {
            var patients = _dbContext.Patients.Where(p => p.NationalID == q || p.PatientCaseID == q).ToList(); // Cause error!!
            return PartialView("_PatientsSearchResult", patients);
        }
    }

Where is my problem & how to solve it?

Thanks in Advance


Is generated code sanitized

$
0
0

Untouched generated code here:

@page
@model pcore31.AddpetModel

@{
    Layout = null;
}

<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Addpet</title></head><body><h4>Pet</h4><hr /><div class="row"><div class="col-md-4"><form method="post"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Pet.PetName" class="control-label"></label><input asp-for="Pet.PetName" class="form-control" /><span asp-validation-for="Pet.PetName" class="text-danger"></span></div><div class="form-group"><label asp-for="Pet.Dogpic" class="control-label"></label><input asp-for="Pet.Dogpic" class="form-control" /><span asp-validation-for="Pet.Dogpic" class="text-danger"></span></div><div class="form-group"><label asp-for="Pet.Odate" class="control-label"></label><input asp-for="Pet.Odate" class="form-control" /><span asp-validation-for="Pet.Odate" class="text-danger"></span></div><div class="form-group form-check"><label class="form-check-label"><input class="form-check-input" asp-for="Pet.Ocheck" /> @Html.DisplayNameFor(model => model.Pet.Ocheck)</label></div><div class="form-group"><input type="submit" value="Create" class="btn btn-primary" /></div></form></div></div><div><a asp-page="Index">Back to List</a></div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}</body></html>

Take for example this line:

<input asp-for="Pet.PetName" class="form-control" />

Is that asp-for also appling the equal to htmlentities?  Or will I have to modify the code and do that myself.

A search I got punching in "<input asp-for" yielded  https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1

I searched that page for "encode", "entity", "enti", "santi", "sanitize.  No hits at all.

So if the generated pages doesn't sanitize data, why are they used?  I normally sanitize the request, but again if I have to sanitize each field, why the auto context instead of individual request?

For example:

string petname = Request.Form["petname"];
// I could add a custom sanitize class

string petname =  Helper.sanitize(Request.Form["petname"]);

// Something like that.

Sorry this "generated" code still confuses me.

How can I return a 404 status code by app.UseStatusCodePages?

$
0
0

These days I am handling 404 Not Found by Asp.Net Core .

As we know, there are several ways to achieve this: app.UseStatusCodePagesWithRedirects/app.UseStatusCodePagesWithReExecute/app.UseStatusCodePages .

I have to choose the app.UseStatusCodePages for I need to localizer the page by URL.

For example:

https://www.microsoft.com/en-us/microsoft-365/

The 'en-us' in URL just for deciding the language of the page.

Here is my code in startup.cs

app.UseStatusCodePages(async context =>
            {
                string currentCulture = "";
                if (context.HttpContext.Request.Path.Value.Split('/').Length < 2)
                {
                    currentCulture = "en";
                }
                else
                {
                    string LanguageGet = context.HttpContext.Request.Path.Value.Split('/')[1];
                    currentCulture = SupportedCultures.Find(X => X.Name == LanguageGet) == null ? "en" : SupportedCultures.Find(X => X.Name == LanguageGet).Name;
                }
                var redirectPath = "/" + currentCulture + "/Error/" + context.HttpContext.Response.StatusCode;
                context.HttpContext.Response.Redirect(redirectPath);
            });

Now it works.

However, after I input a URL which does not exist. The header shows a 302 status code in the Network of Chrome DevTools but not a 404 status code.

Well, when I input the URL(https://www.microsoft.com/en-us/123.html), the header shows a right 404 status code in the Network of Chrome DevTools.

I searched about this on Google. Someone said I should add a ProducesResponseType in the controller, just like this:

public class OthersController : Controller
    {
        [Route("{culture=en}/Error/{code:int}")]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public IActionResult Error(int code)
        {            
            return View(code);
        }
    }

Well, it doesn't work any. I want to solve this because of SEO.

How can I solve this? Thank you.

Display certain records in MVC CRUD application.

$
0
0

Hi All,

I am in the process of creating an Employee Training Records database using SQL and Visual Studio 2019.

So far so good, however at the moment I have one question which I hope you can me out with.

I have a Model, Controller and View for listing employees. There is an option to amend if the employee is current or not.

I would like to create a page which just lists current employees and another which just lists non current employees. 

How do I achieve this? I know I can have a search/filter facility but I want to make this as easy as possible for end users.

Do I use a IF or WHERE statement? If so how and where would this be placed?

Many thanks in advance.

Mick  

  

JwtBearerOptions - token validation offline or online?

$
0
0

Hi all,

I'm working on ASP.Net Core 3.1 for API development, and I was adding logic to validate Bearer tokens, I'm quite new on this and found out logic like this:

public static void AddAuthentication(this IServiceCollection services, IConfiguration config)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

            .AddJwtBearer(options =>
            {
                options.Authority = "https://loremipsum.com";
                options.RequireHttpsMetadata = true;
                options.Audience = "LoremIpSum";
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateActor = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    RequireExpirationTime = true,
                    ValidIssuer = "https://loremipsum.com",
                    NameClaimType = "name"
                };
            })
            .AddCookie(options => options.SlidingExpiration = true);
        }

I was wondering, this allows me to specify some options, but how can I tell to validate tokens offline or online?

Or by default this provides logic only for online validation?

This might be a rookie question and it may be quite simple but I'm not following :(

Simple Register page unable to post

$
0
0

Hi Guys,

I have simple register page and unable to save to db using ASP.NET core MVC, below is my code

  [HttpPost]
        public IActionResult Index(Registration registration)
        {
            if(ModelState.IsValid)
            {
                _context.Registration.Add(registration);
                _context.SaveChanges();
            }
            return View(registration);
        }
@model GOMLIB.Models.Registration<div class="row"><div class="col-xl-12"><div class="card"><div class="card-body"><h4 class="header-title text-yellow">REGISTER WITH US</h4>
                @*<p class="sub-header">
                        Easily extend form controls by adding text, buttons, or button groups on either side of textual inputs, custom selects, and custom file inputs</p>*@

                @using (Html.BeginForm())
                {
                    <div class="form-group mb-1 mt-3"><div class="input-group"><input type="email" class="form-control" placeholder="Enter email address" required parsley-type="email" aria-label="Enter email address"><div class="input-group-append"><input class="btn btn-info waves-effect waves-light" type="submit" value="Register" /></div></div></div>
                }</div></div></div></div>
using System;
using System.Collections.Generic;
using System.Text;

namespace GOMLIB.Models
{
    public partial class Registration
    {        
        public int Registrationid { get; set; }
        public string Email { get; set; }
        public DateTime Createddate { get; set; }
    }
}

Thanks,

Shabbir

How to expose/Invoke c++ COM object/Methods in to .Net core Application?

$
0
0

In Dot net frame work I am able to use the same COM Dll By adding the DLL reference and by creating the object instance i am able to invoke COM Method.

BUT In Dot net core the Same COM Dll not Working. Please Suggest me Some best way to use the COM Dll In .net Core.

Automapper Doesnt map a navigation property

$
0
0

Hello guys,

I have a problem with Automapper in particolar with .projectTo that doesnt map the navigation property of attachments, following the code:

var messagesList = dataContext.EmailMessages
                                     .Include(em => em.FromAddresses)
                                     .Include(em => em.ToAddresses)
                                     .Include(em => em.CcAddresses)
                                     .Include(em => em.BccAddresses)
                                     .Include(em => em.Attachments).ThenInclude(at => at.ContentType)
                                     .Include(em => em.MessageFlags)
                                     .Include(em => em.ReplyTo)
                                     .Include(em => em.Uid)
                                     .Include(em => em.References)
                                     .Where(em => em.UserId == userId &&
                                            em.MessageDirection == EmailMessageDirection.received)
                                     .ProjectTo<EmailMessageDto>(new MapperConfiguration(cfg =>
                                     {
                                         cfg.CreateMap<EmailMessage, EmailMessageDto>();
                                         cfg.CreateMap<EmailContentType, EmailContentTypeDto>();
                                         cfg.CreateMap<EmailAttachment, EmailAttachmentDto>();
                                         cfg.CreateMap<EmailHeader, EmailHeaderDto>();
                                         cfg.CreateMap<EmailMessageFlag, EmailMessageFlagDto>();
                                         cfg.CreateMap<EmailUid, EmailUidDto>();
                                         cfg.CreateMap<EmailAddress, EmailAddressDto>();
                                         cfg.CreateMap<EmailMessageId, EmailMessageIdDto>();
                                     }))
                                     .OrderByDynamic(sortField, sortOrder.ToUpper());

When I get the IQueryable List the contentType is everitime null, if I check without Mapping ContentType is there.

I think the configuration of projectTo mapping is not good, some suggestion ?

Thankyou


JsonSerializer dont deserialize last deep of a class

$
0
0

Hi there I have following problem with JsonSerializer.Deserialize:

here the json string:

{"successful": true,"error": null,"content": {"pageIndex": 1,"totalPages": 32,"items": [
            {"toAddresses": [
                    {"id": 0,"name": "fidacrm@fidatek.cf","address": "fidacrm@fidatek.cf"
                    }
                ],"fromAddresses": [
                    {"id": 0,"name": "signodata gmail","address": "signodata@gmail.com"
                    }
                ],"bccAddresses": [],"ccAddresses": [],"replyTo": [],"attachments": [
                    {"id": 1,"fileName": "IMG_20170908_0001.pdf","fileNameUrl": null,"fileFullPath": null,"fileUrl": null,"contentType": {"id": 0,"format": null,"charset": null,"mediaSubtype": "pdf","mediaType": "application","mimeType": null,"name": "IMG_20170908_0001.pdf"
                        }
                    }
                ],"headers": [
                    {"id": 1,"rawField": "TUlNRS1WZXJzaW9u","headerId": 78,"field": "MIME-Version","offset": 3087,"rawValue": "IDEuMA0K","value": "1.0"
                    },
                    {"id": 32,"rawField": "RGVsaXZlcmVkLVRv","headerId": -1,"field": "Delivered-To","offset": 36,"rawValue": "IGZpZGFjcm1AZmlkYXRlay5jZg0K","value": "fidacrm@fidatek.cf"
                    },
                    {"id": 36,"rawField": "UmV0dXJuLVBhdGg=","headerId": 106,"field": "Return-Path","offset": 0,"rawValue": "IDxzaWdub2RhdGFAZ21haWwuY29tPg0K","value": "<signodata@gmail.com>"
                    },
                    {"id": 65,"rawField": "UmVjZWl2ZWQ=","headerId": 91,"field": "Received","offset": 70,"rawValue": "IGZyb20gc3Y3Ni5pZmFzdG5ldC5jb20NCglieSBzdjc2LmlmYXN0bmV0LmNvbSB3aXRoIExNVFANCglpZCBFQkNDSm4wUG4xN0QyaHNBSWNXSkVRDQoJKGVudmVsb3BlLWZyb20gPHNpZ25vZGF0YUBnbWFpbC5jb20+KQ0KCWZvciA8ZmlkYWNybUBmaWRhdGVrLmNmPjsgVHVlLCAyMSBBcHIgMjAyMCAxMToyMTozMyAtMDQwMA0K","value": "from sv76.ifastnet.com\tby sv76.ifastnet.com with LMTP\tid EBCCJn0Pn17D2hsAIcWJEQ\t(envelope-from <signodata@gmail.com>)\tfor <fidacrm@fidatek.cf>; Tue, 21 Apr 2020 11:21:33 -0400"
                    },
                    {"id": 79,"rawField": "RGVsaXZlcnktZGF0ZQ==","headerId": 47,"field": "Delivery-date","offset": 334,"rawValue": "IFR1ZSwgMjEgQXByIDIwMjAgMTE6MjE6MzMgLTA0MDANCg==","value": "Tue, 21 Apr 2020 11:21:33 -0400"
                    },
                    {"id": 94,"rawField": "UmVjZWl2ZWQ=","headerId": 91,"field": "Received","offset": 382,"rawValue": "IGZyb20gbWFpbC13bTEtZjUwLmdvb2dsZS5jb20gKFsyMDkuODUuMTI4LjUwXTozNjYyNSkNCglieSBzdjc2LmlmYXN0bmV0LmNvbSB3aXRoIGVzbXRwcyAgKFRMUzEuMikgdGxzIFRMU19FQ0RIRV9SU0FfV0lUSF9BRVNfMTI4X0dDTV9TSEEyNTYNCgkoRXhpbSA0LjkzKQ0KCShlbnZlbG9wZS1mcm9tIDxzaWdub2RhdGFAZ21haWwuY29tPikNCglpZCAxalF1aUwtMDA3ZjhHLTUwDQoJZm9yIGZpZGFjcm1AZmlkYXRlay5jZjsgVHVlLCAyMSBBcHIgMjAyMCAxMToyMTozMyAtMDQwMA0K","value": "from mail-wm1-f50.google.com ([209.85.128.50]:36625)\tby sv76.ifastnet.com with esmtps  (TLS1.2) tls TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\t(Exim 4.93)\t(envelope-from <signodata@gmail.com>)\tid 1jQuiL-007f8G-50\tfor fidacrm@fidatek.cf; Tue, 21 Apr 2020 11:21:33 -0400"
                    },
                    {"id": 114,"rawField": "UmV0dXJuLXBhdGg=","headerId": 106,"field": "Return-path","offset": 265,"rawValue": "IDxzaWdub2RhdGFAZ21haWwuY29tPg0K","value": "<signodata@gmail.com>"
                    },
                    {"id": 130,"rawField": "RW52ZWxvcGUtdG8=","headerId": -1,"field": "Envelope-to","offset": 301,"rawValue": "IGZpZGFjcm1AZmlkYXRlay5jZg0K","value": "fidacrm@fidatek.cf"
                    },
                    {"id": 269,"rawField": "VG8=","headerId": 116,"field": "To","offset": 2904,"rawValue": "IDxmaWRhY3JtQGZpZGF0ZWsuY2Y+DQo=","value": "<fidacrm@fidatek.cf>"
                    },
                    {"id": 285,"rawField": "UmVmZXJlbmNlcw==","headerId": 93,"field": "References","offset": 2930,"rawValue": "IA0K","value": ""
                    },
                    {"id": 304,"rawField": "UmVjZWl2ZWQ=","headerId": 91,"field": "Received","offset": 2536,"rawValue": "IGZyb20gcGllcmNhcmxvUEMgKG5ldC0yLTQ0LTEwNy0xMi5jdXN0LnZvZGFmb25lZHNsLml0LiBbMi40NC4xMDcuMTJdKQ0KICAgICAgICBieSBzbXRwLmdtYWlsLmNvbSB3aXRoIEVTTVRQU0EgaWQgdjE5c200MjQ2ODA4d3JhLjU3LjIwMjAuMDQuMjEuMDguMjEuMDMNCiAgICAgICAgZm9yIDxmaWRhY3JtQGZpZGF0ZWsuY2Y+DQogICAgICAgICh2ZXJzaW9uPVRMUzFfMiBjaXBoZXI9RUNESEUtRUNEU0EtQUVTMTI4LUdDTS1TSEEyNTYgYml0cz0xMjgvMTI4KTsNCiAgICAgICAgVHVlLCAyMSBBcHIgMjAyMCAwODoyMTowNCAtMDcwMCAoUERUKQ0K","value": "from piercarloPC (net-2-44-107-12.cust.vodafonedsl.it. [2.44.107.12])        by smtp.gmail.com with ESMTPSA id v19sm4246808wra.57.2020.04.21.08.21.03        for <fidacrm@fidatek.cf>        (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128);        Tue, 21 Apr 2020 08:21:04 -0700 (PDT)"
                    },
                    {"id": 319,"rawField": "RnJvbQ==","headerId": 59,"field": "From","offset": 2857,"rawValue": "ICJzaWdub2RhdGEgZ21haWwiIDxzaWdub2RhdGFAZ21haWwuY29tPg0K","value": "\"signodata gmail\" <signodata@gmail.com>"
                    },
                    {"id": 320,"rawField": "WC1NYWlsZXI=","headerId": 126,"field": "X-Mailer","offset": 3193,"rawValue": "IE1pY3Jvc29mdCBPdXRsb29rIDE2LjANCg==","value": "Microsoft Outlook 16.0"
                    },
                    {"id": 334,"rawField": "SW4tUmVwbHktVG8=","headerId": 64,"field": "In-Reply-To","offset": 2944,"rawValue": "IA0K","value": ""
                    },
                    {"id": 348,"rawField": "TWVzc2FnZS1JRA==","headerId": 77,"field": "Message-ID","offset": 3030,"rawValue": "IDwwMDM5MDFkNjE3ZjAkNzhkNDdkZjAkNmE3ZDc5ZDAkQGdtYWlsLmNvbT4NCg==","value": "<003901d617f0$78d47df0$6a7d79d0$@gmail.com>"
                    },
                    {"id": 366,"rawField": "RGF0ZQ==","headerId": 44,"field": "Date","offset": 2991,"rawValue": "IFR1ZSwgMjEgQXByIDIwMjAgMTc6MjE6MDMgKzAyMDANCg==","value": "Tue, 21 Apr 2020 17:21:03 +0200"
                    },
                    {"id": 398,"rawField": "U3ViamVjdA==","headerId": 113,"field": "Subject","offset": 2959,"rawValue": "IEk6IEludmlvIGNvbiBhbGxlZ2F0bw0K","value": "I: Invio con allegato"
                    },
                    {"id": 409,"rawField": "REtJTS1TaWduYXR1cmU=","headerId": 52,"field": "DKIM-Signature","offset": 810,"rawValue": "IHY9MTsgYT1yc2Etc2hhMjU2OyBjPXJlbGF4ZWQvcmVsYXhlZDsNCiAgICAgICAgZD1nbWFpbC5jb207IHM9MjAxNjEwMjU7DQogICAgICAgIGg9ZnJvbTp0bzpyZWZlcmVuY2VzOmluLXJlcGx5LXRvOnN1YmplY3Q6ZGF0ZTptZXNzYWdlLWlkOm1pbWUtdmVyc2lvbg0KICAgICAgICAgOnRocmVhZC1pbmRleDpjb250ZW50LWxhbmd1YWdlOw0KICAgICAgICBiaD1Pa2EwL25KR0t0MkNKUTVtNW9oMENmSUFlZWdhSTkzVWtSMi9MWlYyU0hRPTsNCiAgICAgICAgYj1LRUpKbCtZVkk3TFRJSUJweFp5VXZXR1FIVzQwZlNvaklvQjNPZDh6bmFPRmtkYnJ4OTltcHB3Yzlha0d4VE1PbXMNCiAgICAgICAgIFBuNGJxNENjeTR5eGhPRWtneWVtRTV4VmZ5NEdBMEZBRUQ3Sy9aMnFrRUl0emNZSm1oclZ3T1JCeklnSUI1Z2l4aG4rDQogICAgICAgICBRcTVrK09SMnZnWnVYNXNYRzFGeEJEZEg0TEwxRms5L0t1VWVEZkNReWNLZnU5bzVaZWhWUTdVWXNXUCtjdXloZnZNMA0KICAgICAgICAgVEkyZXYySHdnTFF4TTM4K2xWWUJqSEw1R2JQNU5aZ1FOK0tyRFZYYlk0aGpoV0VjVG1sRXg0SE9VcFYzUzYzVytFaWMNCiAgICAgICAgIE1vTE1BY0xySzEzUGZIc1NjangvTDg2c1RaYlR3QTFQTXJGUHg2SVNacXZTTEJOUDgwWnBEUWx5ZFRDZ3d2Y05wVDNDDQogICAgICAgICAzRG13PT0NCg==","value": "v=1; a=rsa-sha256; c=relaxed/relaxed;        d=gmail.com; s=20161025;        h=from:to:references:in-reply-to:subject:date:message-id:mime-version         :thread-index:content-language;        bh=Oka0/nJGKt2CJQ5m5oh0CfIAeegaI93UkR2/LZV2SHQ=;        b=KEJJl+YVI7LTIIBpxZyUvWGQHW40fSojIoB3Od8znaOFkdbrx99mppwc9akGxTMOms         Pn4bq4Ccy4yxhOEkgyemE5xVfy4GA0FAED7K/Z2qkEItzcYJmhrVwORBzIgIB5gixhn+         Qq5k+OR2vgZuX5sXG1FxBDdH4LL1Fk9/KuUeDfCQycKfu9o5ZehVQ7UYsWP+cuyhfvM0         TI2ev2HwgLQxM38+lVYBjHL5GbP5NZgQN+KrDVXbY4hjhWEcTmlEx4HOUpV3S63W+Eic         MoLMAcLrK13PfHsScjx/L86sTZbTwA1PMrFPx6ISZqvSLBNP80ZpDQlydTCgwvcNpT3C         3Dmw=="
                    },
                    {"id": 444,"rawField": "VGhyZWFkLUluZGV4","headerId": -1,"field": "Thread-Index","offset": 3227,"rawValue": "IEFkWVg2YTJVSTFMekI3eU1Rc0N4dXlnRmdZV0hJQUFBVFNZUUFBQ3RwTUFBQURwaWdBQUFlOWFBDQo=","value": "AdYX6a2UI1LzB7yMQsCxuygFgYWHIAAATSYQAACtpMAAADpigAAAe9aA"
                    },
                    {"id": 459,"rawField": "UmVjZWl2ZWQ=","headerId": 91,"field": "Received","offset": 667,"rawValue": "IGJ5IG1haWwtd20xLWY1MC5nb29nbGUuY29tIHdpdGggU01UUCBpZCB1MTI3c280MTUyNTgwd21nLjENCiAgICAgICAgZm9yIDxmaWRhY3JtQGZpZGF0ZWsuY2Y+OyBUdWUsIDIxIEFwciAyMDIwIDA4OjIxOjA3IC0wNzAwIChQRFQpDQo=","value": "by mail-wm1-f50.google.com with SMTP id u127so4152580wmg.1        for <fidacrm@fidatek.cf>; Tue, 21 Apr 2020 08:21:07 -0700 (PDT)"
                    },
                    {"id": 466,"rawField": "WC1Hb29nbGUtREtJTS1TaWduYXR1cmU=","headerId": -1,"field": "X-Google-DKIM-Signature","offset": 1489,"rawValue": "IHY9MTsgYT1yc2Etc2hhMjU2OyBjPXJlbGF4ZWQvcmVsYXhlZDsNCiAgICAgICAgZD0xZTEwMC5uZXQ7IHM9MjAxNjEwMjU7DQogICAgICAgIGg9eC1nbS1tZXNzYWdlLXN0YXRlOmZyb206dG86cmVmZXJlbmNlczppbi1yZXBseS10bzpzdWJqZWN0OmRhdGUNCiAgICAgICAgIDptZXNzYWdlLWlkOm1pbWUtdmVyc2lvbjp0aHJlYWQtaW5kZXg6Y29udGVudC1sYW5ndWFnZTsNCiAgICAgICAgYmg9T2thMC9uSkdLdDJDSlE1bTVvaDBDZklBZWVnYUk5M1VrUjIvTFpWMlNIUT07DQogICAgICAgIGI9cVlQQnFSeE5TK2szcnJuMjFjalJtOWJMSTlsRU9ka3AyTnRibFVIbkh3SGtYSTdyamtialJaTENxNVpoMjBaOTVmDQogICAgICAgICBjYWhiVGlxVjRkc0pGWjlWaW9MZE1QK0g2blN2M24xdVhRVHMvdkZTTk8zZXV3VTVqalVVdTF6MXhGNkJ1NUxkcEdLYw0KICAgICAgICAgdUhHb0R2L0tUajdaVW9DSEpPQ2gyMk9QbmpqMkRpc016MXZXT3lDTUYxb3lXQm1aM25oWEtLMVBic3hOVXRxOFJKTk4NCiAgICAgICAgIDRZMWU3ZTFZYWJkZi9MOUJjcGRBUmY2dnNvQU1DSGl6bU1BUEZiN0lBT3NKMk1DRERETGlnYUJRR3dwM2dES0hWN2RUDQogICAgICAgICBQZmExT0lWMi9BTVI4aThLSlVBRWpqakNoZVFtK2gyd05MKzVRVHBheGpILzd5eEV5YU9GZTFoK05aR1dEWWlBWEw5cQ0KICAgICAgICAgY0NXdz09DQo=","value": "v=1; a=rsa-sha256; c=relaxed/relaxed;        d=1e100.net; s=20161025;        h=x-gm-message-state:from:to:references:in-reply-to:subject:date         :message-id:mime-version:thread-index:content-language;        bh=Oka0/nJGKt2CJQ5m5oh0CfIAeegaI93UkR2/LZV2SHQ=;        b=qYPBqRxNS+k3rrn21cjRm9bLI9lEOdkp2NtblUHnHwHkXI7rjkbjRZLCq5Zh20Z95f         cahbTiqV4dsJFZ9VioLdMP+H6nSv3n1uXQTs/vFSNO3euwU5jjUUu1z1xF6Bu5LdpGKc         uHGoDv/KTj7ZUoCHJOCh22OPnjj2DisMz1vWOyCMF1oyWBmZ3nhXKK1PbsxNUtq8RJNN         4Y1e7e1Yabdf/L9BcpdARf6vsoAMCHizmMAPFb7IAOsJ2MCDDDLigaBQGwp3gDKHV7dT         Pfa1OIV2/AMR8i8KJUAEjjjCheQm+h2wNL+5QTpaxjH/7yxEyaOFe1h+NZGWDYiAXL9q         cCWw=="
                    },
                    {"id": 469,"rawField": "WC1Hb29nbGUtU210cC1Tb3VyY2U=","headerId": -1,"field": "X-Google-Smtp-Source","offset": 2305,"rawValue": "IEFQaVF5cEpDVDg2am1MbFJKaVNhdE0rTGU0eGg2MTkwRHh1WWI4ZGtuUlZVL0lEMkJ1SUpVL3pWWVgzY3J5VHY2QUtMWllWY2trcE5EQT09DQo=","value": "APiQypJCT86jmLlRJiSatM+Le4xh6190DxuYb8dknRVU/ID2BuIJU/zVYX3cryTv6AKLZYVckkpNDA=="
                    },
                    {"id": 485,"rawField": "WC1SZWNlaXZlZA==","headerId": -1,"field": "X-Received","offset": 2409,"rawValue": "IGJ5IDIwMDI6YTFjOjllNTE6OiB3aXRoIFNNVFAgaWQgaDc4bXI1ODYzMDIwd21lLjE3Ny4xNTg3NDgyNDY1ODc4Ow0KICAgICAgICBUdWUsIDIxIEFwciAyMDIwIDA4OjIxOjA1IC0wNzAwIChQRFQpDQo=","value": "by 2002:a1c:9e51:: with SMTP id h78mr5863020wme.177.1587482465878;        Tue, 21 Apr 2020 08:21:05 -0700 (PDT)"
                    },
                    {"id": 501,"rawField": "WC1HbS1NZXNzYWdlLVN0YXRl","headerId": -1,"field": "X-Gm-Message-State","offset": 2196,"rawValue": "IEFHaTBQdVozUGN5akx5d0Rjb2NVeXo3V09oZG5weDFFeVh4eGg1TnQ3SitITGJvdHJZRXM1TGZjDQoJYUo1VUNJbmZzdHl2dGZaZE81eGIwcC9EWXFyMg0K","value": "AGi0PuZ3PcyjLywDcocUyz7WOhdnpx1EyXxxh5Nt7J+HLbotrYEs5Lfc\taJ5UCInfstyvtfZdO5xb0p/DYqr2"
                    }
                ],"references": [],"messageFlags": [
                    {"id": 5,"messageFlag": 5
                    }
                ],"id": 15,"messageId": "003901d617f0$78d47df0$6a7d79d0$@gmail.com","uid": {"id": 15,"uidId": 32,"validity": 1567921962,"isValid": true
                },"date": "2020-04-21T17:21:03+02:00","importance": 1,"priority": 1,"subject": "I: Invio con allegato","body": "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">\r\n<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta name=Generator content=\"Microsoft Word 15 (filtered medium)\"><style><!--\r\n/* Font Definitions */\r\n@font-face\r\n\t{font-family:\"Cambria Math\";\r\n\tpanose-1:2 4 5 3 5 4 6 3 2 4;}\r\n@font-face\r\n\t{font-family:Calibri;\r\n\tpanose-1:2 15 5 2 2 2 4 3 2 4;}\r\n/* Style Definitions */\r\np.MsoNormal, li.MsoNormal, div.MsoNormal\r\n\t{margin:0cm;\r\n\tmargin-bottom:.0001pt;\r\n\tfont-size:11.0pt;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tmso-fareast-language:EN-US;}\r\na:link, span.MsoHyperlink\r\n\t{mso-style-priority:99;\r\n\tcolor:blue;\r\n\ttext-decoration:underline;}\r\nspan.StileMessaggioDiPostaElettronica20\r\n\t{mso-style-type:personal-reply;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tcolor:windowtext;}\r\n.MsoChpDefault\r\n\t{mso-style-type:export-only;\r\n\tfont-size:10.0pt;}\r\n@page WordSection1\r\n\t{size:612.0pt 792.0pt;\r\n\tmargin:70.85pt 2.0cm 2.0cm 2.0cm;}\r\ndiv.WordSection1\r\n\t{page:WordSection1;}\r\n--></style><!--[if gte mso 9]><xml>\r\n<o:shapedefaults v:ext=\"edit\" spidmax=\"1026\" />\r\n</xml><![endif]--><!--[if gte mso 9]><xml>\r\n<o:shapelayout v:ext=\"edit\">\r\n<o:idmap v:ext=\"edit\" data=\"1\" />\r\n</o:shapelayout></xml><![endif]--></head><body lang=IT link=blue vlink=purple><div class=WordSection1><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal><o:p>&nbsp;</o:p></p><div><div style='border:none;border-top:solid #E1E1E1 1.0pt;padding:3.0pt 0cm 0cm 0cm'><p class=MsoNormal><b><span style='mso-fareast-language:IT'>Da:</span></b><span style='mso-fareast-language:IT'> signodata gmail &lt;signodata@gmail.com&gt; <br><b>Inviato:</b> martedì 21 aprile 2020 17:07<br><b>A:</b> 'fidacrm@fidatek.cf' &lt;fidacrm@fidatek.cf&gt;<br><b>Oggetto:</b> I: Invio con allegato<o:p></o:p></span></p></div></div><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal><o:p>&nbsp;</o:p></p><div><div style='border:none;border-top:solid #E1E1E1 1.0pt;padding:3.0pt 0cm 0cm 0cm'><p class=MsoNormal><b><span style='mso-fareast-language:IT'>Da:</span></b><span style='mso-fareast-language:IT'> signodata gmail &lt;<a href=\"mailto:signodata@gmail.com\">signodata@gmail.com</a>&gt; <br><b>Inviato:</b> martedì 21 aprile 2020 17:01<br><b>A:</b> 'fidacrm@fidatek.cf' &lt;<a href=\"mailto:fidacrm@fidatek.cf\">fidacrm@fidatek.cf</a>&gt;<br><b>Oggetto:</b> I: Invio con allegato<o:p></o:p></span></p></div></div><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal><o:p>&nbsp;</o:p></p><div><div style='border:none;border-top:solid #E1E1E1 1.0pt;padding:3.0pt 0cm 0cm 0cm'><p class=MsoNormal><b><span style='mso-fareast-language:IT'>Da:</span></b><span style='mso-fareast-language:IT'> signodata gmail &lt;<a href=\"mailto:signodata@gmail.com\">signodata@gmail.com</a>&gt; <br><b>Inviato:</b> martedì 21 aprile 2020 16:41<br><b>A:</b> 'fidacrm@fidatek.cf' &lt;<a href=\"mailto:fidacrm@fidatek.cf\">fidacrm@fidatek.cf</a>&gt;<br><b>Oggetto:</b> I: Invio con allegato<o:p></o:p></span></p></div></div><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal><o:p>&nbsp;</o:p></p><div><div style='border:none;border-top:solid #E1E1E1 1.0pt;padding:3.0pt 0cm 0cm 0cm'><p class=MsoNormal><b><span style='mso-fareast-language:IT'>Da:</span></b><span style='mso-fareast-language:IT'> signodata gmail &lt;<a href=\"mailto:signodata@gmail.com\">signodata@gmail.com</a>&gt; <br><b>Inviato:</b> martedì 21 aprile 2020 16:33<br><b>A:</b> 'fidacrm@fidatek.cf' &lt;<a href=\"mailto:fidacrm@fidatek.cf\">fidacrm@fidatek.cf</a>&gt;<br><b>Oggetto:</b> Invio con allegato<o:p></o:p></span></p></div></div><p class=MsoNormal><o:p>&nbsp;</o:p></p><p class=MsoNormal>Invio con allegato in pdf.<o:p></o:p></p></div></body></html>","isHtml": true,"needReadReceipt": false,"needDeliveredReceipt": false,"inReplyTo": null,"sender": null,"messageDirection": 1
            }
        ],"hasPreviousPage": false,"hasNextPage": true
    }
}

here the code to deserialize:

            var res = await http.GetFromJsonAsync<ApiResult>("api/Email/GetUserInBoxEmails/1/Date/Desc/10/" + auth.CurrentUserId);
            if (res.Successful)
            {
                PaginatedMessages = JsonSerializer.Deserialize<PaginatedList<EmailMessageDto>>(res.Content.ToString(), options);
}

here the calss that dont deserialize:

namespace FidaBlazorUI_Share.Models.Email.ModelDto
{
    public class EmailAttachmentDto
    {
        public EmailAttachmentDto()
        {

        }
        public EmailAttachmentDto(EmailAttachment attachment)
        {
            Id = attachment.Id;
            FileName = attachment.FileName;
            FileNameUrl = attachment.FileNameUrl;
            FileFullPath = attachment.FileFullPath;
            FileUrl = attachment.FileUrl;
            ContentType = new EmailContentTypeDto(attachment.ContentType);
        }

        public int Id { get; set; }
        public string FileName { get; internal set; }
        public string FileNameUrl { get; internal set; }
        public string FileFullPath { get; internal set; }
        public string FileUrl { get; internal set; }
        public EmailContentTypeDto ContentType { get; }
    }
}

and the ContentType clas that don´t want to deserialize:

namespace FidaBlazorUI_Share.Models.Email.ModelDto
{
    public class EmailContentTypeDto
    {
        public EmailContentTypeDto()
        {

        }
        public EmailContentTypeDto(EmailContentType contentType)
        {
            Format = contentType.Format;
            Charset = contentType.Charset;
            MediaSubtype = contentType.MediaSubtype;
            MediaType = contentType.MediaType;
            MimeType = contentType.MimeType;
            Name = contentType.Name;
        }

        public int Id { get; set; }
        public string Format { get; set; }
        public string Charset { get; set; }
        public string MediaSubtype { get; set; }
        public string MediaType { get; set; }
        public string MimeType { get; }
        public string Name { get; set; }
    }
}

So the problem that on deserialization I get all deserialized except the Attachment Content Type that is sull when in the Json there is.

Thank You for help

Problem for using Asp.net c# and html mixing code

$
0
0

I tried to use below code in asp.net but there is error in html tags like and and say it could not find begin tag. but begin tag is in first if. the errors are in between line 44 to 52.

@{string n ="";int j =0;foreach(var item inModel.RelatedProduct){if(item.ProductId!= n)
                j =1;else
                j =0;if(j==1){<div class="modal fade" id="myModal" role="dialog"><div class="modal-dialog modal-dialog-centered " role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">@item.CatalogDescription</h5><button class="close" type="button" data-dismiss="modal"><span aria-hidden="true">&times;</span></button></div><div class="modal-body"><table class="table table-hover"><thead class="thead-dark"><tr><td>Customer</td></tr>}@if(j ==1|| j ==0){<tr><td>@item.CustomerName</td><td>@item.Price</td></tr>}@if(j==1){</table></div><div class="modal-footer"><button class="btn" data-dismiss="modal">Cancel</button></div></div></div></div>}}}

.net Core upload File by WebClient FTP

$
0
0

Hi all,

So, I'm trying to upload a file from my client pc to my webserver using a .net core web API. This works fine when I run the web service locally (meaning that the source file and the service are running on the same machine). But when I run the .net core api on my webserver, it cannot find my client computer's local file despite it being fully spelled out. I understand that the API is looking for the file on the webserver at that point, but I'm trying to figure out how to get the webserver to look on my client computer to upload the file when I give it a path. 

Here is my code as it stands. Again, there is no problem writing to the server, only in finding the client computer's file.

  string fileLocation = @"C:\Temp\Test.txt";
            string fileDestination = "ftp://aaa.com//Test//Test.txt";

            try
            {
                // AsynchronousFtpUpLoader.Upload(fileDestination, fileLocation, ftpUserName,  ftpPassword);

               
                string To = "ftp://MyIPGoesHere/directory/Test.txt";
using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(ftpUserName, ftpPassword); client.UploadFile(fileDestination, WebRequestMethods.Ftp.UploadFile, fileLocation); } } catch (Exception ex) { return BadRequest(new { message = ex.Message + " : " + ex.InnerException }); }

The error I get is "

An exception occurred during a WebClient request. : System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\\Temp\\Test.txt'.\r\n 

I've seen a lot of posts about this, but never seem to find a clear solution. So I'm sorry if this has been answered elsewhere simply. 

Thanks in advance!
 

Problem with Session when getting string data to the action of controller

$
0
0

Hi guys,

As some of you knows, I'm developing a quiz application. I have timer in question view and this time I need to get the time between opening the question view and submitting the answer. Then I substruct that interval from 60 in order to get remained seconds which will be the point of the question if the answer is right.  Here is the details:

View

@model Intellect.Models.ViewModels.AdminViewModel<div class="questioncontainer">        <form asp-action="Question" asp-controller="Home" asp-route-id="@Model.NextQuestion.Id" asp-route-count="@ViewBag.Equestions"><div class="row"><div class="col-lg-3"></div><div class="col-lg-6 col-sm-12"><table><tr><th>Qaliq vaxt</th></tr><tr><td><div id="time"></div> </td></tr></table><div class="question">@Model.CurrentQuestion.Description </div></div><div class="col-lg-3"></div></div><div class="row"><div class="col-lg-3 col-sm-0"></div>
                @{
                    int n = 0;
                }
                @foreach (Answer item in Model.Answers)
                {
                    if (n == 0 || n == 2)
                    {
                        @: <div class="col-lg-3 col-sm-12">
                            @: <div class="firstpart">
                            }<input asp-for="@item.Id" name="@item.Id" hidden /><input type="radio" asp-for="@item.Id" name="myanswer" value="@item.Id" />@item.Description<br>
                            if (n == 1 || n == 3)
                            {
                            @:</div>
                        @:</div>
                    }

                    n++;
                }<div class="col-lg-3"></div></div><div class="row"><div class="col-lg-6 col-sm-4"></div><div class="col-lg-3 col-sm-4"></div><div class="col-lg-3 col-sm-4"><div class="nextbtn">
                        @if (ViewBag.Equestions == 0)
                        {<input type="submit" value="Finish" />
                        }
                        else
                        {<input type="submit" value="Next" />
                        }</div></div></div></form></div>

@section Script{ 
    <script>
        function StartTimer(seconds) {
            var intSeconds = seconds;
            var timer = setInterval(myTimer, 1000);
            function myTimer() {
                if (intSeconds < 0) {
                    Alert("bitdi")
                    clearInterval(timer)
                    return;
                }
                document.getElementById("time").innerText = intSeconds;
                intSeconds--;
            }
        }
        StartTimer(60);</script>
}

Controller

 public class HomeController : Controller
    {
        private readonly IntellectDbContext _intellectDbContext;
        private readonly UserManager<ExamUser> _userManager;
        private readonly SignInManager<ExamUser> _signInManager;
        static int exam_id = 0;
        static int? PreviousId = 0;
        static int result = 0;
        static int correctAnswer = 0;
        static List<Question> RemainedQuestions = new List<Question>();
        static List<int> trueAnswers = new List<int>();

        public HomeController(IntellectDbContext intellectDbContext, UserManager<ExamUser> userManager, SignInManager<ExamUser> signInManager)
        {
            _intellectDbContext = intellectDbContext;
            _userManager = userManager;
            _signInManager = signInManager;
        }
        [HttpGet]
        public async Task<IActionResult> Test(int Id)
        {
            exam_id = Id;
            AdminViewModel admodel = new AdminViewModel();
            admodel.Equestions = await _intellectDbContext.Questions.Include(q => q.Answers).Where(q => q.ExamId == Id).ToListAsync();
            admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(q => q.ExamId == Id).FirstOrDefaultAsync();
            RemainedQuestions = admodel.Equestions;
            PreviousId = admodel.CurrentQuestion.Id;
            return View(admodel);
        }


        [HttpGet]
        public async Task<IActionResult> Question(int Id, int count)
        {
            AdminViewModel admodel = new AdminViewModel();
            admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(x => x.Id == Id).SingleOrDefaultAsync();
            admodel.Answers = await _intellectDbContext.Answers.Where(y => y.QuestionId == Id).ToListAsync();
            admodel.Equestions = await _intellectDbContext.Questions.Where(q => q.ExamId == exam_id).ToListAsync();

            // admodel.CurrentQuestion.Remainedtime = new TimeSpan(0, 0, 60);
            HttpContext.Session.SetString("currentQuestion_" + admodel.CurrentQuestion.Id, DateTime.Now.ToString());


            if (count > 1)
            {
                var question = RemainedQuestions.Single(r => r.Id == admodel.CurrentQuestion.Id);
                PreviousId = question.Id;
                RemainedQuestions.Remove(question);
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }
            else
            {
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }

            if (count == -1)
            {
                return RedirectToAction(nameof(Finish));
            }

            ViewBag.Equestions = count;

            return View(admodel);
        }

        [HttpPost]
        public async Task<IActionResult> Question(int Id, int count, int myanswer)
        {
            AdminViewModel admodel = new AdminViewModel();
            admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(x => x.Id == Id).SingleOrDefaultAsync();
            admodel.Answers = await _intellectDbContext.Answers.Where(y => y.QuestionId == Id).ToListAsync();
            admodel.Equestions = await _intellectDbContext.Questions.Where(q => q.ExamId == exam_id).ToListAsync();

            //  admodel.CurrentQuestion.Remainedtime = new TimeSpan(0, 0, 60);
           // HttpContext.Session.SetString("currentQuestion_" + admodel.CurrentQuestion.Id, DateTime.Now.ToString());
            var interval = DateTime.Now - DateTime.Parse(HttpContext.Session.GetString("currentQuestion_" + Id));

            correctAnswer = _intellectDbContext.Answers.Where(a => a.QuestionId == PreviousId && a.Correct == true).SingleOrDefault().Id;

            if (_signInManager.IsSignedIn(User))
            {
                ExamUser examTaker = await _userManager.GetUserAsync(HttpContext.User);

                examTaker.TestTaker = await _intellectDbContext.TestTakers
                                               .Include(tt => tt.UserQuestions) 
                                               .Where(t => t.Id == examTaker.TestTakerId) 
                                               .FirstOrDefaultAsync();
                admodel.CurrentQuestion = examTaker.TestTaker.UserQuestions.Select(u => u.Question).Where(x => x.Id == Id).SingleOrDefault();
                if (myanswer == correctAnswer)
                {
                    admodel.CurrentQuestion.Score = 60 - (int)interval.TotalMilliseconds / 1000;
                    await _intellectDbContext.SaveChangesAsync();
                    // admodel.CurrentQuestion.Score = result;
                }
            }
                if (count > 1)
            {
                var question = RemainedQuestions.Single(r => r.Id == admodel.CurrentQuestion.Id);
                PreviousId = question.Id;
                RemainedQuestions.Remove(question);
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }
            else
            {
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }

            if(count == -1)
            {
                return RedirectToAction(nameof(Finish));
            }

            ViewBag.Equestions = count;

            return RedirectToAction(nameof(Question));
        }
     }

When I run the application, the following errors comes (refer to link) when clicking on Next to get to the next question view:  https://prnt.sc/s6y9vy

As you see, action (Question) in controller cannot get string data from session to parse it. 

The problem lies here:        var interval = DateTime.Now - DateTime.Parse(HttpContext.Session.GetString("currentQuestion_" + Id));

Please, assist in solving this issue. 

How to set variable scope to the browser in asp.net core web api?

$
0
0

Hi

I want to create variable and make its scope to the browser so every user enter my asp.net core web api through his own browser sets the variable as he needs. i tried to use the static variable but it lives in the scope of the program lifetime and when user sets the variable and other user sets the same variable the previous user sees the value of the variable being set by the other user which is big problem i want every user sets the variable for his own and the variable being reset as he leave the website or close the browser tap or the browser itself.

Iam using asp.net core web api 3.1

Viewing all 9386 articles
Browse latest View live


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