joy
joy
CC#
Created by joy on 11/8/2023 in #help
✅ oauth in asp net framework?
hi all, i have created a redirect url for oauth clients how can i redirect my deployed asp net project in iis to redirect to do the authentication? this is then authentication controller public class AuthController : Controller { public ActionResult Index() { return View(); } [Route("auth/redirect")] [HttpGet] public ActionResult Redirect() { string redirectScript = "<html><script>window.location.href=window.location.href.Replace('#', '?').Replace('redirect', 'AuthRedirect')</script></html>"; return Content(redirectScript, "text/html"); } [HttpGet] public ActionResult AuthRedirect(string access_token) { // Get the full URL from the request var url = Request.Url.ToString(); // Extract the fragment identifier var fragment = url.Substring(url.IndexOf('#') + 1); // Parse the fragment to extract the access_token parameter value var queryString = HttpUtility.ParseQueryString(fragment); var accessToken = queryString["access_token"]; var cookie = new HttpCookie("otsession", accessToken) { Path = "/", HttpOnly = true, }; Response.Cookies.Add(cookie); return RedirectToAction("Index", "Home"); } } this is the oauth link http://localhost:8080/otdsws/login?response_type=token&client_id=<oauth client ID>&redirect_uri=<successful authentication redirect url>&state=none i have never created an implementation of oauth before.. so any assistance will be appreciated
54 replies
CC#
Created by joy on 6/15/2023 in #help
✅ c# to convert msg file to pdf?
hi all, is there a free open source library to convert msg file to pdf while retaining the "outlook PrintToPDF" result format or perhaps we can set the formatting? i tried to convert from msg to html (before using another library to convert to pdf bcs i wanna retain the original format) using outlook library but outlook library need to prompt user for permission, and also tried aspose library for conversion but the output is different when i compare the result with "outlook PrintToPDF" result, i also tried some other libraries that just doesnt work.. any advise is appreciated.. thanks in advance.. if there is no free open source one, the paid one also okay as long as we got the same result as when we use the "outlook PrintToPDF"
3 replies
CC#
Created by joy on 1/12/2023 in #help
✅ create a nullable datetime array
hi all, how do we create a nullable datetime array?
8 replies
CC#
Created by joy on 12/12/2022 in #help
❔ async code in cshtml file of asp net framework that target IE browser
hi all, i understand that Internet Explorer arent' compatible with async/await, but is there an alternative to this if we want to handle asynchronous code (API request for example before we execute the next code) and our target website is Internet explorer, do we have to install babel into our asp net framework project?
18 replies
CC#
Created by joy on 11/9/2022 in #help
❔ determine if file in local folder is of email type using asp
hi all, can i understand what is the proper way to check if a file in the local folder is of email type? rather than checking on my it's extension for example .msg, .eml etc.. which i understand can lead to more issue (insecure system)
3 replies
CC#
Created by joy on 10/31/2022 in #help
anti forgery token asp global asax file
hi all, currently i try to implement the anti forgery token following microsoft article (the csrf and ajax section). https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks so if i make a post request to my form, the anti forgery token will be send from my javascript file to asp controller. here's the implementation i did :
public class CustomAntiForgery : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}

var httpContext = filterContext.HttpContext;
var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
}
}
public class CustomAntiForgery : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}

var httpContext = filterContext.HttpContext;
var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
}
}
my controller :
[HttpPost]
[CustomAntiForgery]
public ActionResult AddMemo{ //...}
[HttpPost]
[CustomAntiForgery]
public ActionResult AddMemo{ //...}
to enable the anti csrf token by default in global asax file, do we need to add CustomAntiForgery into the Application_Start() method? so it looks like this
[CustomAntiForgery]
protected void Application_Start()
{ //... }
[CustomAntiForgery]
protected void Application_Start()
{ //... }
23 replies
CC#
Created by joy on 10/12/2022 in #help
413 request entity too large postman
hi all, im trying to upload a large file through a postman but got this message "413 request entity too large", but when i try to upload it directly to the server there's no issue although it'll takes time for a large file but the upload is successfull, does anybody know why it fails through postman for a large file? if i upload small size file it works tho..
12 replies
CC#
Created by joy on 10/4/2022 in #help
an existing connection was forcibly closed by the remote host
hi all, i have a console program that's trying to call an API (both written in net framework 4.7.2), the console it's trying to upload bunch of documents to another server API, after a long time, i will get this message "an existing connection was forcibly closed by the remote host", can anyone help to advise why? i try to search for solution most of them related to 'enable TLS..." but the API call is working for a while till it gives me error message..
15 replies
CC#
Created by joy on 9/30/2022 in #help
inherit two interface that have same properties
hi all, i have two interfaces that have member with same name inside, and i inherit these two interfaces for some reason but i can't seem to access only one of the member from an interface.. is it possible we decide which member from which interface we wanted to use?
public interface IMemo{
public long id {get;set;}
}

public interface IStickyNote {
public long id {get;set;}
}
public class MyNote <T> where T :IMemo, IStickyNote {
//if i access id member here i will get ambiguity exception
}
public interface IMemo{
public long id {get;set;}
}

public interface IStickyNote {
public long id {get;set;}
}
public class MyNote <T> where T :IMemo, IStickyNote {
//if i access id member here i will get ambiguity exception
}
36 replies
CC#
Created by joy on 9/27/2022 in #help
upload file that have huge size using asp net framework form
hi all, i understand that we can't upload file to a form with size larger than 2GB using asp net (reference from this link https://www.webdavsystem.com/server/documentation/large_files_iis_asp_net/), can i understand.. do we need to upload the file in chunk using JavaScript to pass the content to our controller? i found an article, im not sure if this is the right approach using javascript.. https://www.dotnetbull.com/2018/09/uploading-large-file-chunks-javascript-ajax-mvc-dotnet.html?m=1
50 replies
CC#
Created by joy on 9/26/2022 in #help
get public holiday of a country [Answered]
hi all, how do we check if a specific date is a public holiday in a country using c#? i try to use https://github.com/nager/Nager.Date nager package but it's only for people who sponsor this bcs a license is needed, there's a public api that we can use, but only limited to check if today is a public holiday, not to check if specific date is a holiday, can anybody help to advise? thank you so much in advance
10 replies
CC#
Created by joy on 9/26/2022 in #help
Unable to resolve the .NET SDK version as specified
11 replies
CC#
Created by joy on 9/21/2022 in #help
sql timeout using dapper
hi all, im trying to use dapper in asp net core project and register this DapperContext as Transient im trying to make a request to GetNote endpoint, inside this GetNote endpoint there will be lots of request made to multiple tables, and after some time, i will get an exception from my api like this :
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding
can anyone help advise what could be the possible issue (im wondering if the Transient is correct)? i increased the Connection Timeout to 1000 already..
5 replies
CC#
Created by joy on 9/21/2022 in #help
get value from parallel for loop using Task.WhenAll
hi all, im trying to implement a parallel for loop because of some timeout issue (the normal loop will loop through large dataset and it's taking lots of time so i try to use Task.WhenAll), im trying to process all items inside this await Task.WhenAll(tasks); line but im wondering how do we get the value returned by ProcessItem method because we put them inside the WhenAll to process, can anyone help to advise? thank you so much in advance..
IList<Note> resources = new List<Note>();
var tasks = new List<Task>();
foreach (var item in result)
{
tasks.Add(ProcessItem(item));
}
await Task.WhenAll(tasks); //get the value from here and initialize into the resources variable

NoteList noteList = new NoteList ()
{
Resources = resources
};
return noteList;

IList<Note> resources = new List<Note>();
var tasks = new List<Task>();
foreach (var item in result)
{
tasks.Add(ProcessItem(item));
}
await Task.WhenAll(tasks); //get the value from here and initialize into the resources variable

NoteList noteList = new NoteList ()
{
Resources = resources
};
return noteList;

private async Task<IList<Note>> ProcessItem(NoteItem item)
{
IList<Note> resources = new List<Note>();
var note= await getNote(item);
Note resource = _mapper.Map<Note>(note);
resources.Add(resource);
return resources;
}
private async Task<IList<Note>> ProcessItem(NoteItem item)
{
IList<Note> resources = new List<Note>();
var note= await getNote(item);
Note resource = _mapper.Map<Note>(note);
resources.Add(resource);
return resources;
}
21 replies
CC#
Created by joy on 9/21/2022 in #help
c sharp property validation if value is null
hi all, im trying to do a properties validation if a value for my property for example userName is null then i will return an empty string instead of a null value but if i have lots of properties for an object, do we have to do it like below validation (redundancy), im wondering if this is a good way, can anyone help to advise? thank you so much in advance..
private string _userName;
public string userName {
get { return _userName; }
set {
if (string.IsNullOrEmpty(value)) _userName = string.Empty;
else _userName = value;
}
}
private string _userName;
public string userName {
get { return _userName; }
set {
if (string.IsNullOrEmpty(value)) _userName = string.Empty;
else _userName = value;
}
}
3 replies
CC#
Created by joy on 9/19/2022 in #help
automapper in net framework
hi all, i tried to implement automapper using net framework 4.7.2, i tried in net core im able to convert from NoteItem to Note (same data retrieved from database), but when i implement this in net framework the noteResult give me 0 result, even tho there's no exception or error thrown, can anyone help advise what could be wrong?
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<List<NoteItem>, List<Note>>();
});

IMapper mapper = config.CreateMapper();
var noteResult = mapper.Map<List<NoteItem>, List<Note>>(result); //result have list of NoteItem retrieved from a database
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<List<NoteItem>, List<Note>>();
});

IMapper mapper = config.CreateMapper();
var noteResult = mapper.Map<List<NoteItem>, List<Note>>(result); //result have list of NoteItem retrieved from a database
12 replies
CC#
Created by joy on 9/18/2022 in #help
interface instead of mapping one by one
hi all, im trying to use an interface to initialize common properties, for example INote that contains all common properties, and multiple classes will inherit from this INote, im trying to achieve something like : initialize once and can be used for all objects that inherit this INote interface previously i was doing one by one mapping for each objects that have common properties and found out there are lots of duplication (some resource say better to do manual mapping that use a library like automapper) so i try to do it using interface, but somehow even if a class inherit this INote i still can't do it like this : Memo resource = QueryVariant(new NoteItem(), "memo"); LongNote longNote = QueryVariant(new NoteItem(), "longNote"); did i miss anything here?
public interface INote{
public long NodeId { get; set; }
public string NoteName { get; set; }
}

public class LongNote : INote {

public long NodeId { get; set; }
public string NoteName { get; set; }

public string barcodeID {get;set;}
public string profileURL {get;set;}
}

public class Memo: INote {

public long NodeId { get; set; }
public string NoteName { get; set; }

public string memoURL {get;set;}
public string memoUniqueID {get;set;}
}

Memo resource = QueryVariant(new NoteItem(), "memo"); //doesnt work

private async Task<INote> QueryVariant(NoteItem item, string type) {
INote note = type switch {
"memo" => new Memo { /*initialize properties here*/ };
// replicate for the other types
_ => // throw some exception here
};
// initialize common properties in note here, i.e:
note.id = item.Id.ToString():
note.noteName = item.name;
// etc
return note;
}
public interface INote{
public long NodeId { get; set; }
public string NoteName { get; set; }
}

public class LongNote : INote {

public long NodeId { get; set; }
public string NoteName { get; set; }

public string barcodeID {get;set;}
public string profileURL {get;set;}
}

public class Memo: INote {

public long NodeId { get; set; }
public string NoteName { get; set; }

public string memoURL {get;set;}
public string memoUniqueID {get;set;}
}

Memo resource = QueryVariant(new NoteItem(), "memo"); //doesnt work

private async Task<INote> QueryVariant(NoteItem item, string type) {
INote note = type switch {
"memo" => new Memo { /*initialize properties here*/ };
// replicate for the other types
_ => // throw some exception here
};
// initialize common properties in note here, i.e:
note.id = item.Id.ToString():
note.noteName = item.name;
// etc
return note;
}
20 replies
CC#
Created by joy on 9/18/2022 in #help
dependency injection net framework
45 replies
CC#
Created by joy on 9/16/2022 in #help
validate json schema sent from request body to an api
hi all, im trying to send a request from postman to asp net api, but the net api need to validate the schema value pass from the postman request body, how can we validate the value "theValidSchemaValueToAnAPI"? i understand if we want to validate a model state, we put a "Required" data annotation, but validating the value doesnt seem to work..
public class NoteItem
{
private IList<string> _schemas = new List<string> { "theValidSchemaValueToAnAPI" };
[Required]
public IList<string> schemas { get { return _schemas; } set { _schemas = value; } }
public string noteId{ get; set; }
public string userId { get; set; }
}
public class NoteItem
{
private IList<string> _schemas = new List<string> { "theValidSchemaValueToAnAPI" };
[Required]
public IList<string> schemas { get { return _schemas; } set { _schemas = value; } }
public string noteId{ get; set; }
public string userId { get; set; }
}
3 replies
CC#
Created by joy on 9/14/2022 in #help
dependency injection in net framework
hi all, i understand that in net core we can add dependency injection like this
IConfiguration Configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient();
builder.Services.AddScoped<Note>();
IConfiguration Configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient();
builder.Services.AddScoped<Note>();
but this way doesnt seem to work in net framework, can anyone help advise how can we do this in net framework?
41 replies