ozzy432836
ozzy432836
Dev Blog
47 posts
ZmFtaWx5LCBwYXJrcywgaGVhdG9uIHBhcmssIGZvb3RiYWxsLCBneW0sIHBpYW5vLCBzY290dCBqb3BsaW4sIGNodXJjaCwgYmlibGUsIGNyZWF0aW9uLCB1bml2ZXJzZSwgc2NpZW5jZSwgeGJveCwgR1RBLCBOYW5kb3MsIGNoaWNrZW4sIHN1YndheSwgSXRhbGlhbiBCTVQsIE1jRG9uYWxkcywgUGFuYW1hIEhhdHR5cywgbW92aWVzLCBjaW5lbWEsIGNvZGluZywgY29tcHV0ZXJzLCBlbGVjdHJvbmljcywgRElZLCB0aGUgc2ltcHNvbnMsIEFyc2VuYWwsIDI0LCBjYXJzLCBlbmdpbmVz
Don't wanna be here? Send us removal request.
ozzy432836 · 7 years ago
Text
Software Dev ViewModels and DTOs
My understanding of ViewModels and Dtos
Consider a simple application that consists of:
A front end coded in some JS Framework (Angular). The backend is coded in some server side language (Asp.Net Core - latest). The backend stores data in some database (MSSQL) using some ORM (Entity Framework or Dapper). The system also uses Slack to live log everytime a user logs into the system to the developers can panic.
When a user logs in, they see their profile which consists of
FirstName LastName Email RegNumber
To our application, this is a ViewModel (UserProfile) as its a representation of how the front end wants users to see data.
UserProfileViewModel FirstName LastName Email RegNumber
It means nothing to our core domain models as its just a representation of one or more database tables.
When a user edits their profile, they will post a UserProfileViewModel object to some controller method.
The controller splits the object up as its going to store different parts in different tables.
For example the controller will do something like this when it receives a post on the edit profile method.
User currentUserDetails = _myDatabase.Users.First(u => u.Email === incomingProfile.Email); currentUserDetails.FirstName = incomingProfile.FirstName; currentUserDetails.LastName = incomingProfile.LastName;
Vehicle currentUserVehicleDetails = _myDatabase.Cars.First(c => c.UserId == currentUserDetails.UserId); currentUserVehicleDetails.RegNumber = incomingProfile.RegNumber;
_myDatabase.SaveAndComplete();
In order to accomplish this, Entity Framework has created objects (User and Vehicle) to model the database and the controller has the code to extract what it needs from the ViewModel and update as many tables as it wants.
The ViewModel can also contain custom fields and a method to format it for VIEWING purposes only. For example:
FirstName LastName Email RegNumber
FullName*
void SetFullName() {  FullName = $"{FirstName} {LastName}" }
So the front end can quickly access a full name without having to do any logic (this entirely depends on how much business you prefer to put in the front end Full name is a simple example. It becomes more complex when you have real logic going in the front end).
The system was also meant to post to Slack.
Now Slack is basically another database across a different media to the SQL Server.
In MSSQL, EF dealt with creating a model to map the way the database expects the data to look before inserting data.
We dont have that luxury with Slack. SO, we create a DTO
SlackPostDto Title Body Icon
SlackPostDto sp = new SlackPostDto {  Title = $"{incomingProfile.FullName} logged in";,  Body = $"They have a car with reg number ${RegNumber}";  Icon = "LoginDoor" };
_slackHandler.Post(sp);
0 notes
ozzy432836 · 8 years ago
Text
Install SSL for free - Server 2016 IIS 10.x.x
To begin with, this probably works on earlier versions of IIS and Windows Server but this was the environment I used on the day I finally accomplished what seemed to be an impossible/costly task.
Let me remind you that you should probably just buy an SSL cert for your business ventures from Comodo for example. I used them in the past and the setup was a breeze. However, if you are developing an idea / you are a start up / you are just plain tight with cash then this post should help you.
Go to https://www.sslforfree.com
Enter domain(s) to be secured here.
You can enter [space] separated domains so it may be a good idea to think of all your sub domains and do them in one order.
Tumblr media
Click “Create Free SSL Certificate”
In the next frame, click “Manual Verification”. You can use the other two options as well but I am not covering those in this post.
Then click the smaller Manual verification button (green below)
Tumblr media
Download all the verification files highlighted in red.
In reality, your sub domains could be targeting different sub directories on your web server but I found it easier to initially point all my domains to the same site.
This helps because you can drop all the files you downloaded above into the same directory just for verification purposes.
In my example, I dropped them all into C:\inetpub\wwwroot.well-known\acme-challenge
To make it easy for you, clone this repo https://github.com/ozzy432836/Free-SSL-Windows-IIS into C:\inetpub\wwwroot
Note the web.config included has been setup to allow the reading of static content.
Copy the downloaded verification files into your newly created directory  C:\inetpub\wwwroot.well-known\acme-challenge
You should test that you can access the files via your browser by clicking the links provided by the SSL For Free site (second box highlighted in red below).
Tumblr media
Assuming you can successfully navigate to those links in your browser, scroll further down and click “Download SSL Certificate”
The download will fail if you were not able to navigate to the test links in your browser.
You should have a downloaded zipped folder at this stage. Unzip it and you should find 3 files inside.
certificate.crt
ca_bundle.crt
private.key
This is the bit where I am hacking two SSL Free tools together.
Included in your download is a StartComTool.exe. If you don’t trust my downloaded file then grab it from here https://www.startssl.com/Account but you have to create an account and sign up first. It is another free SSL service but I could not get theirs working.
Using the StartCom Tool, you will be able to generate a .pfx file.
Run the .exe and click “Certificate”
Tumblr media
Browse for your cerificate.crt and your private.key files
Select export PFX
Click submit
Another file should have appeared in your downloaded cert files folder. It should end with .pfx.
Now all you have to do is import this file into IIS.
You can achieve this by going to your root server (1) in IIS and then clicking on “Server Certificates”.
In the next screen, click “Import” (2) and then browse for the .pfx file you just generated (3). Leave the password blank, choose “Personal” for the Certificate store, tick the check box and select OK.
Tumblr media
Your certificate should now show in the Server Certificates List and you can assign it to a https binding on any of your sites.
2 notes · View notes
ozzy432836 · 8 years ago
Text
A very scattered C# post
Reflection
Mutable - can change, immutable - cannot change string is immutable - you actually create a new string when you append etc StringBuilder is physically modified when you append so its cheaper on memory
For everything, research pros and cons
Angular + very declarative, you know what element is bound to what as its clear in markup -everything has ng- in jQuery, it uses CSS selectors and you may not always be clear what is going where... + Directive can manipulate the DOM
Incremental Database Backups
Automated Testing, Automated Deploying
Factory Pattern
Repository Pattern
Red Green Refactor
SOLID Principles: http://www.codeproject.com/Articles/703634/SOLID-architecture-principles-using-simple-Csharp
S rp Single Responsibility Principle - ensure your classes are used for single responsibilities e.g a class person can have methods to add, remove, update, delete people - however dont sneak things in there like SendEmail and hasAccessTo
O cp Open Closed Principle - once you have written a class and deployed it, dont make changes to it if a new feature is required - extend it instead
L sp Liskov Substitution Principle - Personalised Prospectus Application is not a student yet it is  just a lead - however it is saved to the database as a person -
I sp Interface Segragation Principle - similar to OCP - a good example is INEwsCollection which must implement getNewsCollection - if you decide that a new INewsCollection consumer needs a checkNewsCollection method - dont add the method to INewsCollection because you will have to implement in MoodleForumNewsCollection and TestNewsCollection - extend the INewsCollection with INewsCollectionVerifed and your new class should implement the INewsCollectionVerified
D ip Dependency Inversion Principle - IOC sits above:Service Locato, Events, Delegates and DI (Dependency Inversion OR Injection?) - have implemented by inverting control of which db connector to load to a DBConnector class - an early example https://onedrive.live.com/?cid=289FADB32C0AB5D3&id=289FADB32C0AB5D3%2138959 (demonstrates my thinking) - have implemented this using IOC for databases where you dont know which database you will need till runtime so I used polymorphism to call methods from the parent class yet I passed the child class in to call the method - however to really implement this, you combine with SRP and dont create different instances of the interface implementor when you get into your class, inject the Interface in through the constructor, method or property
http://prodinner.aspnetawesome.com/ ASP.NET MVC Ajax
Static Classes: Really just a bucket of methods (somewhere to store things that dont belong to objects). If you declare
fields/properties in here at class level then you must make them static to be accessible in a static method.
Abstract class: Model something in a type hierarchy e.g. Vehicle is abstract and all children must inherit it and implement its methods
(almost like an interface but you can code the methods or choose not to).
Polymorphism: A collection can only hold people. You can add an employee or a student...so long as it is derived from class people.
Overloading: Multiple methods, same name, different arguments.
Overriding: Multiple methods, same name, same arguments. Use in child to override parent method. Its the same as overriding in Java
except you have to use the keyword...
Virtual keyword on method: this revolves around overriding parent methods The virtual modifier tells the compiler that when any class derived from class A is used, an override method should be called. So the child should use the override keyword
virtual keyword on property
Indexer
Multi threading:
Race condition: Occurs in multithreading - when two threads access a shared variable at the same time. The first reads the var and the
second reads same value. They then both perform their operations on the value and they race to see which can update the value last.
Whichever thread writes last wins.
Deadlock - stalemate: two threads lock different variables then try to lock the variable that is already locked by the other thread. So they both wait till each other is free before continuing. Stalemate!
Struct: a lightweight class - use when you just want to structurally store a collection of objects. Its like new stdClass in PHP (but more organised). Its better than creating a dictionary and assigning kvps to store your lightweight collection as i have done in the past. They have limitations compared to classes and you would normally use a class. Classes are reference types while struct are value type objects. If passing a struct in place of an object, you must use the ref keyword to tell the method that the variable should be populated by reference and not value.. Only use if there is a specific need to pass an object by value and not reference.
Enum: you have a set of constants that will never change. e.g. sun - sat, jan - dec. You can declare these at namespace level so it can
be used by all classes. By default, the type of items in list are ints but these can be any primitive type except char
Delegate: used to treat a method like an object. I dont think it has any real use in the example I saw http://aspnetcentral.com/aspnet45/expert/video/0410%20Understand%20delegate%20methods.html
Fields: are basically what you thought were variables. These should be accessed via getters and setters because they abstract the  field and allow you to make change...tbc
Properties: are the way you declare variables in Models with the get; set; They expose fields
Using {} - use this whenever: The using statement is only useful for objects with a lifetime that does not extend beyond the method in which the objects are constructed. Remember that the objects you instantiate must implement the System.IDisposable interface. E.G SQLConnection
FluentValidation is an alternative to data annotations. Some feel it is easier to read and maintain. http://stackoverflow.com/questions/16678625/asp-net-mvc-4-ef5-unique-property-in-model-best-practice In the example i studied, it felt like writing unnecessary code e.g. making a field unique...
Boxing: int x = 1; object y = x; Unboxing: y = 1; x = (int)y; The above work with casting when unboxing and generalisation (almost polymorphism) when boxing
hash region: allow you to collape blocks of code in long code and add a description so you know what each region is for
hash pragma: use to disable warnings and reenable later on
Yield:
Technical Debt: When you make a change, there is often other changes to make in other parts to ensure the integrity of your application. These other changes are called debt.
Use of interfaces:
IDisposable: a way to dispose of unmanaged resources - used most for db connections and talking to db via EF. Use if you are directly accessing an unmanaged resource
IEnumerable vs ICollection
Repository pattern: Why?
Internal keyword vs private http://stackoverflow.com/questions/3813485/internal-vs-private-access-modifiers
IOC - passing the decision making away from the class to an external entity e.g. constructor should not decide which database type to instantiate. You can use DI to implement IOC. You can also use delegates, events, and service locators https://www.facebook.com/video.php?v=690253231015623
DI - Dependency Injection
Know your versions: Visual Studio: 2013 (v12) - help about ASP.NET: 4.5 - search targetFramework in web.config C# : 5 MVC: 5 - search system.data.mvc in web.config EF: 6 - search system.data.entity in web.config
0 notes
ozzy432836 · 8 years ago
Text
Builder Pattern
An example of this in unit testing is var mockUsers = new Mock(); mockUsers .Setup(m => m.getUsers()) .Returns(new List);
0 notes
ozzy432836 · 9 years ago
Text
ASP.NET Core web api subtle differences
https://wildermuth.com/2016/05/10/Writing-API-Controllers-in-ASP-NET-MVC-6
0 notes
ozzy432836 · 9 years ago
Text
ASP.NET Web API JWT Authentication
http://bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/
0 notes
ozzy432836 · 9 years ago
Text
Full Stack Developer
I feel this (at the moment) can be a good summary of becoming full stack.
Design your database in your chosen environment.
Create web services using your favorite back end server side language e.g. Yii, Laravel, Rails, Django, ASP.Net Web API2, or NodeJS if you are brave. These will pretty much CRUD your database.
Consume your web services with Angular2 on the front end https://www.youtube.com/watch?v=Zkesm9CUP_o&list=PLPCoRccv3E8UuctPlTYMWZ-Xr3g1cQj25
Tidy it all up with a nice theme http://html5up.net 
Badabing badaboom you’re a full stack dev!
Next, try to re-do it using other server side languages. If you already know a server side language like ASP.Net or Rails, etc, I suggest you challenge yourself and use NodeJS
Then watch some of these https://cleancoders.com and learn to write better code.
0 notes
ozzy432836 · 9 years ago
Text
C# what to do when you cant Mock a static extension method
Turn to delegates! http://adventuresdotnet.blogspot.co.uk/2011/03/mocking-static-methods-for-unit-testing.html
See option 2.
0 notes
ozzy432836 · 9 years ago
Text
IIS Auto create site and app pool from batch file
One to try later
This is specific to wordpress but you can change your path names, etc
SET mypath=%~dp0 SET mypath=%mypath:~0,-1%
%systemroot%\system32\inetsrv\appcmd.exe add apppool /name:"Phalanger v3.0"
%systemroot%\system32\inetsrv\appcmd.exe set apppool "Phalanger v3.0" /managedRuntimeVersion:v4.0 /managedPipelineMode:Integrated
%systemroot%\system32\inetsrv\appcmd.exe add app /site.name:"Default Web Site" /path:/wordpress /physicalpath:"%mypath%" %systemroot%\system32\inetsrv\appcmd.exe set app /app.name:"Default Web Site/wordpress" /applicationPool:"Phalanger v3.0"
Later that year...
See attached...GRRR forgot you cant do that here...will have to wait till my website is up...
0 notes
ozzy432836 · 9 years ago
Text
TFS Adding Additional State
http://blogs.msdn.com/b/visualstudiouk/archive/2013/01/19/adding-additional-states-onto-the-agile-task-board-in-tfs2012.aspx
Thanks Frank - dunno where you are on twitter!
0 notes
ozzy432836 · 9 years ago
Text
ASP.Net ApplicationUserManager send email
Play with this later (App_Start / IdentityConfig.cs)
manager.EmailService.SendAsync(new IdentityMessage() {Body = "", Destination = "", Subject = ""});
0 notes
ozzy432836 · 9 years ago
Text
Go JS
Nice Javascript examples for real life problems
http://gojs.net/latest/index.html
0 notes
ozzy432836 · 9 years ago
Text
C# compare two objects
This method will help you compare any two objects or even a list of objects.
http://stackoverflow.com/questions/10454519/best-way-to-compare-two-complex-object/34898756#34898756
0 notes
ozzy432836 · 9 years ago
Photo
Tumblr media
Logo
0 notes
ozzy432836 · 10 years ago
Text
C# Partial Class vs Extension Method
Some of differences that will determine whether you want to use a Partial Class or an Extension Method are
Partial Class
Only works against classes in the same project/assembly
Target class has to be marked as partial
Has access to the Target class' fields and protected members
Target must be a class implementation
Extension Method
Can be applied against classes in other assembles
Must be static, has access to only the Target classes public members
Target of extension can be a concrete type, or an abstract type or interface
http://stackoverflow.com/questions/6017673/partial-class-vs-extension-method#answer-6017759
0 notes
ozzy432836 · 10 years ago
Text
C# DI/IOC. That moment when you cant pass an Inteface through the constructor.
Tumblr media
Ok so I managed to pull ConfigurationManager.AppSettings[key]; out into an interface because my test could not access web.config to load a string.
Brilliant (I thought), I was able to mock the IConfiguration like so:
public class PortalConfiguration : IConfiguration {   public string GetAppSetting(string key)   {     return ConfigurationManager.AppSettings[key];   } }
then in my unit test:
_mockConfiguration = new Mock<IConfiguration>();
_mockConfiguration   .Setup(m => m.GetAppSetting(It.IsAny<string>()))   .Returns("http://localhost:8090");
which worked because previously, the method I was testing had a hard coded
ConfigurationManager.AppSettings[key];
in it - which was null - so the test failed.
Now I had a passing test and felt good.
Then I tried to run my application and it crashed because I had to inject a concrete IConfiguration (using StructureMap) into a class at runtime.
This is what caused the problem:
public Startup(IConfiguration configuration) {   _configuration = configuration; }
I could not modify the caller of this class becuase it lived beyond my code somewhere in the .NET framework.
So I did this instead:
public Startup() {   // cannot pass IConfiguration through ctor because   // the core/metadata expects an empty constructor   _configuration = IocConfig.Setup().GetInstance<IConfiguration>(); }
Which essentially does the same thing - it asks my DI Container for which concrete implementation to use (just as it would do if I could have used the code that caused the problem.
If you know another way in which I could have accomplished this, do share.
0 notes
ozzy432836 · 10 years ago
Text
Resharper 9.2 does not work with NUnit 3
  Development - Resharper and NUnit
Upgrading NUnit from 2.6.4 to 3.0.0 via the PM Console
Here are the steps I took that concluded in what is the title of this post.
Install-Package NUnit Install-Package NUnit.Runners  - this is just a reference to NUnit.Console  - one would think that it would be better to just type    Install-Package NUnit.Console    instead of    Install-Package NUnit.Runners      - however, that doesnt appear to be the way Nuget wants it done...it does work though...!
ReSharper >> Options >> Tools >> NUnit  - Select "Specified NUnit Installation"  - Browse to the path that contains:    1. nunit.core.dll    2. nunit.core.interfaces.dll    3. nunit.util.dll
Tip: when you typed Install-Package NUnit in the PM Console, it would have printed a path to the console. This is where you should be looking.
ReSharper 9.2 warns you that NUnit versions 2.5.8 to 2.6.4 are supported. Newer versions could work but no guarantee. I could not find file(3) anywhere. I tried copying the version 2.6.4 of file(3) into the dir and it saved but tests still didnt run.     Conclusion: Resharper 9.2 doesnt work with NUnit3 Roll back to 2.6.4 if you want it to work or use NUnit with the VisualStudio Test Explorer
0 notes