MVPS HOSTS File Update February-08-2016

The MVPS HOSTS file was recently updated [February-08-2016]
http://winhelp2002.mvps.org/hosts.htm

Note: Windows 10 users … the HOSTS file installs with no issues …

Download: hosts.zip (132 kb)
http://winhelp2002.mvps.org/hosts.zip

How To: Download and Extract the HOSTS file
http://winhelp2002.mvps.org/hosts2.htm

HOSTS File – Frequently Asked Questions
http://winhelp2002.mvps.org/hostsfaq.htm

Note: the “text” version (497 kb) makes a great resource for determining possible unwanted connections …
http://winhelp2002.mvps.org/hosts.txt

Get notified when the MVPS HOSTS file is updated
http://winhelp2002.mvps.org/updates.htm

If you find the MVPS HOSTS file useful … please consider a donation …
http://winhelp2002.mvps.org/hosts.htm#donation

How to Manually Start or Stop Automatic Maintenance in Windows 10

Automatic Maintenance is when Windows automatically runs maintenance on a daily schedule when you’re not using your computer.

This includes tasks such as software updates, Windows Updates, security scanning, and system diagnostics. This maintenance will run daily if you aren’t using your computer at the time you’ve chosen. If your computer is in use at the scheduled time or maintenance is behind schedule, Automatic Maintenance will run the next time the computer is not being used.

The goal of Automatic Maintenance is to combine all background maintenance activity in Windows and help third-party developers add their maintenance activity to Windows without negatively impacting performance and energy efficiency. Additionally, Automatic Maintenance enables users as well as enterprises to be in control of maintenance activity scheduling and configuration.

This tutorial will show you how to manually start or stop Automatic Maintenance on demand in Windows 10.

Read more…

Entity Framework Pitfalls: Attaching New Entities With Existing Related Ones

One of the patterns in EF 6.x for attaching new entities to a context is to simply change it’s state to Added:

ctx.Entry(myEntity).State = EntityState.Added;

Entity Framework 6.x will traverse the entity graph of all the related entities and set all their states to Added too. This might be a problem.

Imagine we want to attach a disconnected (new) entity that is linked to an existing one, for which we already have a reference. In this case, we don’t want this reference to be added, because doing so will raise a violation on the database and it will come out as an exception.

What we need to do is to explicitly set the state of any of these existing instances to Unchanged. Fortunately, Entity Framework Core will solve this with the introduction of a new TrackGraph API.

Thanks for Tony Sneed (@tonysneed) for reminding me.

Resoluciones del Nuevo Mes: Febrero 2016

De nuevo es tiempo de escribir las nuevas resoluciones, primero repaso de las de enero:

– Trabajar en mejorar los ejemplos de trader de SimpleGA [pendiente]
– Trabajar en SimpleDatabase [pendiente]
– Trabajar en SimpleMemolap [completo] ver repo
– Trabajar en Memolap [completo] ver repo
– Mejorar AjGenesisNode [pendiente]
– Mejorar SharpGo [completo] ver repo
– Mejorar Husky [completo] ver repo
– Trabajar en GoLin [completo] ver repo

También estuve trabajando en:

– Crear SRedux, una librería similar a Redux [completo] ver repo
– Crear ImmuO, objetos immutables en JavaScript [completo] ver repo
– Comenzar CrysSharp, lenguaje de programación Crystal implementando en C# [completo] ver repo
– Comenzar CrysJS, lenguaje de programación Crystal implementado JavaScript [completo] ver repo
– Agregar ejemplos ReactJS a los ejemplos de JavaScript [completo] ver repo
– Mejorar ElixirJS [completo] ver repo
– Crear ReduMan, manejador de reducers en JavaScript [completo] ver repo
– Crear RkStreams, streams reactivos en JavaScript [completo] ver repo

Mis nuevas resoluciones:

– Mejorar AjGenesisNode-Express
– Trabajar en CrysJS
– Trabajar en CrysSharp
– Trabajar en Memolap
– Trabajar en SimpleMemolap
– Mejorar mis ejemplos de SimpleGA
– Mejorar SharpGo
– Mejorar Husky
– Trabajar en GoLin
– Mejorar ImmuO
– Más ejemplos ReactJS
– Mejorar Aktores
– Mejorar ErlSharp

Me diviegto como logco 😉

Nos leemos!

Angel “Java” Lopez
@ajlopez

How to Enable or Disable Automatic Maintenance in Windows 10

Automatic Maintenance is when Windows automatically runs maintenance on a daily schedule when you’re not using your computer.

This includes tasks such as software updates, Windows Updates, security scanning, and system diagnostics. This maintenance will run daily if you aren’t using your computer at the time you’ve chosen. If your computer is in use at the scheduled time or maintenance is behind schedule, Automatic Maintenance will run the next time the computer is not being used.

The goal of Automatic Maintenance is to combine all background maintenance activity in Windows and help third-party developers add their maintenance activity to Windows without negatively impacting performance and energy efficiency. Additionally, Automatic Maintenance enables users as well as enterprises to be in control of maintenance activity scheduling and configuration.

It is recommended to leave Automatic Maintenance enabled, but sometimes you may wish or need to disable it.

This tutorial will show you how to enable or disable Automatic Maintenance as needed in Windows 10.

Read more…

How to Enable or Disable TRIM Support for Solid State Drives (SSD) in Windows 10

The TRIM command is essential to maintain the performance of solid state drives (SSDs) at an optimal level over the lifetime of the drive. TRIM functions by actively deleting invalid data from the SSD’s memory cells to ensure that write operations perform at full speed. Since a memory block must be erased before it can be re-programmed, TRIM improves performance by pro-actively erasing pages containing invalid data, allowing the SSD to write new data without first having to perform a time-consuming erase command.

TRIM support for SSDs is enabled by default, and is recommended to always keep TRIM support enabled. If disabled, you risk the SSD getting defragged instead of optimized (TRIM).

This tutorial will show you how to check the current status of TRIM support for SSDs, and to enable or disable TRIM support for NTFS and ReFS file systems for all users in Windows 10.

Read more…

Documenting Web APIs with Swagger

A while back I posted an article on how to extend the existing help pages generated by Visual Studio for Web API projects to use reflection instead of XML documentation. One of the limitations of that approach was that you could not test the APIs directly. You had to use SoapUI or equivalent. Since then I have started using Swagger for documentation. As a documentation/testing tool it fills the need. In this article I will demonstrate how to integrate Swagger into a Web API project. Additionally I will continue to use the reflection provider from the previous article.

What is Swagger

Swagger is a popular, open source specification for REST APIs. I first ran across it when I noticed the Add REST Client option in Visual Studio 2015. Clicking that button gives you the option of reading a REST specification from Azure or Swagger and generating a REST client for it. By itself Swagger simply defines an API using a JSON format. Starting this year it is formally known as the OpenAPI Specification. You can read it if you like but really there is no reason to get into the gory details. There are plenty of editors available that allow you to import an existing API and generate the OpenAPI specification for it. There is a web-based one here. I prefer one that allows me to import .NET assemblies so I use NSwagStudio. But for purposes of this article I want to focus on generating the specification from the code on demand.

Swagger is language agnostic (it is just a specification) so to use it you must acquire the tools for your language of choice. For .NET and Typescript (the most likely targets of Windows hosts) NSwag is the core library you will need. Additionally you will likely want some sort of tool to generate the OpenAPI specification file. For this article we be doing it programmatically but having an editor like one of the tools mentioned earlier is useful for seeing the specification. Another tool that you will likely want is a client generator. Visual Studio 2015 has an option to generate a REST client from an OpenAPI specification. NSwagStudio has similar options to generate a .NET or Typescript client for you as well.

Integrating Swagger Into a Project

To get started create a new Web API project. For this article we only need Web API but it will automatically add an MVC area for help. This is the page we talked about previously. Go ahead and delete the area as we won’t need it. We now need to add in the NuGet packages to support Swagger. Since Swagger is evolving it is confusing to determine which implementation to get. For this article I’ll use Swashbuckle. Use Package Manager to download it. It comes with both the libraries need to generate documentation but also a UI we’ll talk about later. The package does a couple of things. Firstly it creates a new file called SwaggerConfig.cs in your App_Start folder. This is the file you’ll use to configure Swagger later. The second thing it does is set up a route so that you can access the specification. To make this a little more meaningful
we’ll swap out the simple controller provided in the sample with a more complex one.

public class ProductController : ApiController
{
    static ProductController()
    {
        s_products.AddRange(new[]
        {
            new Product() { Id = 1, Name = "Product A", Price = 100.0M },
            new Product() { Id = 2, Name = "Product B", Price = 50.0M },
            new Product() { Id = 3, Name = "Product C", Price = 25.0M },
        });
        s_id = 3;
    }
        
    public IEnumerable Get ()
    {
        return s_products;
    }
    
    public Product Get ( int id )
    {
        return s_products.FirstOrDefault(p => p.Id == id);
    }
    
    public Product Post ( [FromBody]Product value )
    {
        var newProduct = new Product()
        {
            Id = ++s_id,
            Name = value.Name,
            Price = value.Price
        };
        s_products.Add(newProduct);
        return newProduct;
    }
    
    public void Put ( int id, [FromBody]Product value )
    {
        var product = Get(id);
        if (product != null)
        {
            product.Name = value.Name;
            product.Price = value.Price;
        } else
        {
            Post(value);
        };
    }
    
    public void Delete ( int id )
    {
        s_products.RemoveAll(p => p.Id == id);
    }
    private static List s_products = new List();
    private static int s_id;
}

Now that Swagger is installed go ahead and run the application and go to the URL ~/swagger/docs/v1 (by default). This returns back the JSON for the API and is how a UI or client generator will get the specification. Navigate to ~/swagger/ui/index and you should be able to see a UI that renders the JSON. More importantly all the API actions should be available and they can be executed. This is useful for learning the API and for testing.

Configuring Swagger

We have some control over the specification using the EnableSwagger method. The first thing I want to change is the URL for the specification. The default URL is not intuitive to me so I’ll change it to ~/help/docs/v1. The version is important if you will have multiple versions of your API. Everything else is personal opinion. Swagger supports multiple versions but you need to cnfigure the URL such that Swagger can specify the version correctly.

.EnableSwagger("help/docs/{apiVersion}", c => 
{
    //Do not include actions marked obsolete
    c.IgnoreObsoleteActions();
    //Include any XML documentation
    c.IncludeXmlComments(GetDocumentationPath());
    //Ignore properties marked obsolete
    c.IgnoreObsoleteProperties();	
}

The GetDocumentationPath method returns back the path to the site bin directory where the XML files are generated by default.

private static string GetDocumentationPath ()
{
    return Path.Combine(HttpRuntime.BinDirectory, "SwaggerDemo.xml");
}  

There are other options available including security, injecting additional styling and changing how operations and types are generated.

UI

Swashbuckle includes Swagger.UI which is a simple UI for allowing you to browse the API and, more importantly, test it. Browse to ~/swagger and it will redirect you to the UI where you can view and test the exposed APIs. Under the hood it is using the specification from the API controller to expose the information. I personally don’t like the defaults so we’re going to change them. Firstly I would prefer that the URL doesn’t mention Swagger and instead is more meaningful so open the SwaggerConfig file and find the call to EnableSwaggerUI. The code is pretty well commented to allow you to configure the UI settings. For our purposes we’ll modify the call to pass a string as the first parameter. The string is the URL we want to use.

.EnableSwaggerUi("help/ui/{*assetPath}", c =>

This will change the URL to simply ~/help/ui. For projects that have no MVC controllers (like this one) it makes sense to simply send the user to the documentation so also modify the home controller to redirect to the help instead of showing a default view.

public ActionResult Index ()
{
    return RedirectPermanent("~/help/ui/index");
}

Notice the index at the end. That is the asset path that was in the earlier URL. We can configure other aspects of the UI as well if we want. For my purposes I don’t want the validators to run and I want the operation list to start expanded.

.EnableSwaggerUi("help/ui/{*assetPath}", c => 
{
    //Do not use online Swagger validation
    c.DisableValidator();
    //Expand the list of operations by default
    c.DocExpansion(DocExpansion.List);
}

Swashbuckle provides us a limited set of options to change. If you want to change other options in the UI then you either need to hack the code or use a different UI altogether.

Documenting the APIs

Out of the box Swagger will use the XML documentation that can be generated by your assemblies. Basically all you need to do is add summary, param, returns and optionally remarks comments to the API controllers, actions and models and you have instant documentation. The downside to this approach is the same as discussed in the earlier article on documenting Web API calls. Therefore I want to port the ReflectionDocumentationProvider from the earlier code over to Swagger. This is actually pretty easy since all the hard work is already done. All we have to do is implement 2 methods. The hard part is knowing what OpenAPI expects. The first thing we need to do is update the interface list for the type. IDocumentationProvider is still valid but IModelDocumentationProvider is replaced by IModelFilte and we add IOperationFilter. The new interfaces each have a single method that simply asks for the documentation for the operation or model, accordingly.

public class ReflectionDocumentationProvider : IDocumentationProvider, IOperationFilter, IModelFilter
{
    public void Apply ( Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription )
    {
        operation.summary = GetDocumentation(apiDescription.ActionDescriptor);
        
	//Parameters
        if (operation.parameters != null)
        {
            foreach (var parameter in apiDescription.ParameterDescriptions)
            {
                var opParam = operation.parameters.FirstOrDefault(p => String.Compare(p.name, parameter.Name, true) == 0);
                if (opParam != null)
                    opParam.description = GetDocumentation(parameter.ParameterDescriptor);
            };
        };
        
	//Return value
        if (apiDescription.ActionDescriptor.ReturnType != null)
        {
            operation.responses.Clear();
            operation.responses["200"] = new Response()
            {
	            description = GetResponseDocumentation(apiDescription.ActionDescriptor),
                schema = new Schema()
                {
                    @ref = apiDescription.ActionDescriptor.ReturnType.FullName
                }
            };
        };
    }
    
    public void Apply ( Schema model, ModelFilterContext context )
    {
        model.description = GetDocumentation(context.SystemType);
    
	//Properties
	model.properties.Clear();
        foreach (var property in context.SystemType.GetProperties())
        {
            model.properties[property.Name] = new Schema()
            {
                description = GetDocumentation(property)
            };
        };
    }
}

For operations we use reflection to get the description associated with the action. For each parameter and the return value we do the same thing. For models (types) we follow a similar approach except we look at the properties. In the previous article I used the standard ComponentModel types but now it probably makes sense to use custom attributes instead. So we introduce a couple of new attributes that can be used to apply documentation to the parameters and return value of an action without the more verbose use of per-parameter attribute. I find it cleaner.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class RestParameterAttribute : Attribute
{
    public RestParameterAttribute ( string name, string description )
    {
        Name = name ?? "";
        Description = description ?? "";
    }

    public string Description { get; private set; }
    public string Name { get; private set; }        
}

[AttributeUsage(AttributeTargets.Method)]
public class RestResponseAttribute : Attribute
{
    public RestResponseAttribute ( string description ) : this(description, null)
    {
    }

    public RestResponseAttribute ( string description, Type responseType )
    {
        Description = description ?? "";
        Type = responseType;
    }

    public string Description { get; private set; } 
    public Type Type { get; private set; }
}

Here’s how we might apply it.

[RestParameter("id", "The product identifier.")]
[RestResponse("The product, if any.")]
public Product Get ( int id )
{
}

The reflection provider needs to be updated to look for these new attributes. To make it easier to use we will use the attributes if available or fall back to the standard ComponentModel attributes otherwise.

public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
    var attr = parameterDescriptor.ActionDescriptor?.GetCustomAttributes()
						.FirstOrDefault(a => String.Compare(a.Name, parameterDescriptor.ParameterName, true) == 0);
    if (attr != null)
        return attr.Description;
    var reflectedParameterDescriptor = parameterDescriptor 
                                            as ReflectedHttpParameterDescriptor;
    return reflectedParameterDescriptor.ParameterInfo.GetDescription();            
}
public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
{
    var attr = actionDescriptor.GetCustomAttributes().FirstOrDefault();
    if (attr != null)
        return attr.Description;
    var returnInfo = GetMethod(actionDescriptor);
    if (returnInfo == null)
        return null;            
    return returnInfo.ReturnTypeCustomAttributes.GetDescription();
}

Now we need to modify Swagger to use it. Normally Swagger uses the standard IDocumentationProvider registered for Web API. However Swashbuckle stomps over that, unfortunately. This is the one area that I find Swashbuckle to be sorely lacking. I want to use it for its combination of Swagger and Swagger UI but I don’t like how it limits access to the core stuff. This actually causes us a problem when it comes to models. To change the documentation provider we need to add an operation filter to Swagger. We also need to hook into the model filters but unfortunately Swashbuckle marks them internal. If we were using Swagger directly we could handle this all directly but instead we’ll have to resort to some reflection trickery to register our provider. To make it simple we’ll wrap it in an extension method.

internal static class SwaggerConfigExtensions
{
    public static SwaggerDocsConfig UseReflectionDocumentation ( this SwaggerDocsConfig source )
    {
        //Register documentation provider
        source.OperationFilter(() => ReflectionDocumentationProvider.Default);
        
        //HACK: This is a hack to get access to the model filters because it isn't public
        //source.ModelFilters();
        var modelFilters = source.GetType().GetField("_modelFilters", BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.Instance);
        var filters = modelFilters?.GetValue(source) as System.Collections.Generic.IList<Func>;
        if (filters != null)
        {
            filters.Add(() => ReflectionDocumentationProvider.Default);
        } else
            Debug.WriteLine("Unable to get model filters from SwaggerDocsConfig, model documentation will be unavailable.");

        return source;
    }
}

Finally we can update the configuration to use the new provider.

    //c.IncludeXmlComments(GetDocumentationPath());
    c.UseReflectionDocumentation();

Caching

The final area to look at is performance. Reflection isn’t fast and the documentation is really static once compilation occurs. To speed up documentation generation we could cache the generated Swagger information. Swashbuckle exposes this option as a custom provider. We simply need to implement a simple caching provider to generate the documentation once.

internal class CachingSwaggerProvider : ISwaggerProvider
{
    public CachingSwaggerProvider ( ISwaggerProvider defaultProvider )
    {
        m_defaultProvider = defaultProvider;
    }
    public SwaggerDocument GetSwagger ( string rootUrl, string apiVersion )
    {
        var cacheKey = $"SwaggerDoc-{apiVersion}";
        //Check cache first
        var doc = HttpRuntime.Cache.Get(cacheKey) as SwaggerDocument;
        if (doc == null)
        {
            doc = m_defaultProvider.GetSwagger(rootUrl, apiVersion);
            HttpRuntime.Cache[cacheKey] = doc;
        };
        return doc;
    }
    private readonly ISwaggerProvider m_defaultProvider;        
}

And the changes to the Swagger config.

c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));

Final Thoughts

I’m still figuring my way through Swagger so there may be issues with the code when using it with larger code blocks and for some situations. Things that come to mind include

  • Documenting non-success responses
  • Providing error details
  • Custom model types that map to standard JSON types
  • Enumerable lists (currently generates an error in the documentation
  • Providing a custom RestDescription for type, member descriptions
  • More Swagger documentation including examples

Code

Removal instructions for Donation Reminder

What is Donation Reminder?

The Malwarebytes research team has determined that Donation Reminder is a browser hijacker. These so-called “hijackers” manipulate your browser(s), for example to change your startpage or searchscopes, so that the affected browser visits their site or one of their choice. This one also displays advertisements.

https://forums.malwarebytes.org/index.php?%2Ftopic%2F178392-removal-instructions-for-donation-reminder%2F

Fluent Validation in JavaScript

A recent discussion with my colleagues about fluent validation in JavaScript made me realize that I didn’t know of any such library. I take it for granted that some may exist, but I have never actually used one. To be clear, I mean a validation library that I can use in unit tests, for asserting conditions. Because I had a free Saturday morning, I decided to write my own!

Nothing fancy, just a couple of methods for dealing with common validations. It can be used in both browsers and in Node.js apps. Several validations can be chained and it any fails, an error is thrown. It goes like this:

/**

 * Builds a new Validation object

 * @param {object} obj The object to validate

 */

function Validation(obj) {    

    this.obj = obj;

    this.negated = false;

    this.reporting(null);

}

 

/**

 * Try to find the first argument of a given type

 * @param {array} args An array of arguments

 * @param {string} type The type to find

 * @returns {object} The first argument that matches the given type, or undefined

 */

function findFirstOfType(args, type) {

    for (var i = 0; i < args.length; ++i) {

        if (typeof args[i] === type) {

            return args[i];

        }

    }

    return undefined;

}

 

/**

 * Either returns the first argument as an array or the arguments implicit parameter

 * @param {array} args A possibly array parameter

 * @param {array} array An array of arguments

 * @returns {array} An array of arguments

 */

function getArguments(args, array) {

    var newArray = args;

    

    if (!(args instanceof Array))

    {

        newArray = [ args ];

        for (var i = 1; i < array.length; ++i) {

            newArray.push(array[i]);

        }

    }

    

    return newArray;

}

 

/**

 * Throws an exception in case of an error

 * @param {boolean} error An error flag

 * @param {string} msg An error message

 */

Validation.prototype.assert = function(error, msg) {

    if (error != this.negated) {

        this.report(msg);

    }

};

 

/**

 * Changes the reporting function in case of a validation error. The default is to throw an Error

 * @param {function} fn A reporting function

 * @returns {object} The Validation object

 */

Validation.prototype.reporting = function(fn) {

    if ((!fn) || (typeof fn !== 'function')) {

        fn = function(msg) {

            throw new Error(msg);

        };

    }

    

    this.report = fn;

    return this;

};

 

/**

 * Uses an external validation function

 * @param {function} fn A validation function

 * @param {string} msg An optional error message

 */

Validation.prototype.isValid = function(fn, msg) {

    var self = this;

    msg = msg || 'Validation failed: custom validation function';

    var error = (fn(self.obj) !== true);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is one of a set of passed values

 * @param {array} args An optional array of arguments

 */

Validation.prototype.isOneOf = function(args) {

    var self = this;

    var msg = 'Validation failed: objects do not match';

    var error = arguments.length > 0;

    args = getArguments(args, arguments);

    

    for (var i = 0; i < args.length; ++i) {

        if (self.obj == args[i]) {

            error = false;

            break;

        }

    }

    

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is not in a set of passed values

 * @param {array} args An optional array of arguments

 */

Validation.prototype.isNoneOf = function(args) {

    var self = this;

    var msg = 'Validation failed: objects do not match';

    var error = false;

    args = getArguments(args, arguments);

        

    for (var i = 0; i < args.length; ++i) {

        if (self.obj == args[i]) {

            error = true;

            break;

        }

    }

    

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate contains a supplied value

 * @param {object} value A value to find

 * @param {string} msg An optional error message

 */

Validation.prototype.contains = function(value, msg) {

    var self = this;

    msg = msg || 'Validation failed: object does not contain target';

    var error = self.obj.length != 0;

    

    for (var i = 0; i < self.obj.length; ++i) {

        if (self.obj[i] == value) {

            error = false;

            break;

        }

    }

    

    this.assert(error, msg);

    return this;    

};

 

/**

 * Checks if the value to validate is equal to a supplied value

 * @param {object} value A value to compare against

 * @param {object} arg1 An optional argument

 * @param {object} arg2 An optional argument

 */

Validation.prototype.isEqualTo = function(value, arg1, arg2) {

    var self = this;

    var caseInsensitive = findFirstOfType([arg1, arg2], 'boolean') || false;

    var msg = findFirstOfType([arg1, arg2], 'string') || 'Validation failed: objects do not match';

    var left = self.obj.toString();

    var right = value.toString();

            

    if (caseInsensitive) {

        left = left.toLowerCase();

        right = right.toLowerCase();

    }

 

    var error = (left != right);

    

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a string

 * @param {string} msg An optional error message

 */

Validation.prototype.isString = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a string';

    var error = ((typeof self.obj !== 'string') && (self.obj.toString() != obj));

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is neither null nor a whitespace string

 * @param {string} msg An optional error message

 */

Validation.prototype.isNotNullOrWhitespace = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is null or whitespace';

    var error = ((self.obj === null) || (self.obj.toString().trim().length == 0));

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a number

 * @param {string} msg An optional error message

 */

Validation.prototype.isNumber = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a number';

    var error = ((typeof self.obj !== 'number') && (Number(self.obj) != self.obj));

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a positive number

 * @param {string} msg An optional error message

 */

Validation.prototype.isPositive = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a number';

    var error = (Number(self.obj) <= 0);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a negative number

 * @param {string} msg An optional error message

 */

Validation.prototype.isNegative = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a number';

    var error = (Number(self.obj) >= 0);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is an odd number

 * @param {string} msg An optional error message

 */

Validation.prototype.isOdd = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not odd';

    var error = (Number(self.obj) % 2 === 0);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is an even number

 * @param {string} msg An optional error message

 */

Validation.prototype.isEven = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not even';

    var error = (Number(self.obj) % 2 !== 0);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a finite number

 * @param {string} msg An optional error message

 */

Validation.prototype.isFinite = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is infinite';

    var error = !isFinite(self.obj);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a function

 * @param {string} msg An optional error message

 */

Validation.prototype.isFunction = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a function';

    var error = (typeof self.obj !== 'function');

    this.assert(error, msg);

    return this;    

};

 

/**

 * Checks if the value to validate is a boolean

 * @param {string} msg An optional error message

 */

Validation.prototype.isBoolean = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a boolean';

    var error = (typeof self.obj !== 'boolean');

    this.assert(error, msg);

    return this;    

};

 

/**

 * Checks if the value to validate is defined

 * @param {string} msg An optional error message

 */

Validation.prototype.isDefined = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is undefined';

    var error = (self.obj === undefined);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is null

 * @param {string} msg An optional error message

 */

Validation.prototype.isNull = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not null';

    var error = (self.obj !== null);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is of a primitive type

 * @param {string} msg An optional error message

 */

Validation.prototype.isPrimitive = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not of a primitive type';

    var type = typeof self.obj;

    var error = ((type !== 'number') && (type !== 'string') && (type !== 'boolean'));

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is an array

 * @param {string} msg An optional error message

 */

Validation.prototype.isArray = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not an array';

    var error = !Array.isArray(self.obj);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate matches a regular expression

 * @param {string} regex A regular expression

 * @param {string} msg An optional error message

 */

Validation.prototype.isMatch = function(regex, msg) {

    var self = this;

    msg = msg || 'Validation failed: object does not match regular expression';

    var error = !(new RegExp(regex).test(self.obj.toString()));

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is valid JSON

 * @param {string} msg An optional error message

 */

Validation.prototype.isJSON = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not valid JSON';

    var error = false;

    try

    {

        error = (typeof JSON.parse(self.obj) !== 'object');

    }

    catch(e)

    {

        error = true;

    }

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate has a given length

 * @param {number} max The maximum length

 * @param {object} arg1 An optional argument

 * @param {object} arg2 An optional argument

 */

Validation.prototype.hasLength = function(max, arg1, arg2) {

    var self = this;

    var msg = findFirstOfType([arg1, arg2], 'string') || 'Validation failed: length does not fall between the given values';    

    var min = findFirstOfType([arg1, arg2], 'number') || 0;        

    var str = self.obj.toString();

    var error = str.length > max;

 

    if (!error) {

        error = (str.length < min);

    }

    

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a Promise

 * @param {string} msg An optional error message

 */

Validation.prototype.isPromise = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a promise';

    var error = ((typeof Promise === 'undefined') || !(self.obj instanceof Promise));

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is a Date

 * @param {string} msg An optional error message

 */

Validation.prototype.isDate = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not a date';

    var error = !(self.obj instanceof Date);

    this.assert(error, msg);

    return this;

};

 

/**

 * Checks if the value to validate is an Error

 * @param {string} msg An optional error message

 */

Validation.prototype.isError = function(msg) {

    var self = this;

    msg = msg || 'Validation failed: object is not an error';

    var error = !(self.obj instanceof Error);

    this.assert(error, msg);

    return this;

};

 

/**

 * Negates the validation logic

 * @returns {object} The Validation object

 */

Validation.prototype.not = function() {

    this.negated = !this.negated;

    return this;

};

 

/**

 * Validates an object

 * @returns {object} The Validation object

 */

Object.prototype.validate = function() {

    return Validation.validate(this);

};

 

Validation.validate = function(obj) {

    var val = new Validation(obj);

    return val;

};

 

if (typeof module !== 'undefined') {

    module.exports = Validation;

}

It’s usage is simple, as would be expected from a fluent library:

//the object to validate

var obj = '1';

 

//fire a bunch of validations - not all make sense

Validation

    .validate(obj)

    .isDefined()

    .isPrimitive()

    .isValid(function(x) { return true })

    .contains('1')

    .isOdd()

    .isOneOf('1', '2', '3')

    .isNoneOf('4', '5', '6')

    .isEqualTo(1)

    .isNotNullOrWhitespace()

    .isString()

    .isNumber()

    .hasLength(2, 1)

    .isMatch('\d+')

    .isPositive();

The included checks are:

  • isValid: takes a JavaScript function to validate the object;
  • isOneOf, isNoneOf: check to see if the target object is contained/is not contained in a set of values;
  • contains: checks if the object to validate – possibly an array – contains in it a given value;
  • isEqualTo: performs a string comparison, optionally case-insensitive;
  • isString, isNumber, isFunction, isArray, isDate, isJSON, isPromise, isError, isBoolean, isPrimitive: what you might expect from the names;
  • isNotNullOrWhitespace: whether the target object’s string representation is neither null or white spaces;
  • isDefined, isNull: checks if the target is defined (not undefined) or null;
  • isMatch: checks if the object matches a given regular expression;
  • hasLength: validates the object’s length (maximum and optional minimum size);
  • isOdd, isEven, isPositive, isNegative, isFinite: whether the object is odd, even, positive, negative or finite.

All of the checks can be negated as well by using not:

Validation

    .validate(obj)

    .not()

    .isNull()

    .isEven()

    .isNegative()

    .isPromise()

    .isArray()

    .isFunction()

    .isDate()

    .isError()

    .isJSON();

And most can also take an optional message, that will be used instead of the default one:

Validation

    .validate(obj)

    .isNull('Hey, I'm null!');

The actual bootstrapping Validation “class” is actually optional, because of the Object prototype extension method validate:

obj

    .validate()

    .isDefined();

The checks that accept array parameters (isOneOf, isNoneOf) can either take a single array argument or an undefined number or arguments (notice the difference):

obj

    .validate()

    .isOneOf([ 1, 2, 3])

    .isNoneOf(4, 5, 6);

Finally, the actual outcome of a failed validation can be controlled through the reporting function, for example, if you prefer to log to the console instead of raising an exception:

Validation

    .validate(obj)

    .reporting(function(msg) { console.log(msg) })

    .isDefined();

The code is available in GitHub: https://github.com/rjperes/FluentValidationJS/. Please use it as you like, and let me know if you face any issues. By all means, improve it as you like, but let me hear about it! Winking smile

Not so fast, some of us need EMET

http://www.zdnet.com/article/microsoft-windows-10-edge-so-secure-they-dont-need-our-emet-anti-zero-day-shield/

Posts like these make me angry.  Don’t get me wrong there are some key things I like about Windows 10.  The security enhancements are key.  But what makes me angry is that the key features they are pointing out here – Device Guard and Applocker are not available on the Pro or Home skus.  They are only available on the Enterprise sku.  Then if you want to use group policy to limit access to Windows store, a feature that used to be able to be controlled with Windows 8 pro, now you have to have Enterprise in order for the group policy to be enforced.
https://support.microsoft.com/en-us/kb/3135657

These decisions disappoint me.

Not the comma!

There is a habit among some AD administrators to create their users so that the name is surname, firstname   – Note the comma between the two names. As an example the name would be

Brown, Bill

instaead of

Bill Brown

 

If you’re just using the GUI tools it doesn’t matter too much and has the arguable advantage of ordering the users by surname. But when it comes to scripting against AD this practice is a complete pain.

Compare these 2 distinguished names

CN=Brown, Bill,OU=Testing,DC=Manticore,DC=org

CN=Dave Green,OU=Testing,DC=Manticore,DC=org

 

Notice the extra comma in the first one. That destroys any chance of splitting the distinguished name on commas – which are the element separators in distinguished names.

You have to escape the comma in the name with a

 

The GUI tools (at least in Windows server 2012 R2) do this for you so the distinguished name looks like this:

CN=Brown, Bill,OU=Testing,DC=Manticore,DC=org

 

If you want to get a user by distinguished name this will work:

Get-ADUser -Identity ‘CN=Dave Green,OU=Testing,DC=Manticore,DC=org’

 

This won’t

Get-ADUser -Identity ‘CN=Brown, Bill,OU=Testing,DC=Manticore,DC=org’

 

You have to use the escaped version:

Get-ADUser -Identity ‘CN=Brown, Bill,OU=Testing,DC=Manticore,DC=org’

 

In my last post I showed how to extract the users OU from the distinguished name

Get-ADUser -Filter * -Properties DisplayName |
select Name, DisplayName, UserPrincipalname, @{N= "Organanisational Unit" ;
E = {($_.DistinguishedName -split ‘,’, 2)[1]}}

 

That code breaks down if you have a comma in the name and you get

Bill,OU=Testing,DC=Manticore,DC=org

for the OU instead of

OU=Testing,DC=Manticore,DC=org

 

Its probably possible to do some regex voodoo to deal with this but as the Universe doesn’t have enough life left in it for me to figure this out I’ll resort to a brute force approach:

Get-ADUser -Filter * -Properties DisplayName |
foreach {
$ouf = ($_.DistinguishedName -split ‘,’, 2)[1]
if (-not ($ouf.StartsWith(‘OU’) -or $ouf.StartsWith(‘CN’) )){
  $ou = ($ouf -split ‘,’, 2)[1]
}
else {
  $ou = $ouf
}
$psitem | select Name, DisplayName, UserPrincipalname, @{N= "Organanizational Unit" ;E = {$ou}}
}

 

Do the inital split as previously but then test the reasults to see if it starts with CN= or OU=. If it doesn’t then split again.

Its not elegant but it works.

It sa lot easier if you don’t use the comma in the first place Smile

Removal instructions for Pass and Play

What is Pass and Play?

The Malwarebytes research team has determined that Pass and Play is a browser hijacker. These so-called “hijackers” manipulate your browser(s), for example to change your startpage or searchscopes, so that the affected browser visits their site or one of their choice. This one also displays advertisements.

https://forums.malwarebytes.org/index.php?/topic/178370-removal-instructions-for-pass-and-play/

Weekend reading

How to Delete BitLocker Recovery Key from OneDrive for Microsoft Account in Windows 10

A BitLocker recovery key is a special key that you can create when you turn on Bitlocker Drive Encryption for the first time on each drive that you encrypt. You can use the recovery key to gain access to your computer if the operating system drive (drive that Windows is installed on) is encrypted using BitLocker Drive Encryption and BitLocker detects a condition that prevents it from unlocking the drive when the computer is starting up. A recovery key can also be used to gain access to your files and folders on a fixed data drive (internal hard drive) or removable data drive (such as an external hard drive or USB flash drive) that is encrypted by BitLocker, if for some reason you forget the password or your computer cannot access the drive.

You can back up the BitLocker recovery key for an encrypted drive by printing it, saving it to your Microsoft account, saving it to a USB flash drive, and/or saving it to a file where you like. It is recommended to store the recovery key separate from your computer, and make additional copies to be safe and have available if ever needed to recover the encrypted drive with.

When you back up your recovery key to your Microsoft account, the recovery key gets saved online to your OneDrive for you to get if ever locked out of the encrypted drive.

This tutorial will show you how to delete a backed up BitLocker recovery key on your OneDrive after it was saved to your Microsoft account in Windows 10.

Read more…

Microsoft ‘scams’..

A good website here, straight from the horse’s mouth. Read and inwardly digest, pass it on to people you know, spread the word.

Do it NOW.. 😉

How to Back up BitLocker Recovery Key for Drive in Windows 10

A BitLocker recovery key is a special key that you can create when you turn on Bitlocker Drive Encryption for the first time on each drive that you encrypt. You can use the recovery key to gain access to your computer if the operating system drive (drive that Windows is installed on) is encrypted using BitLocker Drive Encryption and BitLocker detects a condition that prevents it from unlocking the drive when the computer is starting up. A recovery key can also be used to gain access to your files and folders on a fixed data drive (internal hard drive) or removable data drive (such as an external hard drive or USB flash drive) that is encrypted by BitLocker, if for some reason you forget the password or your computer cannot access the drive.

You can store the BitLocker recovery key for an encrypted drive by printing it, saving it to your Microsoft account, saving it to a USB flash drive, and/or saving it to a file where you like. It is recommended to store the recovery key separate from your computer, and make additional copies to be safe and have available if ever needed to recover the encrypted drive with.

If you lose the BitLocker recovery key for an encrypted drive, you will lose all your data on the drive if you get locked out of it and have to format the drive.

This tutorial will show you how to back up the recovery key of a drive encrypted by BitLocker in Windows 10.

Read more…

Some thoughts on finding a users OU

Back in this post http://itknowledgeexchange.techtarget.com/powershell/discovering-a-users-ou/

 

I showed how to get the OU of a user from the distinguished name of the user object. if you want to display that as part of your output you can create a calculated field

Get-ADUser -Filter * -Properties DisplayName |
select Name, DisplayName, UserPrincipalname, @{N= "Organanisational Unit" ;
E = {($_.DistinguishedName -split ‘,’, 2)[1]}}

 

In your select statement take the Distinguishedname and split it on the comma – make sure you split it into 2 parts – the second is the OU

 

Don’t rely on the Displayname alone as its not present for some built in accounts such as administrator

Removal instructions for EasyPhotoEdit

What is EasyPhotoEdit?

The Malwarebytes research team has determined that EasyPhotoEdit is a browser hijacker. These so-called “hijackers” manipulate your browser(s), for example to change your startpage or searchscopes, so that the affected browser visits their site or one of their choice. This one also displays advertisements.
EasyPhotoEdit is a Mindspark/Ask toolbar.

https://forums.malwarebytes.org/index.php?%2Ftopic%2F178341-removal-instructions-for-easyphotoedit%2F

How to Find Firmware Revision Number of Windows 10 Mobile Phone

This tutorial will show you how to find the firmware revision number on your Windows 10 Mobile phone.

Read more…

How to Find OS Build Number of Windows 10 Mobile Phone

Software (ex: “Windows 10 Mobile”) indicates the general product name Microsoft uses to describe the release. OS build (ex: “10.0.10586.71”) indicates the specific version build number of the release.

This tutorial will show you how to find the OS build number on your Windows 10 Mobile phone.

Read more…

Recent Comments

Archives