Friday, November 29, 2019

SharePoint framework webpart - ERR_SSL_PROTOCOL_ERROR

I was unable to view a newly created sharepoint framework webpart in Chrome browser and the error shown was

This site can’t provide a secure connection
localhost sent an invalid response.
Try running Windows Network Diagnostics.
ERR_SSL_PROTOCOL_ERROR

The only solution I could find for this problem was to change protocol of the local website from https to http.

Specifially, open serve.json file under config directory and set https = false, and initialPage = http://localhost:5432/workbench


{
  "$schema""https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
  "port"4321,
  "https"false,
  "initialPage""http://localhost:5432/workbench",
  "api": {
    "port"5432,
    "entryPath""node_modules/@microsoft/sp-webpart-workbench/lib/api/"
  }
}



If you know of any other way to fix this error without changing protocol, please do let me know.

More information can be found on this blog https://github.com/SharePoint/sp-dev-docs/issues/2343

Friday, November 22, 2019

Configure MVC app to receive and handle OPTIONS requests

Many of the frequently used http request methods are readily available from within MVC controllers. e.g, GET, PUT, POST, DELETE, etc.

However, there is also one important HTTP request method OPTIONS, which is sent before any CORS request to check if the request is allowed. This method is normally handled automatically by MVC framework, but if we ever need to handle it inside our controller, then add following tags to web.config


<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>

</system.webServer>



This is explained in detail at https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api



Wednesday, November 20, 2019

Azure Pipelines Error: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

An angular project deployed through Azure DevOps pipeline would throw this error in the release pipeline:




 ##[error]System.Management.Automation.MethodInvocationException: Exception calling "Transform" with "4" argument(s): "Could not load file or assembly 'System.IO.FileSystem, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified." ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.



The error was thrown in a 'Config transformation' task. I tried to install file system package using
Install System.IO.FileSystem -Version 4.0.1


in a Powershell task and also tried to install dot net framework 4.6 using

Install DotNetFramework.Runtime -Version 4.6.1

in a custom Nuget task, but both these methods didn't solve the issue.

Finally after going through the task history realized that the task was auto updated to latest version which has caused this issue.

So simply changing this task's version from 2.* to 1.* solved this problem. This behavior is kind of expected since a major version includes some breaking changes by convention.

Tuesday, November 19, 2019

MVC unobstrusive - validate only a single form control

I was trying to find articles detailing how to validate only a single form control using unobstrusive validation, but could not find one. So I digged in a little and found out that the following way works nicely. It may not be the most ideal solution for this problem though, so your suggestions are welcome.



var myForm = $('form');
var validator = myForm.data('validator');
var myValidator = new $.validator(validator.settings, myForm);
myValidator.check($('#myElement')[0]);
myValidator.showErrors();


The key part here is to call check method on a validator object, this method is an internal method so is not available on the default validator object. So I have created a new validator object and passed settings of existing validator objects to it. It is important to pass existing settings since they contain final validation message for each element after combining jquery default message and any custom messages from server side attributes.


Friday, November 15, 2019

MVC validate a model using data annotation attributes without model binding

Sometimes, we need to validate a data model without model binding. For example, if the application has separate models for the actual data entity and an action method such as edit action in a view. In such cases, it would be very convenient to use data annotation attributes already specified on the model to perform validation logic.


This can be achieved by using ValidationContext and Validator objects, like so:


 var widget = new Widget
                        {
                            Id = 12,
                            Price = 15.57M
                        };

        var context = new ValidationContext(widget, null, null);
        var results = new List<ValidationResult>();
        if( Validator.TryValidateObject( widget, context, results, true ) )
        {
            //Validation Successful
        }
        else
        {
            //Validation Failed
        }


More information can be found at https://stackoverflow.com/questions/7101800/can-i-check-modelstate-without-modelbinding

Thursday, November 14, 2019

Preventing overposting attacks in MVC


An mvc website can have seriously compromised security if it is not carefully defended against overposting attacks. Attackers can over post request data if controller actions use some sort model binding.

More information about these attacks and how to defend against them can be found at

https://andrewlock.net/preventing-mass-assignment-or-over-posting-in-asp-net-core/

Thursday, November 7, 2019

c# Custom List validation attribute

By default, MVC model binder validates each object before assigning properties, including each object in a list.

However if we want to implement a custom validation attribute (using DataAnnotations), and use  Validator.TryValidateObject mehtod, this can get bit tricky, since it does not recursively validate 'properties of objects returned by properties'.

What is means it assuming I have class A defined as:

        class A
        {
            [Required]
            public string name;
        }


And class B defined as:

        class B
        {
            [Required]
            public List<A> myPropertyList;

        }

Then calling Validator.TryValidateObject on an object of will validate if myPropertyList inside the object has a value, but it will not validate if each object in the myPropertyList has a name assigned.



There are several solutions to this problem.

1) For an IEnumarable use custom validation attribute IsValid method convert myPropertyList to a IEnumarable  then enumerate through each object in the list and call Validator.TryValidateObject method on the object, finally combine all the result to get the error messages. This is explained at https://stackoverflow.com/questions/51523346/validating-lists-in-c-sharp


2) TryValidateObject method would also ignore validation attribute of name in class A if it is not a list, but a single object


e.g. given that I have

        class C
        {
            [Required]
            public string name;
        }

        class D
        {
            [Required]
            public A myProperty;

        }
e.g. given that I have e.g. given that I have e.g. given that I have e.g. given that I have 


TryValidateObject again won't validate that name is not empty if called on an object of class D. In such a situation a custom validation attribute can be assigned to myProperty which can do this task and aggregate the results. This is explained at http://www.technofattie.com/2011/10/05/recursive-validation-using-dataannotations.html

3) Implement IValidatableObject interface at the top level class and iterate through each property recursively to validate it.

4) There is also in interesting article for client side validation at https://stackoverflow.com/questions/23337170/data-validation-for-every-item-in-a-list-of-my-viewmodel

Sunday, November 3, 2019

Powershell - Organize media files based on creation date

In windows media files like jpg, mp4 or mov have properties called as extension attributes which record their creation date in addition to the regular creation and modified date properties. When we copy of move files to some other location, the regular created date and modified date properties are changed, but not so with the extension attributes. Thus the extension attributes record  correct timestamps.

I found a handy powershell script which can be used to organise media files based on their extension attributes. This script can be found at http://todd.ropog.com/organize-media-files-with-powershell/

Saves us a lot of time while taking backups :)

c# httpclient The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

 If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remo...