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

Oracle connectivity issue for asp.net core 2.1 web api from docker container

$
0
0
Hi All,
I am trying to connect oracle database using Oracle.ManagedDataAccess.Core 2.18.3 ; i am using asp.net core 2.1 web api. When i run this code on my local machin it works fine but when dockerised it and deployed it under container it fails with below error

ORA-00604 : error occured at recursive SQL level 1
ORA-01882 : timezone region not found

I searched on internet and found below solutions but both of them are not working for me ; Please help asap.

1. Set timezone in docket file as below
ENV TZ=America/New_York
2. Also setup timezone to open oracle connection as below
Oracle globalization info = con.GetSession();
info.TimeZone = "America/New_York";
con.SetSessionInfo(info);


Please help

Modify the Request Body with Middleware

$
0
0

I found a lot of information on the web about how to modify response content, but is it possible to modify therequest body on the way in with middleware? Can I replace the body with my own version and then send it on to the later middleware components?

Thank You

How can I use globalization and localization in .net core 3.0 preview8?

$
0
0

I used globalization and localization in .net core 2.2 yet and now wanna migrate it to .net core 3.0 preview8.

Here is my code in .net core 2.2:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
//app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHttpsRedirection();
}

var SupportedCultures = new List<CultureInfo> {
new CultureInfo("en"),
new CultureInfo("zh-Hans"),
new CultureInfo("zh-Hant")
};
var options = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en"),
SupportedCultures = SupportedCultures,
SupportedUICultures = SupportedCultures
};
app.UseRequestLocalization(options);
app.UseStaticFiles();

app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");


var requestProvider = new RouteDataRequestCultureProvider();
options.RequestCultureProviders.Insert(0, requestProvider);

app.UseRouter(routes =>
{
routes.MapMiddlewareRoute("{culture=en}/{*mvcRoute}", subApp =>
{
subApp.UseRequestLocalization(options);

subApp.UseMvc(mvcRoutes =>
{
mvcRoutes.MapRoute(
name: "default",
template: "{culture=en}/{controller=Home}/{action=Index}");
// map the .html suffix
mvcRoutes.MapRoute(
name: "home.html",
template: "{culture=en}/{controller=Home}/{action}.html");
});
});
});
}

And here is my code in .net core 3.0

[Obsolete]
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHttpsRedirection();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

var SupportedCultures = new List<CultureInfo> {
new CultureInfo("en"),
new CultureInfo("zh-Hans"),
new CultureInfo("zh-Hant")
};
var options = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("zh-Hans"),
SupportedCultures = SupportedCultures,
SupportedUICultures = SupportedCultures
};
app.UseRequestLocalization(options);
var requestProvider = new RouteDataRequestCultureProvider();
options.RequestCultureProviders.Insert(0, requestProvider);
app.UseStaticFiles();

app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");

app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{culture=zh-hans}/{controller=Home}/{action=Index}");
endpoints.MapControllerRoute(
name: "html",
pattern: "{culture=zh-hans}/{controller=Home}/{action}.html");

});

}

The MVC Controller and any other things change a lot and I don't know how to migrate it.

Now the problem is the default language of globalization and localization is 'zh-hans' but not in .net core 3.0 is English. What's more, it seems the globalization and localization do not work also.

The code I wrote before is for changing the globalization and localization by URL, for example, www.microsoft.com/en/ for English,www.microsoft.com/zh-hans for Chinese.

How can I solve it? Would you please help me? Thank you.

are there any free Rich text editor for razor pages

Rich text editor not working on razor pages but works on plain html pages

$
0
0

Hi guys

I found a free Rich text editor here https://summernote.org/getting-started/#without-bootstrap

which works with plain html pages, and there is a bootstrap v4 version which does not seem to work in my razor pages, as I added the cdn links on the razor pages and tried adding also in the layout pages, but neither works

here is my code (with 2 options below)

OPTION 1- keep every script in my layout page (Added scripts are in yellow) I already have bootstrap 4, so just added boostrap.js and the external scripts

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>@ViewData["Title"] - Xxxh</title><environment include="Development"><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /><link href="~/lib/x/css/main.css" rel="stylesheet" /><script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha384-xBuQ/xzmlsLoJpy akNTNrHIW2I5f" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote-bs4.css" rel="stylesheet"><script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote-bs4.js"></script><script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script><script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script><script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script></environment></head><body><main role="main" class="pb-3">
            @RenderBody()</main></div><footer class="border-top footer text-muted"><div class="container"><partial name="_CookieConsentPartial" />&copy; 2019 - X - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> | <a asp-area="" asp-controller="Home" asp-action="Support">Support</a> | <a asp-area="" asp-controller="Home" asp-action="Affiliates">Affiliates & Resellers</a></div></footer><environment include="Development"><script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script></environment><environment exclude="Development"><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha256-FgpCb/KJQ RdAu8="></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-xrR8PRhcEn3czEjhAO9o"></script></environment><script src="~/js/site.js" asp-append-version="true"></script>

    @RenderSection("Scripts", required: false)</body></html>
my razor page is below

@section scripts { }<script>$(document).ready(function () {$('#summernote').summernote({ placeholder: 'Hello stand alone ui', tabsize: 2, height: 100 }); </script> }); } <h1>Editor</h1><!DOCTYPE html><div id="summernote"></div>

OPTION 2 - Add my scripts to my razor page and not layout page

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>@ViewData["Title"] - Xxxh</title><environment include="Development"><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /><link href="~/lib/x/css/main.css" rel="stylesheet" /><script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha384-xBuQ/xzmlsLoJpy akNTNrHIW2I5f" crossorigin="anonymous"></script><script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script><script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script><script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script></environment></head><body><main role="main" class="pb-3">
            @RenderBody()</main></div><footer class="border-top footer text-muted"><div class="container"><partial name="_CookieConsentPartial" />&copy; 2019 - X - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> | <a asp-area="" asp-controller="Home" asp-action="Support">Support</a> | <a asp-area="" asp-controller="Home" asp-action="Affiliates">Affiliates & Resellers</a></div></footer><environment include="Development"><script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script></environment><environment exclude="Development"><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha256-FgpCb/KJQ RdAu8="></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-xrR8PRhcEn3czEjhAO9o"></script></environment><script src="~/js/site.js" asp-append-version="true"></script>

    @RenderSection("Scripts", required: false)</body></html>


add the external Rich text editor scripts to my razor page

@section scripts
{
///I removed the boostrap duplicate which exisit in the layout page above<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote-bs4.css" rel="stylesheet"><script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote-bs4.js"></script><script>$(document).ready(function () {$('#summernote').summernote({
placeholder: 'Hello stand alone ui',
tabsize: 2,
height: 100


});
</script>
});

}
<h1>Editor</h1><!DOCTYPE html><div id="summernote"></div>

this is a working plain html page

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>bootstrap4</title><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote-bs4.css" rel="stylesheet"><script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote-bs4.js"></script></head><body><div id="summernote"></div><script>$('#summernote').summernote({
        placeholder: 'Hello bootstrap 4',
        tabsize: 2,
        height: 100
      });</script></body></html>

How to set IdentityOptions Dynamically from database

$
0
0

how to set IdentityOptions Dynamically from database asp.net core 2?

I can set it statically

services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true; 
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;

// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);

options.Lockout.MaxFailedAccessAttempts = 2;
options.Lockout.AllowedForNewUsers = true;

// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = true;
});

But I wanna configure it from database. I have some columns about that.

var staticSetting = _unitOfWork.StaticSettings.GetAll().FirstOrDefault();
staticSetting.RequireDigit
staticSetting.RequireLowercase
staticSetting.RequireNonAlphanumeric
staticSetting.RequireUppercase 
staticSetting.RequiredLength 
staticSetting.RequiredUniqueChars 
staticSetting.DefaultLockoutTimeSpanFromMinutes
staticSetting.MaxFailedAccessAttempts
staticSetting.AllowedForNewUsers

how and where can I set it from database?

Reject/Accept Method and Header

$
0
0

I am at a lost as to how to reject or accept specific methods and header from asp.net core 2.2.  For example, I would only want post and get method with a custom header like "X-MYAPP-Version" 

All the examples are related to CORS but none on non cross site access.   Thank you.

How can I get information from the callback?

$
0
0

Hello, I am a beginner and now I need to achieve a sign-in into the website by a third-party account(such as sign-in by google+) with OAuth2.0.

Firstly, it will redirect to the third-party website to input the username and password.

When the username and the password are correct, it will send a callback to my website(if my website iswww.microsoft.com, it will send https://www.microsoft.con/callback?code=123&state=test)

Now the problem is how can my website get the callback at once when it sends and soon gets the information from it.

Thank you.


launch app with .net core

$
0
0

hi

i want to launch app on android or ios by click button on asp.net core...

How to use GridView functionality in DotNet Core

$
0
0

Coming from a ASP.NET background, we are migrating a large application from ASP.NET to DotNet Core. One of the main obstacles is the lack of 'GridView'. The previous application makes heavy use of a GridView allowing inline editing where the users can edit a row directly. More importantly, some of the screens allow users to submit all GridView Rows for bulk update. Row editing and bulk processing of rows in asp.net is a trivial task but achieving similar functionality in dotnet core is a headache for us. Can someone shed light on this. Thanks in advance.

Asp.NET Core Toasttr Problem

$
0
0

Hi everyone,

I am using .net core mvc. I want to do when I click button show message "Data İnsert". But doesnt working. I am shared code.

 Layout.cshtml

@if (TempData["mesaj"] != null)
  {<script type="text/javascript">
          (function () { toastr.info('Data Create'); })();</script>
}

Controller

public IActionResult ProjectAdd(int katid, string icerik, string baslik, IFormFile resimyolu)
      {
          using (Portfolios port = new Portfolios())
          {
              TProjects proje = new TProjects();
              if (resimyolu != null)
              {
                  var path = Path.Combine(
                   Directory.GetCurrentDirectory(), "wwwroot/resimler", resimyolu.FileName);
                  var stream = new FileStream(path, FileMode.Create);
                  proje.CatId = katid;
                  proje.Baslik = baslik;
                  proje.İcerik = icerik;
                  proje.ResimYolu = resimyolu.FileName;
 
              }
 
              port.TProjects.Add(proje);
              port.SaveChanges();
 
              TempData["mesaj"] = "Date Created";
              return RedirectToAction("ProjectAdd");
          }
      }

Filter with excel export call by link does not work!

$
0
0

Hi

I'm using a query type mapped to a db view to export an excel file successfully, but when trying to filter no data is filtered.

The model of VisitHeader:

    public class VisitHeader
    {
        public int Id { get; set; }
        public decimal GuestId { get; set; }
        public int CenterId { get; set; }
        public int VisitTypeId { get; set; }

        public string FullName { get; set; }

        public string CenterName { get; set; }

        public DateTime VisitDate { get; set; }

        public string VisitName { get; set; }

        public bool SpecialStatus { get; set; }

        public string Notes { get; set; }

        public Center Center { get; set; }
        public Guest Guest { get; set; }
        public VisitType VisitType { get; set; } 
    }

mapping in the Context:

public virtual DbQuery<VisitHeader> VisitHeader { get; set; }

Visit/Index method:

        private readonly ApplicationDbContext _context;
        private readonly UserManager<ApplicationUser> _userManager;

        public VisitController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        public async Task<IActionResult> Index(decimal? sid, int? CeId)
        {
            var visContext = _context.Query<VisitHeader>().AsQueryable();
            //Some code
            ViewData["CenterId"] = new SelectList(_context.Center, "Id", "CenterName");
            return View(await visContext.ToListAsync());
        }

Excel export method in Visit controller:

        public IActionResult Excel(decimal? sid, int? CeId)
        {
            var viContext = _context.Query<VisitHeader>().AsQueryable();
            ViewData["CeIdF"] = CeId;
            ViewData["TxtIdF"] = sid;
            if (sid != null || sid.GetValueOrDefault() != 0)
            {
                viContext = viContext.Where(s => s.GuestId.ToString().Contains(sid.ToString()));
            }
            if (CeId != null || CeId.GetValueOrDefault() != 0)
            {
                viContext = viContext.Where(s => s.CenterId.ToString().Equals(CeId.ToString()));
            }
            viContext = viContext.OrderByDescending(s => s.Id);

            var comlumHeadrs = new string[]
            {
                "Name","Center","Visit Type","Visit Date","Notes"
            };

            byte[] result;
            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("Visit Worksheet"); 
                using (var cells = worksheet.Cells[1, 1, 1, 5]) 
                {
                    cells.Style.Font.Bold = true;
                }
                for (var i = 0; i < comlumHeadrs.Count(); i++)
                {
                    worksheet.Cells[1, i + 1].Value = comlumHeadrs[i];
                }
                var j = 2;
                foreach (var visit in viContext)
                {
                    worksheet.Cells["A" + j].Value = visit.FullName;
                    worksheet.Cells["B" + j].Value = visit.CenterName;
                    worksheet.Cells["C" + j].Value = visit.VisitName;
                    worksheet.Cells["D" + j].Value = visit.VisitDate.ToString("dd/MM/yyyy");
                    worksheet.Cells["E" + j].Value = visit.Notes;

                    j++;
                }
                result = package.GetAsByteArray();
            }

            return File(result, "application/ms-excel", $"Visit.xlsx");
        }

The Visit/Index view:

@model IEnumerable<VisitHeader>
@*Some Code here*@<form asp-action="index" method="get"><div class="form-actions no-color"><p><div class="form-group row"><div class="col-xs-2"><label for="ex2">ID</label><input class="form-control" type="text" name="sid" value="@ViewData["TxtIdF"]"></div><div class="col-xs-3"><label for="ex1">Name</label><input class="form-control" id="namee" type="text" readonly></div><div class="col-xs-2"><label>Center</label><select class="form-control" asp-items="ViewBag.CenterId" name="CeId" value="@ViewData["CeIdF"]"><option selected value="">  </option></select></div><div class="col-xs-4"><br /><input type="submit" value="Search" class="btn btn-default"><a asp-action="Excel" asp-controller="Visit" asp-route-id="@ViewData["CeIdF"]" class="btn btn-primary">
                        Excel</a></div></div></p></div></form>

I'm using Ajax also in the previous view to call some another method used for searching successfully.

When I press Excel button the data is not filtered because the parameter didn't sent to the method due to the debugger. I don't know how to send it.

How to solve please?

Hosted Asp.net mvc core app shows list of Files instead of Home Page

$
0
0

Hello everyone, 

I've published my app into release Version in order to host it on locally IIS server, the app is published correctly and is hosted on the server, but when I open the url in the browser for the hosted app it shows me the list of files in that directory instead of my app Home page.

here's a screen shot of my problem

https://imgur.com/K4gqbql

and this is the code for my web.config file

<?xml version="1.0" encoding="UTF-8"?><configuration><system.webServer><directoryBrowse enabled="true" /><defaultDocument><files><clear /><add value="index.html" /><add value="Default.htm" /><add value="Default.asp" /><add value="index.htm" /><add value="iisstart.htm" /><add value="default.aspx" /></files></defaultDocument></system.webServer></configuration>

can you help me please 

Oracle connectivity issue for asp.net core 2.1 web api from docker container

$
0
0
Hi All,
I am trying to connect oracle database using Oracle.ManagedDataAccess.Core 2.18.3 ; i am using asp.net core 2.1 web api. When i run this code on my local machin it works fine but when dockerised it and deployed it under container it fails with below error

ORA-00604 : error occured at recursive SQL level 1
ORA-01882 : timezone region not found

I searched on internet and found below solutions but both of them are not working for me ; Please help asap.

1. Set timezone in docket file as below
ENV TZ=America/New_York
2. Also setup timezone to open oracle connection as below
Oracle globalization info = con.GetSession();
info.TimeZone = "America/New_York";
con.SetSessionInfo(info);


Please help

Datetime formatting differences on productionserver VS development pc

$
0
0

Hi,

I am developing a app that is making intensive use of Datetime calculations. On my development machine I have my Regional setting on Dutch.

I am hosting my app on a server in the UK. Now when I set in razor a HTML data field with a Datetime value like this: 

data-datum=@Model.LinesList[i].DayList[ii].Datum.ToString("yyyy-MM-dd")

On my development machine it renders with "-" between the year, Month and Day component. but on the UK server a "/" is appearing.

Since I am using this Date in Jquery selections, things go very wrong.

Is there a way to force the production server to use the Dutch formatting? Or is there an other trick to make this working?


Filtering data when export a db view to excel

$
0
0

Hi

I'm trying to filter the data when export some view in the database to excel file.

I'm using this code in the Visit controller:

public IActionResult Excel(decimal? sid, int? MrId)
        {
            var viContext = _context.Query<VisitHeader>().AsQueryable();
            ViewData["TxtIdF"] = sid;
            ViewData["MrIdF"] = MrId;
            if (sid != null || sid.GetValueOrDefault() != 0)
            {
                viContext = viContext.Where(s => s.NzeelId.ToString().Contains(sid.ToString()));
            }
            if (MrId != null || MrId.GetValueOrDefault() != 0)
            {
                viContext = viContext.Where(s => s.MrkzId.ToString().Equals(MrId.ToString()));
            }

            var comlumHeadrs = new string[]
            {
                "Name","Center","Visit Type","Visit Date","Notes"
            };

            byte[] result;

            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("Visit Worksheet"); 
                using (var cells = worksheet.Cells[1, 1, 1, 5]) //(1,1) (1,5)
                {
                    cells.Style.Font.Bold = true;
                }
                for (var i = 0; i < comlumHeadrs.Count(); i++)
                {
                    worksheet.Cells[1, i + 1].Value = comlumHeadrs[i];
                }
                var j = 2;
                foreach (var visit in viContext)
                {
                    viContext = viContext.OrderByDescending(s => s.Id);
                    worksheet.Cells["A" + j].Value = visit.FullName;
                    worksheet.Cells["B" + j].Value = visit.MrkzName;
                    worksheet.Cells["C" + j].Value = visit.VisitType;
                    worksheet.Cells["D" + j].Value = visit.VisitDate.ToString("dd/MM/yyyy");
                    worksheet.Cells["E" + j].Value = visit.Notes;

                    j++;
                }
                result = package.GetAsByteArray();
            }

            return File(result, "application/ms-excel", $"Visit.xlsx");
        }

where VisitHeader is a view in the database and mapped in the context.

and in the Visit/Index view:

@model IEnumerable<VisitHeader>
@*Some code here*@
<form asp-action="index"><div class="form-actions no-color"><p><div class="form-group row"><div class="col-xs-2"><label for="ex2">ID</label><input class="form-control" id="idd" type="text" name="sid"></div><div class="col-xs-3"><label for="ex1">Name</label><input class="form-control" id="namee" type="text" readonly></div><div class="col-xs-2"><label>Center</label><select class="form-control" asp-items="ViewBag.MrkzId" name="MrId" value="@ViewData["MrIdF"]"><option selected value=""> </option></select></div><div class="col-xs-4"><br /><input type="submit" value="Seatch" class="btn btn-default"><a asp-action="Excel" asp-controller="Visit" class="btn btn-primary">Excel</a></div></div></p></div></form>

When I press search button after choose a value from MrkzId Select, the data is filterred in the view it self but when press Excel button the data is not filtered!

Why? and How to solve please?

beginner question

$
0
0

I am following this page https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2

and I have added the line  app.UseStaticFiles(); to my configuration, but the address "~/images/myfile.jpeg does not find the images folder.  However, the address "~/../../images/myfile.jpeg" does find it on my local server, but not on my website.

It say in the link that "~/" is supposed to represent www.root but it appears to behave like regular file system addresses. 

How can I relatively address my path?

src=@Model.Styles[j].ImageFileName />
private List<ResumeStyle> UpdateImagePathForStyles(List<ResumeStyle> styles, string folder)
        { 
            for (int i = 0; i < styles.Count; i++)
            {
                styles[i].ImageFileName = $"~/images/{styles[i].ImageFileName}";
            }
            return styles;
        }

thanks

HttpHandler in asp.net core - Response.BinaryWrite does not contain a definition

$
0
0

Hi!

I am traying change my old "RequestHandler.ashx" to asp.net core but now I am getting some problem with the migration, could any one help?

Into the Statup.cs:

app.MapWhen(context => context.Request.Path.ToString().EndsWith(".order"),
appBuilder =>
{
     appBuilder.UsePrintMiddleware(); 
}); 

On my Meddleware:

public static class PrintMiddlewareHelper
{
public static IApplicationBuilder UsePrintMiddleware
(this IApplicationBuilder builder)
{
return builder.UseMiddleware<PrintController>();
}
}

On my controller:

private RequestDelegate _next;

public PrintController(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
context.Response.ContentType = "application/octet-stream";

// Pega número do pedido para criar o cupom
var BytesValue = CriaResponse(context.Request.Path.Value.ToLower().Replace("/", "").Replace(".order", ""));
context.Response.BinaryWrite(BytesValue);

await _next.Invoke(context);
}

// Acessa PrinterUtility e gera dados do cupom para enviar à impressora térmica
private byte[] CriaResponse(string idOrder)
{
PrinterUtility.EscPosEpsonCommands.EscPosEpson obj = new PrinterUtility.EscPosEpsonCommands.EscPosEpson();

var BytesValue = Encoding.ASCII.GetBytes(string.Empty);
//BytesValue = PrintExtensions.AddBytes(BytesValue, GetLogo(@"D://logo1.bmp"));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Separator());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.CharSize.DoubleWidth6());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.FontSelect.FontA());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Alignment.Center());
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("Title\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.CharSize.DoubleWidth4());
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("Sub Title\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.CharSize.Nomarl());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Separator());
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("Invoice\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Alignment.Left());
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("Invoice No. : " + IdOrder+ "\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("Date : 12/12/2015\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("Itm Qty Net Total\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Separator());
BytesValue = PrintExtensions.AddBytes(BytesValue, string.Format("{0,-40}{1,6}{2,9}{3,9:N2}\n", "item 1", 12, 11, 144.00));
BytesValue = PrintExtensions.AddBytes(BytesValue, string.Format("{0,-40}{1,6}{2,9}{3,9:N2}\n", "item 2", 12, 11, 144.00));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Alignment.Right());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Separator());
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("Total\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, Encoding.ASCII.GetBytes("288.00\n"));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Separator());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Lf());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Alignment.Center());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.CharSize.DoubleHeight6());
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.BarCode.Code128("12345"));
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.QrCode.Print("12345", PrinterUtility.Enums.QrCodeSize.Grande));
BytesValue = PrintExtensions.AddBytes(BytesValue, "-------------------Thank you for coming------------------------\n");
BytesValue = PrintExtensions.AddBytes(BytesValue, obj.Alignment.Left());
BytesValue = PrintExtensions.AddBytes(BytesValue, CutPage());

return BytesValue;
}

On my another application:


static void Main(string[] args)
{
string Parameter = args[0].ToLower().ToString().Replace(POSJobHandler.Properties.Settings.Default.ReplaceText.ToLower(),"");
string Ext = POSJobHandler.Properties.Settings.Default.PostExtn;

string url = POSJobHandler.Properties.Settings.Default.UrlPost + "/" + Parameter + "." + Ext;


WebRequest request = WebRequest.Create(url);
WebResponse response=request.GetResponse();


string result;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}

RawPrinterHelper.SendValueToPrinter(POSJobHandler.Properties.Settings.Default.PrinterName, Encoding.ASCII.GetBytes(result) );

return;
}

Everything was working fine before moveing to asp.net core, but now, context.Response.BinaryWrite(BytesValue) isn't working anymore! (Response.BinaryWrite does not contain a definition)

How can I do that now? Need I change to Json, for exemplo, and than convert to Binary as a result on my another application? 

Need help with custom ValidationAttribute for date range

$
0
0

I have a .net core application with a simple search page with 2 date boxes and I would like to validate the range. I have found some examples on how to do this online but the code is not working for me. The ValidationAttribute would validate against another property named in my model. The problem is that property I am looking for in the ValidationContext is always null. I have debugged it and while I expect the ValidationContext to have an object type of SearchModel, it has an object type of DateTime. 

The below is the relevant code. SearchModel is a Razor Page model. The error occurs onif (property == null) . Does anyone have advice on how I can get the parent and access the DateOfBirthEnd property?

public class SearchModel
{
    [BindProperty]
    [DataType(DataType.Text)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [BindProperty]
    [DataType(DataType.Text)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [BindProperty]
    [Display(Name = "Date Of Birth Start")]
    [InputType(HtmlInputType.Text)]
    [Comparison("DateOfBirthEnd", ComparisonType.LessThan, ErrorMessage = "End date must be greater than start date")]
    public DateTime? DateOfBirthStart { get; set; }

    [BindProperty]
    [Display(Name = "Date Of Birth End")]
    [InputType(HtmlInputType.Text)]
    public DateTime? DateOfBirthEnd { get; set; }
}



[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
  public class ComparisonAttribute : ValidationAttribute
  {
    private readonly string _comparisonProperty;
    private readonly ComparisonType _comparisonType;

    public ComparisonAttribute(string comparisonProperty, ComparisonType comparisonType)
    {
      _comparisonProperty = comparisonProperty;
      _comparisonType = comparisonType;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      ErrorMessage = ErrorMessageString;

      if (value.GetType() == typeof(IComparable))
      {
        throw new ArgumentException("value has not implemented IComparable interface");
      }

      var currentValue = (IComparable)value;

      var property =  validationContext.ObjectType.GetProperty(_comparisonProperty);

      if (property == null)
      {
        throw new ArgumentException("Comparison property with this name not found");
      }
      var comparisonValue = property.GetValue(validationContext.ObjectInstance);

      if (comparisonValue.GetType() == typeof(IComparable))
      {
        throw new ArgumentException("Comparison property has not implemented IComparable interface");
      }

      if (!ReferenceEquals(value.GetType(), comparisonValue.GetType()))
      {
        throw new ArgumentException("The properties types must be the same");
      }

      bool compareToResult;

      switch (_comparisonType)
      {
        case ComparisonType.LessThan:
          compareToResult = currentValue.CompareTo((IComparable)comparisonValue) >= 0;

          break;

        case ComparisonType.LessThanOrEqualTo:
          compareToResult = currentValue.CompareTo((IComparable)comparisonValue) > 0;

          break;

        case ComparisonType.EqualTo:
          compareToResult = currentValue.CompareTo((IComparable)comparisonValue) != 0;

          break;

        case ComparisonType.GreaterThan:
          compareToResult = currentValue.CompareTo((IComparable)comparisonValue) <= 0;

          break;

        case ComparisonType.GreaterThanOrEqualTo:
          compareToResult = currentValue.CompareTo((IComparable)comparisonValue) < 0;

          break;

        default:
          throw new ArgumentOutOfRangeException();
      }

      return compareToResult ? new ValidationResult(ErrorMessage) : ValidationResult.Success;
    }
  }

MP4 video's not works on on ios or safari mobile only ?

$
0
0

Hi

please i have an asp core site with angular 5 as front end - site have view with contain button when i press it it's src of video sent to video element then video open on auto play mode

** video run without any problem on android and chrome, Firefox on mobile (android only) and web - but no luck to run it on ios device like i phone on safari 

HTML Image

asp core to get video file (api controller)

public IActionResult GetVideos(string categoryId = null, string langId = null, bool Default = true, bool active = true, int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var videos = _videoService.GetAllVideos(null, null, categoryId, active, pageIndex, pageSize);
            var list = videos.ToList();

            if (langId != null)
            {
                if (list.Any())
                {
                    foreach (var a in list.ToList())
                    {
                        a.Name = a.GetLocalized(n => n.Name, langId);
                    }
                }
            }

            var videosAsDtos = list.Select(pc =>
            {
                return _dtoHelper.PrepareVideoDto(pc);
            });

            // HttpContext.Response.Headers.Add("Accept-Ranges", "bytes");
            _response.Add(Ok().StatusCode, "Success", videosAsDtos, true);

            return Json(_response);
        }

Get Videos Method (services)

        public IPagedList<Video> GetAllVideos(string name = null, string desciption = null, 
        string categoryId = null, bool? active = null,
            int pageIndex = 0, int pageSize = Int32.MaxValue)
        {
            var query = GetVideos();

            //search by name
            if (!String.IsNullOrWhiteSpace(name))
                query = query.Where(c => c.Name != null && c.Name.ToLower() == name.ToLower()).ToList();

            //search by active
            if (active != null)
            {
                query = query.Where(c => c.Active == active).ToList();
            }

            var videos = new PagedList<Video>(query.OrderBy(i => i.Id), pageIndex, pageSize);
            return videos;
        }

set global header "accept ranges" on startup.cs

// Add header:
            application.Use((context, next) =>
            {
                context.Response.Headers["Accept-Ranges"] = "bytes";
                return next.Invoke();
            });

            application.UseMvc();

angular code to run video

      this.data.GetHomeVideo(localStorage.getItem("LangId")).subscribe(res => {
        this.VideoURL = res.VideoUrl;$("#homevideo").addClass("fullscreenvideo");$("#homevideo").show();
      });

HTML Code

<a id="homevideo" style="display: none; text-align: center;"><video id="myVideo" style="width: 78%" controlsList="nodownload" oncontextmenu="return false;" [src]="VideoURL"
        autoplay muted playsinline type="video/mp4"></video></a>

so please any way to fix that and make all videos work as android or web ?

Thanks a lot ....

Viewing all 9386 articles
Browse latest View live


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