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

JSON serilizer and date format

$
0
0

Hi

I've got a StartDate propetry in my ServiceItem defined like this:

        [DataType(DataType.Date)]
        [Required]
        public DateTime? StartDate { get; set; }

Then when I try to serialize SubscriptionServiceItem into Json using:

return Json(Mapper.Map<SubscriptionServiceItemDto>((await _context.ServiceItems.OfType<SubscriptionServiceItem>().Where(g => g.Id == id && g.IsArchived == false).ToListAsync()).First()));

I get the following response

"startDate": "2013-05-11T00:00:00",

Is it possiblie in ASP.NET Core to format the JSON result for that particular property like this:

"startDate": "2013-05-11",

.Net Core Deserialize JQgrid Filters String rules return 0 array

$
0
0

Hi All.

I have a filters with value:-

"{\"groupOp\":\"AND\",\"rules\":[],\"groups\":[{\"groupOp\":\"OR\",\"groups\":[],\"rules\":[{\"data\":\"Aborted\",\"op\":\"eq\",\"field\":\"Contract_Status\"},{\"data\":\"Completed\",\"op\":\"eq\",\"field\":\"Contract_Status\"}]},{\"groupOp\":\"OR\",\"groups\":[],\"rules\":[]}]}"

tringBuilder sb = new StringBuilder();

                    string rtRule = string.Empty;
                    string rtWhere = string.Empty;

                   
                    FilterModel filterModel = JsonConvert.DeserializeObject<FilterModel>(filters.ToString());

                    // How to convert the rules structure to the search criteria structure
                    var searchCriterias = filterModel.rules.Select(Rule => new SearchCriteria
                    {
                        Column = Rule.field,
                        Operation =
                              (WhereOperation)
                              StringEnum.Parse(
                                  typeof(WhereOperation),
                                  Rule.op),
                        Value = Rule.data
                    }).ToArray();

But, the filterModel > rules return 0 count array.

My FilterModel as

using System;
using System.Collections.Generic;
using System.Reflection;

namespace XXXXX
{
    public static class LinqDynamicConditionHelper
    {
        private static Dictionary<string, string> WhereOperation =
                new Dictionary<string, string>
                {
                    { "eq", "{1} =  {2}({0})" },
                    { "ne", "{1} != {2}({0})" },
                    { "lt", "{1} <  {2}({0})" },
                    { "le", "{1} <= {2}({0})" },
                    { "gt", "{1} >  {2}({0})" },
                    { "ge", "{1} >= {2}({0})" },
                    { "bw", "{1}.StartsWith({2}({0}))" },
                    { "bn", "!{1}.StartsWith({2}({0}))" },
                    { "in", "" },
                    { "ni", "" },
                    { "ew", "{1}.EndsWith({2}({0}))" },
                    { "en", "!{1}.EndsWith({2}({0}))" },
                    { "cn", "{1}.Contains({2}({0}))" },
                    { "nc", "!{1}.Contains({2}({0}))" },
                    { "nu", "{1} == null" },
                    { "nn", "{1} != null" }
                };

        private static Dictionary<string, string> ValidOperators =
                new Dictionary<string, string>
                {
                    { "Object"   ,  "" },
                    { "Boolean"  ,  "eq:ne:" },
                    { "Char"     ,  "" },
                    { "String"   ,  "eq:ne:lt:le:gt:ge:bw:bn:cn:nc:" },
                    { "SByte"    ,  "" },
                    { "Byte"     ,  "eq:ne:lt:le:gt:ge:" },
                    { "Int16"    ,  "eq:ne:lt:le:gt:ge:" },
                    { "UInt16"   ,  "" },
                    { "Int32"    ,  "eq:ne:lt:le:gt:ge:" },
                    { "UInt32"   ,  "" },
                    { "Int64"    ,  "eq:ne:lt:le:gt:ge:" },
                    { "UInt64"   ,  "" },
                    { "Decimal"  ,  "eq:ne:lt:le:gt:ge:" },
                    { "Single"   ,  "eq:ne:lt:le:gt:ge:" },
                    { "Double"   ,  "eq:ne:lt:le:gt:ge:" },
                    { "DateTime" ,  "eq:ne:lt:le:gt:ge:" },
                    { "TimeSpan" ,  "" },
                    { "Guid"     ,  "" }
                };

        public static string GetCondition<T>(RuleModel rule)
        {
            if (rule.data == "%")
            {
                // returns an empty string when the data is ‘%’
                return "";
            }
            else
            {
                // initializing variables
                Type myType = null;
                string myTypeName = string.Empty;
                string myTypeRawName = string.Empty;
                PropertyInfo myPropInfo = typeof(T).GetProperty(rule.field.Split('.')[0]);
                int index = 0;
                // navigating fields hierarchy
                foreach (string wrkField in rule.field.Split('.'))
                {
                    if (index > 0)
                    {
                        myPropInfo = myPropInfo.PropertyType.GetProperty(wrkField);
                    }
                    index++;
                }
                // property type and its name
                myType = myPropInfo.PropertyType;
                myTypeName = myPropInfo.PropertyType.Name;
                myTypeRawName = myTypeName;
                // handling ‘nullable’ fields
                if (myTypeName.ToLower() == "nullable`1")
                {
                    myType = Nullable.GetUnderlyingType(myPropInfo.PropertyType);
                    myTypeName = myType.Name + "?";
                }
                // creating the condition expression
                if (ValidOperators[myTypeRawName].Contains(rule.op + ":"))
                {
                    string expression = String.Format(WhereOperation[rule.op],
                                                      GetFormattedData(myType, rule.data),
                                                      rule.field,
                                                      myTypeName);
                    return expression;
                }
                else
                {
                    // un-supported operator
                    return "";
                }
            }
        }

        //private static string GetFormattedData(Type type, string value)
        //{
        //    switch (type.Name.ToLower())
        //    {
        //        case "string":
        //            value = @"""" + value + @"""";
        //            break;
        //        case "datetime":
        //            DateTime dt = DateTime.Parse(value);
        //            value = dt.Year.ToString() + "," + dt.Month + "," + dt.Day.ToString();
        //            break;
        //    }
        //    return value;
        //}

        private static string GetFormattedData(Type type, string value)
        {
            switch (type.Name.ToLower())
            {
                case "string":
                    value = @"""" + value + @"""";
                    break;
                case "datetime":
                    DateTime dt = DateTime.Parse(value);
                    value = dt.Year.ToString() + "," +
                            dt.Month.ToString() + "," +
                            dt.Day.ToString();
                    break;
            }
            return value;
        }
    }

    public class RuleModel
    {
        public string field { get; set; }
        public string op { get; set; }
        public string data { get; set; }
        public string groupOp { get; set; }
    }

    public class FilterModel
    {
        public string groupOp { get; set; }

        public IList<RuleModel> rules { get; set; }
    }
}

Please advise,

Thanks.

Regards,

Micheale

How can I commucate with the device with asp.net core?

$
0
0

Our company has an old project made by UWP(with GUI) and running in Raspberry with windows IOT before.

As we know, Windows IoT has not updated for several years that it seems it is dead.

These days I found that Microsoft has published many tutorials about asp.net core in IoT devices.

Because of this, I want to migrate my project from UWP to asp.net core.

The Raspberry will connect to a third-party device by a LAN port. The device has an interface protocol that I use a socket to communicate with it before.

I don't know much about socket whether it is the same as HTTPClient/WebSocket or there is a better way to replace it. In addition, it seems asp.net core does not support the socket.

Would you please give me a suggestion? Thank you.

timed out trying to read data from the socket stream

$
0
0

Hi,
i want upload files whit ftp to an other server but when i use these codes ,
its created file in host but the size of file is 0 bytes and return error

   public async Task<IActionResult> Create( IFormFile file)
{
FtpClient client = new FtpClient("144.76.30.231"); client.Credentials = new NetworkCredential("yavarani", "*********"); client.Connect(); using (var stream = new StreamReader(file.OpenReadStream())) { client.UploadAsync(stream.BaseStream, "/yavarani/yavaraniha.ir/wwwroot/Files/Videos/" + aVF.FileNameOrLink).Wait(); }
}

Error : 
timed out trying to read data from the socket stream
 

MailKit HTML format question

$
0
0

Hello,

I am getting Textarea value with jquery and pass it to action in order to send an e-mail. The problem is when it gets to the action, the markup gets lost. How can I keep the value with the markup and send an e-mail?

Here is the portion I am getting value from (result)

<div class="col-md-5"><div class="form-group container-fluid"><textarea class="form-control" id="result" rows="5" readonly></textarea></div><div class="form-group row container-fluid"><div class="col"><input id="btn_purchase" type="button" value="Purchase" class="btn btn-success" /></div><div class="col"> <input id="total" type="text" class="form-control w-25 float-right" readonly /></div></div></div>

Here is the jquery

$("#btn_purchase").click(function() {
        var result = $("#result").html();
        var total = $("#total").val();
        var email = $("#email").val();
        alert(result);
        var serviceURL = '/GameBanks/Send?body=' + result + '&total=' + total + '&email=' + email;$.ajax({
            type: "GET",
            url: serviceURL,
            dataType: 'json',
            success: function (data) {
                if(true)
                    alert("Email sent to " + email);
                else
                    alert("Email did not send to " + email);
            }
        });
    });

Here is the action:

 [HttpGet]
        public Boolean Send(string body, string total, string email)
        {
            var mailstatus = SendEmail(body, email);

            if (!mailstatus) return false;

            return true;
        }

public bool SendEmail(string message, string email)
        {
            try
            {
                                
                var messagem = new MimeMessage();
                messagem.From.Add(new MailboxAddress("gaming", "test@test.com"));
                messagem.To.Add(new MailboxAddress("Customer", email));
                messagem.Subject = "Serial";
                var builder = new BodyBuilder();
                builder.HtmlBody = message;
                messagem.Body = builder.ToMessageBody();

              
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {

                    client.Connect("smtp.yandex.com.tr", 587, false);

                    //SMTP server authentication if needed
                    client.Authenticate("test@test.com", "test");

                    client.Send(messagem);

                    client.Disconnect(true);

                    return true;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }

        }

Group by and Order by in View

$
0
0

I have category title using a Group By and want to order by the display order of the title. Each category is number by a display order field and I want to order by  the display order. How do I do that with the group by that I already have.

 @foreach (var linkGroup in Model.Links.GroupBy(l => l.LinkCategory, LinkCategory.CategoryIdComparer))
                        {<div class="card forum-blue"><div style="color:black"><h4 class="bg-forum-blue" style="padding: 4px; color: white">@linkGroup.Key.Title</h4><hr />
                                    @foreach (var link in linkGroup)
                                    {<p style="padding:4px"><tr><td><a href="@link.Url" target="_blank">@link.Title</a><br> @Html.Raw(@link.Description)</td></tr></p>
                                    }</div></div><br />
                        }

Have something like this but I get an error

 @foreach (var linkGroup in Model.Links.GroupBy(l => l.LinkCategory, LinkCategory.CategoryIdComparer).Select(g => g.OrderByDescending(d => d.Order)).ToList())

on

@linkGroup.Key.Title

Possible Multiple enumerations

How-To: AD auth on Linux w/ Apache/Nginx reverse proxy

$
0
0

I've been trying to figure out if it's possible to use AD for auth in an app served from a linux host.

So far I've found these documents that might get me part way there.

Host ASP.NET Core on Linux

Securing Apache HTTPD with Microsoft Active Directory

nginx-ldap-auth

What I have in my lab setup is a ubuntu box running samba configured as an ADDC, and another which I want to host my app on that is a member of the domain.

I have my development machine a member of the domain as well, and I can log in to computers in the domain with the same account.

I'm not an expert in any of this stuff, I'm just learning, so please excuse me if I get terminology or concepts wrong.

Is there any middleware that would work with such a setup? Stuff to use in Starup.cs which would work with Apache/Nginx as a reverse proxy configured to auth with ldap?

Would it be possible to do single sign on with kerberos/ntlm somehow? I'd imagine that might have more to do with the browser/host though. I'd like to use the credentials from the computer running the web browser to authenticate into the web app without needing to enter a password. Idk if that's at all possible, but if it is, any direction I should look for how to set this up in an environment using both Windows and Linux hosts?

~~~~~~~~~~~~~~

Edit:

I found this document Configure Windows Authentication in ASP.NET Core # Kestrel

But it says: "Credentials can be persisted across requests on a connection. Negotiate authentication must not be used with proxies unless the proxy maintains a 1:1 connection affinity (a persistent connection) with Kestrel."

Further it says: "Once the Linux or macOS machine is joined to the domain, additional steps are required to provide a keytab file with the SPNs"

This post FireFox, Windows Security and Kestrel on ASP.NET Core, seems to provide some more insight into this.

I think at this point, I'll have to either figure out:

1) If I can configure either apache or nginx to " maintains a 1:1 connection affinity (a persistent connection) with Kestrel.", how to not use a proxy, not use negotiate, or if "An alternative to Windows Authentication in environments where proxies and load balancers are used is Active Directory Federated Services (ADFS) with OpenID Connect (OIDC)." is an option.

2) Since the ubuntu box I want to serve an asp.net core app from is already a member of the domain, I'll have to make sure I have the keytab file set up correctly.

Looks like I need to start experimenting with this stuff so I can learn more. Any input on if I'm on the right track here, or redirects to guides from people who have already gone through this, would be much appreciated.

Thanks,

T.F.

ASP.NET Core MVC CRUD Modal PopUp

$
0
0

Hi, 

I am just starting to work with ASP.Net Core MVC. I have difficulty in creating a popup modal. I've tried to create a simple page. 

Below is my model:

namespace CoreModal.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
    }
}

Below is my EmployeeController:

namespace CoreModal.Controllers
{
    public class EmployeeController : Controller
    {
        public static List<Employee> empList = new List<Employee>() {
            new Employee {Id=1, Name="John", Email="john@gmail.com", Address="Campbell", Phone="1234"}
        };

        public IActionResult Index()
        {
            ViewBag.Employee = empList;
            return View();
        }

        [HttpPost]
        [Route("create")]
        public IActionResult Create(string name, string email, string address, string phone)
        {
            var newEmployee = new Employee
            {
                Name = name,
                Email = email,
                Address = address,
                Phone = phone
            };

            empList.Add(newEmployee);
            ViewBag.Employee = empList;
            return RedirectToAction("Index");
        }
    }
}

In my Index View, I create a button to trigger a popup modal for creating a new Employee object as follow:

<a href="#addEmployeeModal" class="btn btn-success" data-toggle="model"><i class="material-icons">&#xE147;</i><span>Add New Employee</span></a><d id="addEmployeeModal" class="modal fade" name="addEmployeeModal"><div class="modal-dialog"><div class="modal-content"><form method="post" asp-controller="employee" asp-action="create"><div class="modal-header"><h4 class="modal-title">Add Employee</h4><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button></div><div class="modal-body"><div class="form-group"><label>Name</label><input type="text" class="form-control" required="required" name="name"/></div><div class="form-group"><label>Email</label><input type="text" class="form-control" required="required" name="email"/></div><div class="form-group"><label>Address</label><input type="text" class="form-control" required="required" name="address"/></div><div class="form-group"><label>Phone</label><input type="text" class="form-control" required="required" name="phone"/></div></div><div class="modal-footer"><input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" /><input type="Submit" class="btn btn-success" value="Add" /></div></form></div></div></d>

But instead of directing to a popup modal, it directs it to url https://localhost:44330/#addEmployeeModal.

What did I do wrong?

Thanks


is a property an object, list and inherit from x class

$
0
0

Hi

I am looping through the properties of an object and need to find out is the property is an class or multiple classes (enumerable, collection or list) and inherit a class of x and i am a little stuck, any help would be appriciated.

Disable user authentication for a controller

$
0
0

Hi,

I want to disable user authentication for a controller. But I still need to authentication (bearer token should be valid) for this controller. And of course need authentication and user roles for other controllers. How can I disable role base auth for an controller/action?

My startup class contains:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication(); app.UseAuthorization(); app.UseRoleAbility();
...
}


And my controller contains 

[Authorize]

attribute.

when I bring the cursor over datetime input text the existing date value will be disappeard from the input text

$
0
0

Hi

After setting the value of Expiry date and PenaltyExpDt to the corresponding input text, and after when I place the cursor over  there, the value would be disappeared from the textbox. Why that date is no longer stay when I put the cursor over the textbox of  datetime

LicenseModel
public int DocCatID { get; set; }
public DateTime? ExpiryDate { get; set; }
public DateTime? PenaltyExpDt { get; set; }
NotMapped]
public string PenaltyExpDttxt { get; set; }
[NotMapped]
public string ExpiryDateTxt { get; set; }

Html

<div class="form-group"><label asp-for="DocCatID" class="control-label control-label-left col-sm-3 text-danger">Document Category</label><div class="controls col-sm-9"><select class="form-control" asp-for="DocCatID"
               asp-items="@ViewBag.Category" data-role="select" onchange="SetExpiryDate"></select><span asp-validation-for="DocCatID" class="text-danger">@ViewBag.ErrorMsgCategory</span></div></div><div class="col-md-6"><div class="form-group"><label class="control-label control-label-left col-sm-3">Penalty Point<br />Expiry Date</label><div class="controls col-sm-9"><div class='input-group date' id='PenaltyDatePicker'><input type='text' id="txtPenaltyExpDt" asp-for="PenaltyExpDt" class="form-control disabled" /><span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div></div></div></div><div class="form-group"><label class="control-label control-label-left col-sm-3">License Expiry</label><div class="controls col-sm-9"><div class='input-group date' id='ExpiryDatePicker'><input type='text' id="txtExpiryDate" asp-for="ExpiryDate" class="form-control disabled" /><span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div></div></div>
<script>$(document).ready(function () {
$("#ExpiryDatePicker").datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, autoclose: true, todayBtn: 'linked' });
$("#PenaltyDatePicker").datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, autoclose: true, todayBtn: 'linked' }); function SetExpiryDate() { var url = '@Url.Action("GetExpiryDate", "EmpDoc")';$.post(url, $('form').serialize(), function (view) { console.log(view);$("#txtExpiryDate").val(view.expiryDateTxt); // Here I set the value of Date into textbox in dd/mm/yyyy format $("#txtPenaltyExpDt").val(view.penaltyExpDttxt);// I set the value here }); }</script>

Controller. The corresponding Expiry Dated taking from the database and set to textbox using the function  SetExpiryDate

public IActionResult GetExpiryDate(EmpDocumentModel data)
        {
            LicenseModel doc = new LicenseModel();
            var docmodel = _unitOfWork.DocumentRepository.GetExpirydate(data.EmployeeID, data.DocCatID);
            data.ExpiryDate = null;
            data.PenaltyExpDt = null;

            if (data.ExpiryDate != null)
            {
                data.ExpiryDateTxt = String.Format("{0:dd/MM/yyyy}", docmodel.ExpiryDate);
            }
            if (data.PenaltyExpDt != null)
            {
                data.PenaltyExpDttxt = String.Format("{0:dd/MM/yyyy}", docmodel.PenaltyExpDt);
            }
            return Json(data);
        }

How to Shift Left a row of Thumbnails

$
0
0

My code is currently:

<div class="img-wrap">

    <img class="item-thumb" src="file1.jpg" id="thumbimg" onclick="ShowLarge(this);" />

    <img class="item-thumb" src="file2.jpg" id="thumbimg" onclick="ShowLarge(this);" />

     (and then replicated for 8 more thumbnails)

</div>

Suppose product1 has 6 thumbnails, and product2 has 8 thumbnails. How can I shift-left the images?

I am learning html and Razor, so I'm open to any suggestions!

cannot load the menu in asp.net core

$
0
0

I have trying to load a menu using bulma.css instead of bootstrap.  I have taken bootstrap off the site.  

This localhost page can’t be found

No webpage was found for the web address: https://localhost:44391/

<div id="error-information-popup-container" style="color: #5f6368; font-family: 'Segoe UI', Tahoma, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-style: initial; text-decoration-color: initial;" jstcache="0"> <div id="error-information-popup" jstcache="0"> <div id="error-information-popup-box" jstcache="0"> <div id="error-information-popup-content" jstcache="0"> <div class="error-code" style="color: var(--error-code-color); font-size: 0.8em; text-transform: uppercase; margin-top: 12px; display: block;" jstcache="18" jscontent="errorCode">HTTP ERROR 404</div> </div> </div> </div> </div>

Below is the layout menu; 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Bumples</title>


<environment include="Development">
.
<link rel="~/lib/bulma-0.8.0/css/bulma.css" rel="stylesheet" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>

<environment exclude="Production">
<link rel="~/lib/bulma-0.8.0/css/bulma.css" rel="stylesheet" />
<link rel="stylesheet" href="~/css/min.css" asp-append-version="true" />
</environment>

</head>

<body>
<section class="hero is-fullheight has-background-black">
<div class="hero-body">
</div>
</section>
<section class="section" ">
<div class="Container">
<h2 "Title">
Hellp jen
</h2>
</div>
</section>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>

<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - WebApplication1 - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>

<script src="~/lib/jquery/dist/jquery.min.js"></script>

@RenderSection("Scripts", required: false)


</body>

Thanks Jen

The startup is below:

using Bumples.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Bumples
{
public class Startup
{
private readonly IConfiguration Configuration;


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

public void ConfigureServices(IServiceCollection services)
{

//Add Connection Middleware
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));

services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();

//Add MVC Middleware
services.AddControllersWithViews();
services.AddRazorPages();
}

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

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

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}

}




</html>

 

OAuth 2.0 Authentication: try to avoid .AddCookie and just want to use .AddOAuth only

$
0
0

Hello everyone,

I got the chance to reinvent this application [1] with .NET Core 2.2, AspNetCore and Docker.
This repository is an out-of-the-box easy-to-use sample application for our API and OAuth 2.0 Service.

Everything works very well, but there is a point that I do not fully understand.

I want to use this application without any usage of a cookie. All neccessary OAuth credentials (Client ID, secret, access token and refresh token) are stored in json files. The user should be able to use this application even in a fresh incognito session, just with the stored credentials.

I tryed to set the ".AddOAuth" as the default, but there is no "OAuthAuthenticationDefaults.AuthenticationScheme". I also had tryed "UseJwtBearerAuthentication" but all examples, are completly different to the OAuth part. My code only works with ".AddCookie" and "CookieAuthenticationDefaults.AuthenticationScheme". :(

In [2] I postet a snippet of my code.

My Questions are:

  • I know the advantage of using cookies but is there an other important reason why I need cookies here?
  • Could someone point me to an example which uses OAuth (with Microsoft.AspNetCore.Authentication.OAuth) without usage of cookies?
  • Is there a way, to use the OAuth creadentials with the baererAuthentication?

I spent hours in researching about this topc :(

Thanks a lot, Robert

[1] https://github.com/Sage/sageone_api_csharp_sample

[2] This snippet is from https://github.com/Sage/sageone_api_csharp_sample/blob/bfe10ba405ec5f7f488995879b308cc3f48ac39c/app/Startup.cs#L56

services.AddDistributedMemoryCache();
      services.AddSession(options =>
      {
        options.Cookie.HttpOnly = false;
        options.Cookie.IsEssential = true;
        options.IdleTimeout = TimeSpan.FromHours(1);
      });

      services.AddMvc();
      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

      services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
          .AddCookie(o => o.LoginPath = new PathString("/login"))
          .AddOAuth("oauth2", "Sage Accounting", o =>
          {
            o.ClientId = config_client_id;
            o.ClientSecret = config_client_secret;
            o.CallbackPath = new PathString("/auth/callback");
            o.AuthorizationEndpoint = AUTHORIZATION_ENDPOINT;
            o.TokenEndpoint = TOKEN_ENDPOINT;
            o.SaveTokens = true;

            o.Scope.Add("full_access");
            o.Events = new OAuthEvents
            {
              OnRemoteFailure = HandleOnRemoteFailure,
              OnCreatingTicket = async context => //async
              {
                int tok_expires_in = (int)context.TokenResponse.Response["expires_in"];
                int tok_refresh_token_expires_in = (int)context.TokenResponse.Response["refresh_token_expires_in"];

                tokenfileWrite(context.AccessToken,
                                calculateUnixtimestampWithOffset(tok_expires_in),
                                context.RefreshToken,
                                calculateUnixtimestampWithOffset(tok_refresh_token_expires_in),
                                context.HttpContext);
                return;
              }
            };
          });
    }

which are some ASP.NET based Opens source Learning management System

$
0
0

Dear all,

Which are some of the best asp.net based opens source based LMS systems which I can download and use.

I was not able to find any recent ones. any advise over this will be appreciated .

Thank You


WebApi using Token

$
0
0

Hi

  I have Visual Studio 2012. I want to develop Restful Api using token. Is there any tutorial or link available.

Can Api be developed in VS 2012 using Asp.net core.

Thanks

multiple grid in view in .net core

$
0
0

A single view with atleast two horizontal layout like split layout. I want to accomodate two grid like. The two grids should work independently.One layout with

list of customers. The other layout with list of orders of the customer selected. In asp.net grid control available. But i am using .net core.

Server Error in Application - The resource cannot be found.

$
0
0

I have a Website that runs exactly as it should in localhost. When I upload it and want to run it on my domain, I get the above error with the following description:

Description:HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

My provider blatantly told me, that they don't give support for something like that, because it has to be due to my app being faulty.

my web.config is as follows:

<configuration>
   <location path="." inheritInChildApplications="false">
   <system.webServer>
     <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
     </handlers>
   <aspNetCore processPath=".\Homepage Core.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="outofprocess">>
     <environmentVariables>
        <environmentVariable name="ASPNETCORE_HTTPS_PORT" value="443" />
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Release" />
     </environmentVariables>
  </aspNetCore>
</system.webServer>
 </location>
</configuration>

Any ideas, what could cause this?

How Do I Block Data from Rendering in an API Controller?

$
0
0

I have an api controller that gets data from a service that returns more data than I want rendered in the json output, but I also need to access the same data from Razor Pages. How do I block that output at the controller level?

Normally I would just omit the data from the get task that the service performs, so that it would render as null in json output, but if I do that I can't access it from server side code in a Razor Page. The api controller is used because json is needed for an infinite scroll plugin. Otherwise I would not even need a controller.

Is there perhaps a quick line of code that can be added to a Controller that tells it to omit a specific field from the json output?

Here is the task redacted for efficiency from the Service file:

public async Task<Posts[]> GetPosts()
        { 
            var posts = await _context.Posts.Where(post => post.Active == true)
                            .Select(p => new Posts { 
                            Postid = p.Postid,
                            Title = p.Title,
                            Description = p.Description,
                            Userid = p.Userid 
                            })
                        .ToArrayAsync();
            return posts;
        }

A second task then paginates the results of the first one

public async Task<List<Posts>> GetPaginatedResult(int currentPage, int pageSize)
        {
            var data = await GetPosts();
            return data.OrderByDescending(d => d.Postid).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
        }

The controller is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PostAlmostAnything.Data;
using PostAlmostAnything.Models;
using PostAlmostAnything.SiteServices;
using PostAlmostAnything.AppCode;

namespace PostAlmostAnything.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PaginatedPostsController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public PaginatedPostsController(PostsService postService)
        {
            PostService = postService;
        }
        public PostsService PostService { get; }
 [HttpGet("{id:int}/{sid:int}")]
        public async Task<List<Posts>> GetPaginatedPostsAsync(int id, int sid)
        {
            int CurrentPage = id;
            int PageSize = sid;
            return await PostService.GetPaginatedResult(CurrentPage, PageSize);
        }

        
    }
}

Obviously there are reasons not to render the Userid field in the json output, but I also need to access the Userid in razor pages that need to get the UserName based on that id. I am using the default Identity tables in my database and those tables by default have no foreign key relationships with one another, so when they are scaffolded automatically they do not create navigation classes. Identity also stores the UserId as a string instead of a unique identifier like the old AspnetMembership provider did, so I'm not really sure how to go about creating a foreign key relationship between string values. I seem to recall trying to do that once and running into some kind of error message about SQL Server not supporting such relationships with strings. As a result I have another task called GetUserNambeById that I call from razor pages to populate UserName fields. This requires GetPosts to return the UserId so that it can be passed to GetUserNameById.

Filtering a join table

$
0
0

Hello all! 

I'll preface this with letting you know I'm a beginner developer (learning dotnet core and angular).  With that said, I'm having issues with filtering in a join table.  I have setup a table that is a one to many, holding two columns - OwnerId and OwneeId.  The ownerId can have many OwneeId's.  This was all setup via Entity Framework.  

I'm looking for someone who can help walk me through filtering all ownee's that and OwnerId may have, and then return their name via my API (the owner is a organization, and the ownee is a location).  

I have searched around for an answer but am having trouble finding something that works. (and I'm not using Linq in my project).  

The way I have things setup is as follows: 

IOrganizationRepository:

using System.Collections.Generic;
using System.Threading.Tasks;
using Outmatch.API.Models;

namespace Outmatch.API.Data
{
    public interface IOrganizationRepository
    {
        void Add<T>(T entity) where T: class;
        void Delete<T>(T entity) where T: class;
        Task<bool> SaveAll();
        Task<IEnumerable<Organizations>> GetOrganizations();
        Task<Organizations> GetOrganization(int id);
        Task<OrgToLoc> GetOwnees(int OrganizationId, int LocationId);
    }
}

OrganizationRepository:

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Outmatch.API.Helpers;
using Outmatch.API.Models;

namespace Outmatch.API.Data
{
    public class OrganizationsRepository : IOrganizationRepository
    {
        private readonly DataContext _context;
        public OrganizationsRepository(DataContext context)
        {
            _context = context;

        }
        public void Add<T>(T entity) where T : class
        {
            _context.Add(entity);
        }

        public void Delete<T>(T entity) where T : class
        {
            _context.Remove(entity);
        }
        // get an organization only one of them).  Pass in the organization ID from the user interface, and pull the organization that corrisponds to the 
        // id, returning it to the GUI 
        public async Task<Organizations> GetOrganization(int id)
        {
            var organization = await _context.Organization.FirstOrDefaultAsync(u => u.Id == id);
            return organization;
        }

        // Get the list of all organizations and return them to the GUI
        public async Task<IEnumerable<Organizations>> GetOrganizations()
        {
            var organizations = await _context.Organization.ToListAsync();
            return organizations;
        }

        public async Task<OrgToLoc> GetOwnees(int OrganizationId, int LocationId)
        {
            return await _context.LocationOwners.FirstOrDefaultAsync(u => u.OwnerId == OrganizationId && u.OwneeId == LocationId);
        }

        public async Task<bool> SaveAll()
        {
            return await _context.SaveChangesAsync() > 0;
        }
    }
}

ILocationsRepository:

using System.Collections.Generic;
using System.Threading.Tasks;
using Outmatch.API.Models;

namespace Outmatch.API.Data
{
    // This interface Repository queries the DB and retreives the locations
    public interface ILocationsRepository
    {
        void Add<T>(T entity) where T: class;
        void Delete<T>(T entity) where T: class;
        Task<bool> SaveAll();
        Task<IEnumerable<Locations>> GetLocations();
        Task<Locations> GetLocation(int id);
    }
}

LocationsRepository:

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Outmatch.API.Models;

namespace Outmatch.API.Data
{
    public class LocationsRepository : ILocationsRepository
    {
        private readonly DataContext _context;
        public LocationsRepository(DataContext context)
        {
            _context = context;

        }
        public void Add<T>(T entity) where T : class
        {
            _context.Add(entity);
        }

        public void Delete<T>(T entity) where T : class
        {
            _context.Remove(entity);
        }
        // get a location only one of them).  Pass in the location ID from the user interface, and pull the location that corrisponds to the 
        // id, returning it to the GUI 
        public async Task<Locations> GetLocation(int id)
        {
            var location = await _context.Locations.FirstOrDefaultAsync(u => u.Id == id);
            return location;
        }

        // Get the lost of all locations and return them to the GUI
        public async Task<IEnumerable<Locations>> GetLocations()
        {
            var locations = await _context.Locations.ToListAsync();
            return locations;
        }

        public async Task<bool> SaveAll()
        {
            return await _context.SaveChangesAsync() > 0;
        }
    }
}

OrganizationsController:

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Outmatch.API.Data;
using Outmatch.API.Dtos;
using Outmatch.API.Models;

namespace Outmatch.API.Controllers
{
    // Controller for getting location and locations.
    // [Authorize]
    // [Route("api/[controller]")]
    // [ApiController]
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class OrganizationsController : ControllerBase
    {
        private readonly IOrganizationRepository _repo;
        private readonly IMapper _mapper;
        public OrganizationsController(IOrganizationRepository repo, IMapper mapper)
        {
            _mapper = mapper;
            _repo = repo;
        }

        // Get a list of all organizations from the database
        [HttpGet]
        public async Task<IActionResult> GetOrganizations()
        {
            var organizations = await _repo.GetOrganizations();

            var organizationsToReturn = _mapper.Map<IEnumerable<OrganizationForListDto>>(organizations);

            return Ok(organizations);
        }
        // Create an orgaization
        [HttpPost]
        public async Task<IActionResult> CreateOrganizations(OrganizationCreateDto organizationCreateDto)
        {
            //  Grab the current users roles to verify they have access to this API call
            var userRole = User.FindFirst(ClaimTypes.Role).ToString();

            if (userRole != "http://schemas.microsoft.com/ws/2008/06/identity/claims/role: GlobalAdmin")
                return Unauthorized();

            // Create the new organization
            var organizationToCreate = _mapper.Map<Organizations>(organizationCreateDto); //

            _repo.Add(organizationToCreate);

            if (await _repo.SaveAll())
            {
                var organizationToReturn = _mapper.Map<OrganizationCreateDto>(organizationToCreate);
                return CreatedAtRoute("GetOrganization", new { controller = "Organizations", Id = organizationToReturn.Id }, organizationToReturn);
            }
            throw new Exception("Unable to create new organization. Failed to save.");
        }

        // Get a specific organization from the database
        [HttpGet("{id}", Name = nameof(GetOrganization))]
        public async Task<IActionResult> GetOrganization(int id)
        {
            var organization = await _repo.GetOrganization(id);

            var organizationToReturn = _mapper.Map<OrganizationCreateDto>(organization);

            return Ok(organizationToReturn);
        }

        // Check if the location is already assigned to an owner (organization)
        [HttpPost("{id}/assign/{locationId}")]
        public async Task<IActionResult> AssignLocation(int id, int locationId)
        {
            // Ensure the user is authorized to assign the location to an organization
            var userRole = User.FindFirst(ClaimTypes.Role).ToString();

            if (userRole != "http://schemas.microsoft.com/ws/2008/06/identity/claims/role: GlobalAdmin")
                return Unauthorized();

            var assignment = await _repo.GetOwnees(id, locationId);

            // Check if the location is already owned by the same owner. 
            if (assignment != null)
                return BadRequest("This location is already assigned to this organization");

            if (await _repo.GetOrganization(id) == null)
                return NotFound("This organization does not exist");

            assignment = new OrgToLoc
            {
                OwnerId = id,
                OwneeId = locationId
            };

            _repo.Add<OrgToLoc>(assignment);

            if (await _repo.SaveAll())
                return Ok();

            return BadRequest("Failed to assign the location to an organization");
        }
    }
}

LocationsController:

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Outmatch.API.Data;
using Outmatch.API.Dtos;
using Outmatch.API.Models;

namespace Outmatch.API.Controllers
{
    // Controller for getting location and locations.
    // [Authorize]
    // [Route("api/[controller]")]
    // [ApiController]
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class LocationsController : ControllerBase
    {
        private readonly ILocationsRepository _repo;
        private readonly IMapper _mapper;
        private readonly IClientRepository _clientRepo;
        private readonly UserManager<User> _userManager;
        public LocationsController(ILocationsRepository repo, IMapper mapper, IClientRepository clientRepo, UserManager<User> userManager)
        {
            _userManager = userManager;
            _clientRepo = clientRepo;
            _mapper = mapper;
            _repo = repo;
        }

        // Get a list of all locations from the database
        [HttpGet]
        public async Task<IActionResult> GetLocations()
        {
            var locations = await _repo.GetLocations();

            var locationsToReturn = _mapper.Map<IEnumerable<LocationForListDto>>(locations);

            return Ok(locations);
        }
        // Create a location
        [HttpPost]
        public async Task<IActionResult> CreateLocation(int clientId, LocationCreateDto locationCreateDto)
        {
            //  Grab the current users roles to verify they have access to this API call
            var userRole = User.FindFirst(ClaimTypes.Role).ToString();

            if (userRole != "http://schemas.microsoft.com/ws/2008/06/identity/claims/role: GlobalAdmin")
                return Unauthorized();

            // Create the new location
            var locationToCreate = _mapper.Map<Locations>(locationCreateDto); //

            _repo.Add(locationToCreate);

            if (await _repo.SaveAll())
            {
                var locationToReturn = _mapper.Map<LocationCreateDto>(locationToCreate);
                return CreatedAtRoute(nameof(GetLocation), new { id = locationToReturn.Id, userid = clientId }, locationToReturn);
            }
            throw new Exception("Unable to create new location. Failed to save.");
        }

        // Get a specific location from the database
        [HttpGet("{id}", Name = nameof(GetLocation))]
        public async Task<IActionResult> GetLocation(int id)
        {
            var location = await _repo.GetLocation(id);

            var locationToReturn = _mapper.Map<LocationCreateDto>(location);

            return Ok(locationToReturn);
        }
    }
}

OrgToLoc model file:

namespace Outmatch.API.Models
{
    public class OrgToLoc
    {
        public int OwnerId { get; set; }
        public int OwneeId { get; set; }
        public Locations Owner { get; set; }
        public Locations Ownee { get; set; }
    }
}

DataContext:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Outmatch.API.Dtos;
using Outmatch.API.Models;

namespace Outmatch.API.Data
{
    // DbContext is what is called to connect to the database and pass data along. 
    public class DataContext : IdentityDbContext<User, Role, int, IdentityUserClaim<int>, UserRole,
        IdentityUserLogin<int>, IdentityRoleClaim<int>, IdentityUserToken<int>>
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) {}

        // Values name represents the table name in the database. 
        public DbSet<Value> Values { get; set; }
        public DbSet<Locations> Locations { get; set; }
        public DbSet<Organizations> Organization { get; set; }
        public DbSet<OrgToClients> OrgToClients { get; set; }
        public DbSet<OrgToLoc> LocationOwners { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            // Define the relationship betweek user roles and users (Clients)
            builder.Entity<UserRole>(userRole => 
            {
                userRole.HasKey(ur => new {ur.UserId, ur.RoleId});

                userRole.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                userRole.HasOne(ur => ur.User)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();
            });

            // Define the relationship between Organization and Clients (or Users)
            builder.Entity<OrgToClients>()
                .HasKey(c => new {c.UserId, c.OrganizationId});

            builder.Entity<OrgToClients>()
                .HasOne(u => u.Organization)
                .WithMany(u => u.UserId)
                .HasForeignKey(u => u.OrganizationId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.Entity<OrgToClients>()
                .HasOne(u => u.User)
                .WithMany(u => u.OrganizationId)
                .HasForeignKey(u => u.UserId)
                .OnDelete(DeleteBehavior.Restrict);

            // Define the relationship between Organizations (Owners) and  Locations (Ownees)
            builder.Entity<OrgToLoc>()
                .HasKey(k => new {k.OwnerId, k.OwneeId});

            builder.Entity<OrgToLoc>()
                .HasOne(u => u.Ownee)
                .WithMany(u => u.Owners)
                .HasForeignKey(u => u.OwneeId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.Entity<OrgToLoc>()
                .HasOne(u => u.Owner)
                .WithMany(u => u.Ownees)
                .HasForeignKey(u => u.OwnerId)
                .OnDelete(DeleteBehavior.Restrict);
        }
    }
}

Can anyone point me in the right direction on this?  As mentioned above, I am trying to filter out all OwneeId id's from the OwnerId table, and return the "LocationName" from the Locations table.  Any assistance would be greatly appreciated. 

Viewing all 9386 articles
Browse latest View live


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