.status-msg-wrap { display: none; }
Thursday, August 15, 2019
no image

Secrets and tools of Time Management

The day has 24 hours, only the working time is considered, it goes on average eight hours a day.

Everyone has basically the same amount of time at their disposal - you, the colleague, the boss, the manager ... But it is amazing how different people utilize their time in different ways. Some particularly productive and efficient people get the most out of each day, while others wonder how this is possible. Part of the answer: Using good time management strategies. In fact, there are many ways you can use your time better to get more out of your daily hours. There are many things you should do in order to better use your time, but also frequent mistakes that need to be avoided.

You should not sleep too much.
If you are a heavy sleeper you should buy an alarm clock and specially an alarm clock with multiple alarms will be helpful in managing your time more efficiently.


Time always passes quickly. If you sit together for two hours with the girl you love, you think it's only a minute; but if you sit on a hot stove for just a minute, you think it's two hours to clarify the idea of ​​relativity.

Thus, in professional life - apart from overtime and additional work - each employee is provided with the same time resource. However, how this time is divided and used is everyone's responsibility. So you should try to gain expertise in what you are doing at your job.
Thursday, May 23, 2019
no image

Consuming a SOAP web service in controller

I added a service from a wsdl in the connected services through "Microsoft WCF Web Service Reference Provider"

It generated all the classes correctly. Now I want to consume this service when I access a api controller at a certain endpoint.

This is the interface of the service that will be called, it has an implementation as well called "SyncRequestPortChannel" which is too long to include here

[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.0.1")]

[System.ServiceModel.ServiceContractAttribute(Namespace="http://www.megatravel.xyz/XMLSchemaSoap", ConfigurationName="SyncReservations.SyncRequestPort")]

public interface SyncRequestPort

{

[System.ServiceModel.OperationContractAttribute(Action="", ReplyAction="*")]

[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]

System.Threading.Tasks.Task<SyncReservations.syncResponse1> syncAsync(SyncReservations.syncRequest1 request);

}

In Startup.cs I addded this

public void ConfigureServices(IServiceCollection services)

{

services.Configure<CookiePolicyOptions>(options =>

{

// This lambda determines whether user consent for non-essential cookies is needed for a given request.

options.CheckConsentNeeded = context => true;

options.MinimumSameSitePolicy = SameSiteMode.None;

});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

// Instanciranje servisa pri pokretanju aplikacije

services.TryAddSingleton<IHelloWorldService, HelloWorldService>();

//

services.AddScoped<SyncRequestPort, SyncRequestPortClient>();

}

And finally in my controller I referenced the SyncRequestPort interface hoping to get the implementation SyncRequestPortClient, however I got a NullReferenceException, the _client isn't instantiated

[Route("api/[controller]")]

[ApiController]

public class ReservationController : ControllerBase

{

private SyncRequestPort _client;

// GET: api/Reservation

[HttpGet]

public IEnumerable<SyncReservations.reservation> Get()

{

Task<syncResponse1> response = _client.syncAsync(new syncRequest1());

return response.Result.syncResponse.reservations;

}

What is the problem with this code? I have searched everywhere for a solution, please help

Consuming a SOAP web service in controller Click here
no image

AppPool/IIS DNS Caching beyond TTL

So using AWS Redis ("elasticache") with 3 nodes, as a session state via the StackExchange Redis sessionstate provider.

Connection is via a CNAME. AWS provides a single DNS entry with a very short TTL that always points to the "master" node, so in the event of a failover, DNS updates, propegates and systems resume.

In theory.

Last night our master failed. The cluster very happily failed from node 1 -> node 2, but our website stayed offline.

Got alerted about an hour after the event, so for a < 5 minute TTL, already at over an hour.

Investigation found DNS was fine. Both nslookup and "ping" from the web server itself showed the main host was resolving to node #2 as expected. By this point node #1 had rebooted but was now a read only replica.

So now the application is completely throwning an error that it can't write to a read only server, even though DNS was showing the proper IP everywhere.

In the end, recycle the app pool, and instantly everything came back online. From what I can tell, the app pool was essentially caching the DNS lookup beyond the TTL.

Is there a way to prevent or change this behaviour? I'd like to have the app be properly resilient to a future failover event.

AppPool/IIS DNS Caching beyond TTL Click here
no image

Javascript framework in existing .net framework MVC C#.

We have an application built in .net framework MVC C# that we gradually want to convert to an SPA. We're about to redesign the page most heavily reliant on javascript and decided we need to implement a javascript framework in order to do this well. Besides, we'll need one if we want to become an SPA in the future. Which would you recommend? Angular seems like we'd have to rebuild pretty much everything in order to accomplish, even if we could do it one part at a time. React and Vue seems like we could just start using in this page and then gradually implement it in other places once we've learned the framework. Are there any challenges to any framework we need to be aware of? Which would you recommend? We will convert to .net Core in the future, would there be any huge benefits to doing it in this switch?

We're a small team of three people, but we've been developing this app full time for a long time, this iteration is maybe eight years old? We have a good back end with our own database framework that communicates with the client via Wcf. Another thing we want in the future is the ability for the server to contact the client via SignalR or similar.

Javascript framework in existing .net framework MVC C#. Click here
no image

How do I prevent a temporary value being assigned when editing a record with EntityFramework?

I'm struggling with an error I'm getting when trying to update a record. Could anyone offer any input please?

I've created an Edit page for a record, when saving, I get the following error:

The property 'Id' on entity type 'LoadTable' has a temporary value while attempting to change the entity's state to 'Modified'. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

I think Id may be being assigned a temporary value rather than using the existing one but I'm unsure how to prevent this.

From my Edit.cs:

[BindProperty] public LoadTable LoadTable { get; set; } public async Task<IActionResult> OnGetAsync(Guid id) { if (id == null) { return NotFound(); } LoadTable = await _context.LoadTable.FirstOrDefaultAsync(m => m.Id == id); if (LoadTable == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(LoadTable).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!LoadTableExists(LoadTable.Id)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool LoadTableExists(Guid id) { return _context.LoadTable.Any(e => e.Id == id); } 

From context:

entity.Property(e => e.Id).HasDefaultValueSql("(newid())"); 

From Model:

public partial class LoadTable { public Guid Id { get; set; } } 

Any help or input would be greatly appreciated. Thanks!

How do I prevent a temporary value being assigned when editing a record with EntityFramework? Click here
Wednesday, May 22, 2019
no image

3 best stereo speakers to buy in 2019

In today's post i will share with you the three most recommended speakers for 2019 according to user popularity

Bose Bass Module 700

You love your new sound bar Bose Soundbar 700, but would like to increase the performance by a notch? Add the Bose Bass Module 700 bass module to experience bass power worthy of the name. Designed exclusively for the Bose Soundbar 700 soundbar, it's the best bass module we've ever produced for any of our home theater systems. In fact, this module offers the best performance on the market among the subwoofers of this size. It connects wirelessly to your soundbar and adds even more depth and impact to everything you listen to, from explosive film effects to the wildest playlists.
 For details visit

Yamaha's compact MCR-232 sound system  

Yamaha's compact MCR-232 sound system is one of the best and best-in-class sound systems under the $ 500 mark. Its audio quality reaches a staggering level of fidelity with strong, powerful bass and rich, well-articulated midrange frequencies. Those who know the PianoCraft series will recognize a similar sound quality between these two remarkable systems. The sound dispersion is wide and offers a good quality of listening, even in a big room where this speaker brings to life the music. To obtain such a quality, it is still necessary to make a small compromise: the compact sound system is divided into three elements - amplifier, CD player and speakers. 

Rockville RSG15.24

Rockville RSG15.24 speakers are best for DJ or music managers and people who want to gather large crowds of people. They consumer 2000 Watts of energy and these speakers have very loud and clear voice and bass is very high. If you are a party organizer you would love these because of their high quality sound. These speakers have high frequency and non ressonant particle board. For further details please click here

no image

Winforms and linq to sql classes not saving to mdf file.

So I'm trying to help someone out with a small win forms project and while I've never worked in win forms I'm well versed in web forms so it translates easy enough. Here is the problem I have. I added an MDF file as I'm just trying to keep it so all of the data is contained in the solution itself, so there's no sql express set up or anything.

My code all works fine, and if I run the form, I will see the data I add/edit. However, as soon as I close and reopen the project, the data is gone. Now, if I go in manually to the db and add entries via the sql manager it works, but not from my form objects. Any ideas why? I can attached my full porject upon request, but an example is

Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click 'double check the added a name

Dim name = nameTb.Text 'note I only put name in the form. You would want to update it with all the options 'and then update the stuff in the using db thing to add all the proper fields If (String.IsNullOrWhiteSpace(name)) Then MessageBox.Show("Please enter a name") Exit Sub End If 'this is using linq to sql classes to connect to the database so you don't have to write actual sql and can use classes 'and intellisense to connect to stuff Using db As New DndClassesDataContext Dim entity = New Entity entity.EntName = name db.Entities.InsertOnSubmit(entity) db.SubmitChanges() MessageBox.Show("The entity was added") End Using 'reload the data LoadEditEntities() LoadEntityList() 

End Sub 'add btn click LoadEditEntities reloads a combo box with the data. As I said, this all works when I run the form, I can add things and I see them show up in the edit combo. However, as soon as I stop and then re run the project, the data never got saved. Any ideas? DndClassesDataContext is a linq object that maps back to my mdf file.

Winforms and linq to sql classes not saving to mdf file. Click here
no image

Update database where ID is specified after File Upload is complete. asp.net web api

I want to update the FileName column in the database whenever i have successfully uploaded a file to the web api. I will specify the Id in my url when im posting the file through postman for example http//localhost/PhysioWebPortal/api/PerformedExercises/PostFile/1014 , where 1014 is the id Can anyone help me with the updating database part? I have attached a image of the database as well.

T

his is the code for the post:

// POST: api/PerformedExercises/Post

[HttpPost]

[ResponseType(typeof(PerformedExercis))]

//[Route("{Id}")]

[Route("PostFile/{id}")]

public HttpResponseMessage PostFile(int id , PerformedExercis performed)

{

//Check if Request contains any File or not

if (HttpContext.Current.Request.Files.Count == 0)

{

throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

}

var httpRequest = HttpContext.Current.Request;

var docfiles = new List();

foreach (string files in httpRequest.Files)

{

var postedFile = httpRequest.Files[files];

string filePath = HttpContext.Current.Server.MapPath("~/Uploaded/" + (DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss")) + postedFile.FileName);

Console.WriteLine(postedFile.FileName);

Console.WriteLine(filePath);

var provider = new MultipartFormDataStreamProvider(filePath);

postedFile.SaveAs(filePath);

docfiles.Add(filePath);

}

//Read the File data from Request.Form collections.

HttpPostedFile uploadedFile = HttpContext.Current.Request.Files[0];

//Convert the File data to Byte Array which will be store in database

byte[] bytes;

using (BinaryReader br = new BinaryReader(uploadedFile.InputStream))

{

bytes = br.ReadBytes(uploadedFile.ContentLength);

}

//Retrieve and update database

if (performed.FileName == null)

{

throw new HttpResponseException(HttpStatusCode.InternalServerError);

}

else

{

//Insert the File to Database Table - performedExercises

PHYSIODBEntities f_Entities = new PHYSIODBEntities();

PerformedExercis file = new PerformedExercis

{

FileName = Path.GetFileName(uploadedFile.FileName)

};

f_Entities.SaveChanges();

f_Entities.PerformedExercises.Add(file);

return Request.CreateResponse(HttpStatusCode.OK, new { Name = file.FileName });

}

}

Update database where ID is specified after File Upload is complete. asp.net web api Click here
no image

trouble with azure variables for connection strings

I've got an API deployed and working in azure via github. Problem is I want to utilize their varaibles so I do not push my connection strings to a public github repo. So I created my variables in azure

https://i.redd.it/hmku4tqewsz21.png

And two variables under app settings..

https://i.redd.it/wms4aukcwsz21.png

Here is the code i've tried using to access it -

string dbconn = Environment.GetEnvironmentVariable("SQLCONNSTR_DBConnectionString"); string dbconn = ConfigurationManager.ConnectionString["DBConnectionString"].ConnectionsString; string dbconn = Configuration.GetConnectionString("DBConnectionString"); 

None of these values work, they return NULL in local, but if I'm not mistaken these variables should be compiled during the deployment azure kicks off when I merge, so it shouldn't work on local...

And i've only attempted to access the connection strings for the db so far, once that works I will obviously move on to check the storage strings.

EDIT: My insights is showing 500 errors.

trouble with azure variables for connection strings Click here
no image

Resources for becoming a better developer

Hi all,

I have tried a quick search in this forum but could not find something relevant to my question so here I am. Apologies in advance if this's been asked before.

So I am a .net mvc developer with over 5 years of experience. I got so used and comfortable in my current job that I kinda stopped improving myself beyond what's required to do my job at this company.

I would like to improve myself and be a better programmer. So here is what I know:

  • ASP.NET Web Forms: I have used that for 3 years (the first 3 years of my professional life, not currently)
  • ASP.NET MVC: This is what I am mainly using these days.
  • ASP.NET CORE: I have not used this yet.
  • Angular: Very basic knowledge
  • VUE.JS: I have not used this yet.
  • React.JS: I have not used this yet.

So what I would like to do is improve myself to keep my skills relevant in today's workplace (I live in the UK but it shouldn't matter that much)

I would like to be more advanced so that I would feel comfortable taking on a senior role in the near future.

Here is what I want:

  • Any advance learning material for .NET/ASP.NET/MVC/CORE etc. Most books I find are geared towards beginners.
  • Any good books on software architecture (like layers, how to think about layering a project, decoupling, dependency injection, etc) that are relevant today because I feel like most of software design principles might not be as relevant today because of advancement in technology. For example, Repository Layer is somewhat obsolete with Entity Framework or Dapper.
  • Any other books that you think is a must read for me.
  • I have not used TDD (both companies I've worked for never really saw the value in it so I never bothered learning it)

I hope I have provided enough information for what I want.

Resources for becoming a better developer Click here
no image

Why are there no AOP or Dynamic Proxy implementations for .Net Core?

There are a bunch of libraries available for AOP (Apart Oriented Programming) or dynamic proxies on .Net Framework. But almost all of them say they don't work on .Net Core. Anytime only why?

Are there any available?

I looked at Castle Dynamic Proxy, Spring.Net AOP, and a few that use code dom to generate the proxy. None work on core.

Why are there no AOP or Dynamic Proxy implementations for .Net Core? Click here
no image

[Help] Adding custom header to .netcore using swashbuckle

Good day all, first time on this sub, but I need some help.

I haven't used C# in the past 3 years but have been placed on a project that uses exclusively C#.

The problem I'm facing is with the swashbuckle plugin, I have already added and apiKey security definition, but I additionally have to add a custom header to all requests that our backend uses to identify if the call was made from mobile or web. The header is named "WebVersion".

I've been going through the documentation and haven't had much success, found loads of solutions for none .netcore though.

If anyone could point me in the right direction, that would be amazing

[Help] Adding custom header to .netcore using swashbuckle Click here
Tuesday, May 21, 2019
no image

Is it just me, or do most people who use ASP.NET Core get defensive or entitled when someone recommends using a "nimbler" technology stack like Django, Node/Express, or Ruby on Rails for web development?

Usually, the responses I hear are ASP.NET Core is the future and that I'm stupid for sticking with Django, Node/Express, or Ruby on Rails for web development.

And when people try to bring up points on why ASP.NET Core is not necessarily the best solution for startups or rapid prototyping compared to nimbler technologies, I often get the response that JavaScript sucks, it's garbage, Django and Rails sucks.

I mean, come on.

Yes, I'm sure a more than a few startups CAN use ASP.NET Core and have been using it, but let me ask you: What is the common case?

In your opinions, if I were a complete beginner programmer, and I learned JavaScript, Python, and PHP and that's all I knew, would you say that I should go out of my way to learn ASP.NET Core and C# if my end goal was to work on hobby side projects or develop my own web startup?

The truth is: The common case for .NET/.NET Core/ASP.NET Core is that it is ultimately mostly used by existing .NET Developers or large Enterprise projects, not hobby projects or startups. It's not even about what languages are trendy or not, it's just pointing out the COMMON CASE. Java / C# are fundamentally known for being enterprise-grade languages. Yes, you can do startup projects with it, but it won't be the COMMON CASE.

Let's say I wanted to create a social media or marketplace app, and I just wanted to develop the MVP as quick as possible. Can I do it in C#/ASP.NET Core? Yes, it's possible. But why would I SPECIFICALLY go out of my way to learn a language for this specific use case?

Thoughts?

Is it just me, or do most people who use ASP.NET Core get defensive or entitled when someone recommends using a "nimbler" technology stack like Django, Node/Express, or Ruby on Rails for web development? Click here
no image

Quality Open Source Example Projects?

Greetings all,

I am a full stack .NET developer. Mainly, I am still stuck in the MVC world, but I have played with .Net Core + a few of the front end frameworks.

I am currently in a bit of a downtime at my job, I figured I might as well learn something new.

Do you all know of any good quality open source .NET projects? Honestly, I don't really care what the project does nor do I care about what fronted framework is being used, whether it's .NET, .NET Core, etc..

I just want to see if I can improve my methods/tools. I feel like I learn far more from 'taking things apart' and tinkering than guides/tutorials.

Quality Open Source Example Projects? Click here
no image

Where does the RouteConfig.cs file appear in Visual Studio 2019?

I'm following some tutorials and one of the things early on that differs from the video is I don't have a routeconfig.cs file. I click File > New Project > ASP.NET Core Web Application > Web Application (Model-View-Controller). The folders I get are Controllers, Models, Views. No Startup folder where my routeconfig would appear to be.

Can someone explain how this changed in VS2019 and where this file is? If it's not global anymore, can you provide a basic analogy for how it works?

Thank you in advance kind peoples!

Where does the RouteConfig.cs file appear in Visual Studio 2019? Click here
no image

Question on Approach

Hey Guys, have a new project to work and wanted to check what would be a good way of doing this. Apologies in advance if this scenario has been asked and answered many times.

I have a webapi that is hosted on Azure. It receives webhooks from an external source, does some processing and stores in to a db.

I want to build another function that then reads this DB, creates new objects and posts this to another API. This function need not operate in real-time(real-time is also an option) as the entries are inserted in the DB, but I would probably want it to check every 15mins or an hour havent decided yet.

I have been reading up on webjobs and am wondering if its the best way to do it or if there are other approaches I should be using. Preferably I would want to run everything out of an azure app service or similar and dont really want to set-up a VM and configure IIS etc.

Do let me know your thoughts.

Edit: Looking at Azure Logic Apps as well

Question on Approach Click here
no image

ELI5: NuGet

I'm a novice programmer, and truly don't understand what NuGet is, how it would benefit me, or how to use it. Would some kind soul be willing to explain any of these things, preferably using small words?

ELI5: NuGet Click here
Monday, May 20, 2019
no image

CQRS for e-wallet app

My team is about to start project that will store credits that you can earn, buy, spend, convert. It must handle millions of users and 100k transactions a day.

I am CQRS practitioner since 2years now, but I have no experience in ES.

Do you think CQRS+ES would be good fit for such project?

I spent last 2 weeks learning CQRS+ES, but the more I read, the more confused I am. There is no single complete course on it (udemy, pluralisght, lynda). Tutorials mostly focus on concepts (which I understand) but misses real life, complex implementation scenarios, e.g.: - how to replay 100million events to create new projection? - how to exactly implement snapshot mechanism? - there should be 1 event store per 1 aggregate root? or 1 event store per app? - how to handle situation when event schema changes? how you "fix" your already existing events in event store? - what should be a key of an event in NoSQL db? AggregateID+EventNumber? you need to somehow keep an order of events. - order of events should be kept per aggregate instance? aggregate class? or per whole app?

I am worried that if my team proceed with CQRS+ES we may fail misserably due to above concerns. On the other hand if we go with just CQRS and single RDBM our system can fail under heavy load.

CQRS for e-wallet app Click here
no image

Help with Span/ReadOnlySpan, Memory/ReadOnlyMemory

I've been migrating a lot of code to use ReadOnlySpan<char> when accessing segments of strings. And with read-only access to arrays, ReadOnlySpan<T> seems like a better choice some times.

But the deeper I dive, the less confident I become about:

When to use?

When not to use?

Example Problem:

Given a Regex match that has N number of matches. Instead of getting 'copies' of string contents, I will extract ReadOnlySpan<char> in the following manner:

var group = match.Groups[1]; var span = originalString.AsSpan().Slice(group.Index, group.Length);

Seems simple enough, but I wonder if after repeat processing if I'm trading memory for extra processing or some other detrimental effect. I know .NET Core 3 is much better at this, but I'm more curious about my own misconceptions.

Help with Span<T>/ReadOnlySpan<T>, Memory<T>/ReadOnlyMemory<T> Click here
no image

Making the switch from PHP world

Hello, I am looking to start learning .net core. I have been programming with php, mainly using laravel framework so i am used to the mvc pattern. I also have some decent knowledge of Java syntax which i think will help me with c#.The reason i am trying to make this switch it's because c#/.net/sharepoint has way more job opportunities in my country than php and also because it seems to be a better organized programming lanaguage which i think will help me.

I would like to know from people that have way more experience than me, what's the best way to go and the learning path i should follow, because i am kinda lost right now with all the information and different aspects of asp.net core.

Thanks in advance to anyone that helps me.

Making the switch from PHP world Click here
no image

[Question] Testing Web API Wrappers

Hi all,

I'm trying to figure out how to properly integration test my managed wrappers over the HttpClient class. Unit testing the things that depend on these wrappers is easy enough (you just mock the whole dependency), but I'd really like to be able to contact that actual endpoint that the client will be using in the wild. The expected benefit of doing this, for me, is:

  1. Enable me to verify routes are being published properly
  2. Validate that authentication are working correctly
  3. Ensure that the dependency injection configuration doesn't have any holes
  4. And other integration test objectives

Does anyone have any frameworks or methods they are using to support this use-case. Would you mind sharing?

Thanks!

[Question] Testing Web API Wrappers Click here
no image

Why use ASP.NET when we can develop websites and web apps with Html, CSS, JS and JS frameworks alone?

I started off with asp.net mvc today. It's confusing to see why asp.net mvc apps make use of JS programs or jquery files, bootstrap, or Angular. Can't we get all of those functionalities that they provide with asp.net only, like in cshtml view files?

Also, as the title explains, why is asp.net even used when we can build web sites and web apps just as well with all those other technologies alone.

I think my understanding of asp.net or .net itself is weak.

Why use ASP.NET when we can develop websites and web apps with Html, CSS, JS and JS frameworks alone? Click here
no image

Cannot run IIS express from within Visual Studio.

So about two days ago, I stop being able to run web sites in Visual Studio.

I get this error:

http://localhost:54147 : error : Error opening web http://localhost:54147. Unable to open the Web site 'http://localhost:54147'. You do not have permission to access the IIS configuration file. Opening and creating web sites on IIS requires running Visual Studio under an Administrator account.

Now, I have done what it says, and run Visual Studio as an administrator (I am used to doing this as have a site running subdomains).

I have also gone to

C:\Users\[username]\Documents\IISExpress\config

Clicked through the permissions prompt, but still problem remains.

This happens in Visual Studio 2015, 2017.

Yesterday, I gave up. I reset windows. Today i had a nice shiny new windows install. I put on SQL server, several versions, and installed Visual Studio 2019 and looked forward to it working. But same problem.

My desktop machine continues to work fine on exactly same software (windows 10, vs 2015, 2017, etc.) and on exactly the same webs (I sync them via dropbox).

Tearing my hair out. Any ideas? I thought blowing my laptop away and resetting windows was the nuclear option, but this bug seems to survive even this.

And please don't post if you're just going to suggest I am not running as an admin, etc. Please read the steps I have taken before posting responses. There must be a solution, but it isn't the obvious one the error suggests, because I have tried it.

Cannot run IIS express from within Visual Studio. Click here
Sunday, May 19, 2019
no image

Blazor Server Side (Razor components) with JWT API

Hello,

Can anyone point me in the right direction? I'm looking for examples of how provide authentication/authorisation in a Blazor Server side (not client site!!) app against a JWT based API (the user store / authentication is in the API, which returns a JWT on successful sign in).

I got it working in Blazor Client side, but its way too experiential for me to get much else working! Server side appears easier generally but I'm stumbling at the jwt auth hurdle!

Thanks!

Blazor Server Side (Razor components) with JWT API Click here
no image

Open.ChannelExtensions (Expressive Pipelining)

https://www.nuget.org/packages/Open.ChannelExtensions/2.0.0

Open.ChannelExtensions

A set of extensions for optimizing/simplifying System.Threading.Channels usage.

Highlights

Being able to define an asynchronous pipeline with best practice usage using simple expressive syntax:

await Channel .CreateBounded<T>(10) .SourceAsync(source /* IEnumerable<Task<T>> */) .PipeAsync( maxConcurrency: 2, capacity: 5, transform: asyncTransform01) .Pipe(transform02, /* capacity */ 3) .ReadAllAsync(finalTransformedValue => { // Do something async with each final value. }); 

or

await source /* IEnumerable<T> */ .ToChannel(boundedSize: 10, singleReader: true) .PipeAsync(asyncTransform01, /* capacity */ 5) .Pipe( maxConcurrency: 2, capacity: 3, transform: transform02) .ReadAll(finalTransformedValue => { // Do something with each final value. }); 

Examples

Reading (until the channel is closed)

One by one read each entry from the channel

await channel.ReadAll( entry => { /* Processing Code */ }); await channel.ReadAll( (entry, index) => { /* Processing Code */ }); await channel.ReadAllAsync( async entry => { await /* Processing Code */ }); await channel.ReadAllAsync( async (entry, index) => { await /* Processing Code */ }); 

Read concurrently each entry from the channel

await channel.ReadAllConcurrently( maxConcurrency, entry => { /* Processing Code */ }); await channel.ReadAllConcurrentlyAsync( maxConcurrency, async entry => { await /* Processing Code */ }); 

Writing

If complete is true, the channel will be closed when the source is empty.

Dump a source enumeration into the channel

// source can be any IEnumerable<T>. await channel.WriteAll(source, complete: true); // source can be any IEnumerable<Task<T>> or IEnumerable<ValueTask<T>>. await channel.WriteAllAsync(source, complete: true); 

Synchronize reading from the source and process the results concurrently

// source can be any IEnumerable<Task<T>> or IEnumerable<ValueTask<T>>. await channel.WriteAllConcurrentlyAsync( maxConcurrency, source, complete: true); 

Pipelining / Transforming

Transform and buffer entries

// Transform values in a source channel to new unbounded channel. var transformed = channel.Pipe( async value => /* transformation */); // Transform values in a source channel to new unbounded channel with a max concurrency of X. const X = 4; var transformed = channel.Pipe( X, async value => /* transformation */); // Transform values in a source channel to new bounded channel bound of N entries. const N = 5; var transformed = channel.Pipe( async value => /* transformation */, N); // Transform values in a source channel to new bounded channel bound of N entries with a max concurrency of X. const X = 4; const N = 5; var transformed = channel.Pipe( X, async value => /* transformation */, N); // or transformed = channel.Pipe( maxConcurrency: X, capacity: N, transform: async value => /* transformation */); 
Open.ChannelExtensions (Expressive Pipelining) Click here
no image

Combining Net Core and WCF in Docker compose

Greetings everyone

I have a project where I am supposed to create an application that consumes a SOAP web service. The application I am writing and the one offering the service are supposed to be written in different technologies.

I chose ASP.NET Core as my weapon of choice and my colleague chose Spring to implement the other app.

As I couldn't find a way to consume SOAP from NET Core, I kept stumbling upon WCF which is a technology still not supported by the NET Core.

My idea is to use docker compose to create two separate containers, where WCF will communicate over SOAP with the Spring web services, whereas the ASP.NET Core could communicate to WCF.

Is this viable or a good idea?

What would be your suggestion to solving this problem?

It is mandatory that the communication is based on SOAP. And mandatory to have two apps, my app will have to occassionaly sync its database with the one of the central.

TL; DR; ASP.NET Core and Spring apps communicating over SOAP. Can't do it?! WCF in the middle. May be a bad idea. How to design such a setting in docker compose.

Combining Net Core and WCF in Docker compose Click here
no image

Deploying IdentityServer 4 on IIS

Hey guys,So I'm trying to deploy an IdentityServer4 Authentication Server.I have deployed apps (that doesn't use X509Certificate).I've published my app it the IIS seems to be working but I can't communicate with it because of the SSL Certificate.My startup page class:

public class Startup { private IConfiguration Configuration { get; set; } public Startup(IHostingEnvironment environment) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.SetBasePath(environment.ContentRootPath); builder.AddJsonFile("appsettings.json"); builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { services.AddIdentityServer() .AddSigningCredential(new X509Certificate2( Configuration.GetSection("Addresses").GetValue<string>("RSA"), "password")) .AddInMemoryApiResources(InMemoryConfiguration.ApiResources()) .AddInMemoryClients(InMemoryConfiguration.Clients()) .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>(); services.AddTransient<IUserData, SqlUserRepository>(); services.AddDbContext<DbContextUser>(options => options.UseSqlServer(Configuration.GetConnectionString("MainServer"))); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseDeveloperExceptionPage(); app.UseIdentityServer(); app.UseStaticFiles(); } } 

Everything was working great on my computer.That's the logs I get from the appPool of my IdentityServer 4 app :

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0] User profile is available. Using 'C:\Users\swap.authserver.com\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. info: IdentityServer4.Startup[0] Starting IdentityServer4 version 2.4.0.0 info: IdentityServer4.Startup[0] You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation. info: IdentityServer4.Startup[0] Using the default authentication scheme idsrv for IdentityServer Hosting environment: Production Content root path: C:\SwapPublish\AuthServer Now listening on: http://127.0.0.1:27839 Application started. Press Ctrl+C to shut down. info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/1.1 GET http://localhost:5001/ info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] Request finished in 102.4928ms 404 

Everything seems fine.

When I send a request to get token (AKA URL https://localhost:5001/connect/token) I get this log from my API app :

 warn: Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository[50] Using an in-memory repository. Keys will not be persisted to storage. warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[59] Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits. info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[58] Creating key {2f6cbe8f-3454-4d1a-a4b7-d07cd2a593cb} with creation date 2019-05-19 17:59:53Z, activation date 2019-05-19 17:59:53Z, and expiration date 2019-08-17 17:59:53Z. warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35] No XML encryptor configured. Key {2f6cbe8f-3454-4d1a-a4b7-d07cd2a593cb} may be persisted to storage in unencrypted form. Hosting environment: Production Content root path: C:\SwapPublish\API Now listening on: http://127.0.0.1:33388 Application started. Press Ctrl+C to shut down. info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/1.1 POST http://vmedu184.mtacloud.co.il/user/signup text/plain;charset=UTF-8 83 info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Route matched with {action = "Signup", controller = "User"}. Executing action SwapExperimental.Controllers.UserController.Signup (Swap.Api) info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Executing action method SwapExperimental.Controllers.UserController.Signup (Swap.Api) - Validation state: Valid info: Microsoft.EntityFrameworkCore.Infrastructure[10403] Entity Framework Core 2.1.8-servicing-32085 initialized 'DbContextUser' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (5ms) [Parameters=[@__email_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30'] SELECT TOP(1) [user].[Id], [user].[CellPhone], [user].[City], [user].[Email], [user].[FirstName], [user].[LastName], [user].[Password], [user].[SignUpDate], [user].[Token] FROM [Users] AS [user] WHERE [user].[Email] = @__email_0 info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (1ms) [Parameters=[@p0='?' (Size = 4000), @p1='?' (Size = 4000), @p2='?' (Size = 450), @p3='?' (Size = 4000), @p4='?' (Size = 4000), @p5='?' (Size = 4000), @p6='?' (DbType = DateTime2), @p7='?' (Size = 4000)], CommandType='Text', CommandTimeout='30'] SET NOCOUNT ON; INSERT INTO [Users] ([CellPhone], [City], [Email], [FirstName], [LastName], [Password], [SignUpDate], [Token]) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7); SELECT [Id] FROM [Users] WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity(); info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] Executed action SwapExperimental.Controllers.UserController.Signup (Swap.Api) in 776.3644ms fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLMSGF60JMF7", Request id "0HLMSGF60JMF7:00000001": An unhandled exception was thrown by the application. System.AggregateException: One or more errors occurred. (The SSL connection could not be established, see inner exception.) ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host --- End of inner exception stack trace --- at System.Net.FixedSizeReader.ReadPacketAsync(Stream transport, AsyncProtocolRequest request) at System.Net.Security.SslState.ThrowIfExceptional() at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__47_1(IAsyncResult iar) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1 creationTask) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Swap.Api.Tools.AuthServerHttpClient.GetAccessTokenPack(User user) in D:\Programming Projects\Swap\SwapExperimental\SwapExperimental\Tools\AuthServerHttpClient.cs:line 39 --- End of inner exception stack trace --- at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at Swap.Api.Tools.AuthServerHttpClient.GetAccessToken(User user) in D:\Programming Projects\Swap\SwapExperimental\SwapExperimental\Tools\AuthServerHttpClient.cs:line 34 at SwapExperimental.Controllers.UserController.Signup() in D:\Programming Projects\Swap\SwapExperimental\SwapExperimental\Controllers\UserController.cs:line 43 at lambda_method(Closure , Object , Object[] ) at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsTContext ---> (Inner Exception #0) System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host --- End of inner exception stack trace --- at System.Net.FixedSizeReader.ReadPacketAsync(Stream transport, AsyncProtocolRequest request) at System.Net.Security.SslState.ThrowIfExceptional() at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__47_1(IAsyncResult iar) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1 creationTask) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Swap.Api.Tools.AuthServerHttpClient.GetAccessTokenPack(User user) in D:\Programming Projects\Swap\SwapExperimental\SwapExperimental\Tools\AuthServerHttpClient.cs:line 39<--- info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] Request finished in 993.7944ms 500 

btw, when I try to open my authserver in browser, I get this message saying :

https://i.redd.it/mma50lplj7z21.png

and if I try to open Exe file :

https://i.redd.it/0bj6lnjtj7z21.png

No idea why does it happen, Can anyone shed light?

Thank you.

Deploying IdentityServer 4 on IIS Click here
no image

Validation in Model or ViewModel

Supposing I have Model Course

//A few of the attributes

 [Key] public int CourseId { get; set; } [Required(ErrorMessage = "Course title is required")] [StringLength(100, MinimumLength = 3, ErrorMessage = "Course title must be between {2} and {1} characters long")] [DataType(DataType.Text)] [Display(Name = "Course Title")] public string CourseTitle { get; set; } [Required(ErrorMessage = "Course capacity is required")] [Display(Name = "Available places on course")] public int CourseCapacity { get; set; } 

Would I replicate this exactly in an AddCourseViewModel with the same Data Annotations?

My understanding is the ViewModel will pass the data to the Model (I plan on using AutoMapper), if the data is validated on the ViewModel does it still need validated again when its passed to the Model?

Also if no validation happens on the ViewModel that would mean someone could leave a required field empty? right?

Validation in Model or ViewModel Click here
Saturday, May 18, 2019
no image

TDD: How are you testing your callbacks in a pub/sub pattern?

I'm ramping up on TDD and created a basic test first. The issue I need help with is creating a test that verifies that a callback occurred and there is a specific data type in the callback.

The test I created looks like it should work, but when I run the test in debug mode the Test thread exits after setting the event handler. The WaitOne() call is never reached.

I was expecting the thread to remain alive in the Test method and wait at the WaitOne() call until the program under test fires the event using a Threadpool thread. How are you testing your callbacks? Any ideas on where I went wrong?

[TestFixture] public class Harvester { [Test] public void HarvestJobSites() { var waitTime = (int)TimeSpan.FromHours(2).TotalMilliseconds; var callbackEvent = new ManualResetEvent(false); bool isUpdated = false; var indeedHarvester = new IndeedJobHarvester(); indeedHarvester.Start(); indeedHarvester.OnCompletion += delegate(JobHarvestCompletionArgs args) { isUpdated = true; callbackEvent.Set(); Assert.IsNotNull(args.Jobs); Assert.That(args.Jobs.Count, Is.GreaterThan(0)); Assert.IsTrue(args.Jobs[0] is IndeedJob); }; if(!isUpdated) callbackEvent.WaitOne(waitTime); } } 
TDD: How are you testing your callbacks in a pub/sub pattern? Click here
no image

Best way for cross-platform reversible encryption

I am porting a library to .NET Core from Framework and the bit that I don't have a good answer for at the moment is credential storage for a backend API. I need to be able to store a large set of credentials with reversible encryption, modifiable by the consumer of the library. With classic .NET on Windows I used DPAPI with serialization to JSON. Is there a cross platform equivalent?

Best way for cross-platform reversible encryption Click here
The webdev Team