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
Read More
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
Read More
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
Read More
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
Read More
Wednesday, May 22, 2019
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
Read More
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
Read More
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
Read More
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
Read More
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
Read More
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
Read More
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
Read More
The webdev Team