Pages

Tuesday, March 16, 2021

Steps C# Edge driver and Selenium Test Project

Create NUnit or MSTest project

In project manager, install pacakge: Microsoft.Edge.SeleniumTools

Package will install:

  • Microsoft.Edge.SeleniumTools
  • Selenium.WebDriver
  • Selenium.Support
  • DotNetSeleniumExtras.PageObjects.Core 
**PageObjects were marked obsolete - instead of  OpenQA.Selenium.Support.PageObjects use SeleniumExtras.PageObjects namespace. 

Navigate to: WebDriver - Microsoft Edge Developer

Download latest Microsoft Edge Driver.


Open downloaded Microsoft Edge Driver zip file and save msedgedriver.exe to a local drive.

Must change driver's name from msedgedriver.exe to MicrosoftWebDriver.exe. 

**Changing name is a must or an error message:
 OpenQA.Selenium.DriverServiceNotFoundException : The file C:\Selenium\EdgeDriver\msedgedriver.exe does not exist. The driver can be downloaded at https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

Reference EdgeDriver within Test fixture.


[Test] public void Test1() { //Open Browser IWebDriver webDriver = new EdgeDriver(@"C:\Selenium\EdgeDriver"); //Navigate to site webDriver.Navigate().GoToUrl("http://yoopergreens.com"); //Assert.Pass(); }
This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Tuesday, March 9, 2021

TypeScript Recursion Code Snippet

Reusable TypeScript / JavaScript Recursion Method

Toggling opening and closing UI block level elements. Handles n - level.


Targeting a button, toggles open showing its children elements.




Targeting another button, will hide all shown children elements.



















Hooking up UI


$(".toggleSeeds").click((function () {
    var state = {},
        currentId = null;

    return function () {
        var id: number = GetId(this.id);

        ResetStates(this);

        state[id] = typeof state[id] != "undefined" ? state[id] : {
            collapsed: true,
            toggleSeeds: $("#toggleSeeds_" + id + "> img")[0],
            supplierSeeds: $("#supplierSeeds_" + id)
        };

        if (state[id].collapsed) {

            state[id].supplierSeeds.show();
            state[id].toggleSeeds.src = "/images/SVG/arrowhead-Down.svg";

            if (currentId && currentId != id) {
                state[currentId].supplierSeeds.hide();
                state[currentId].collapsed = true;
                state[currentId].toggleSeeds.src = "/images/SVG/arrowhead-Right.svg";
            }
            currentId = id;
        } else {
            state[id].supplierSeeds.hide();
            state[id].toggleSeeds.src = "/images/SVG/arrowhead-Right.svg";
            currentId = null;
        }

        state[id].collapsed = !state[id].collapsed;
    }
}()));
  
Tracking states
var ResetStates: (element: HTMLElement) => void = (function () {  
  var buttonState: HTMLElement[] = [];  
  return (element: HTMLElement) => {  
   var state: HTMLElement,  
    parent: HTMLElement,  
    stateLevels: RegExpMatchArray,  
    targetLevels: RegExpMatchArray,  
    sameLevel: boolean,  
    sameParent: boolean,  
    isChild: boolean,  
    switchedLevels: boolean;  
   if (buttonState.length == 0) {  
    buttonState.push(element);  
    return;  
   }  
   state = buttonState[buttonState.length - 1] ?? element;  
   parent = buttonState[0] ?? element;  
   stateLevels = state.id.match(/[0-9]+/g);  
   targetLevels = element.id.match(/[0-9]+/g);  
   sameParent = stateLevels[0] == targetLevels[0];  
   sameLevel = stateLevels.length == targetLevels.length;  
   isChild = (targetLevels.length > stateLevels.length) && sameParent;  
   switchedLevels = (parent.id != element.id) && !sameParent;  
   if (state.id != element.id) {  
    if (sameLevel) {  
     buttonState[buttonState.length - 1] = null;  
     state.click();  
     buttonState.push(element);  
    } else if (isChild) {  
     buttonState.push(element);  
    } else if (switchedLevels || sameParent) {  
     while (buttonState.length > 0) {  
      state = buttonState[buttonState.length - 1];  
      if (state != null) {  
       buttonState[buttonState.length - 1] = null;  
       state.click();  
      }  
     }  
     buttonState.push(element);  
    }  
   } else {  
    buttonState.pop();  
   }  
  }  
 }()); 
This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Monday, June 4, 2018

Ninject Setup IoC and Webapi

Ninject Setup IoC and Webapi
Namespace

  • Ninject.Mvc5
  • Ninject.Web.WebApi
  • Ninject.Web.Common.WebHost
  • Ninject.Web.Common
  • Ninject
  • WebActivatorEx


Ninject.Mvc5 installs dependencies

  • Ninject.Web.Common.WebHost
  • Ninject.Web.Common
  • Ninject.Web.Mvc
  • Ninject

Making Ninject work with WebApi
Installing package
  • Ninject.Web.WebApi

Will add dependency
  • Ninject.Web.WebApi
Making Ninject auto executing
Install package
  • WebActivatorEx
Below, file was created in App_Start or manually created


[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YooperGreens.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YooperGreens.App_Start.NinjectWebCommon), "Stop")]

namespace YooperGreens.App_Start
{
    using System;
    using System.Web;
    using System.Web.Http;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using Ninject.Web.Common.WebHost;
    using Ninject.Web.WebApi;
    using YooperGreens.Db;

    public static class NinjectWebCommon
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));

            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<YooperGreensDbContext>().ToSelf().InRequestScope();
            kernel.Bind<IAccountViewModel>().To<AccountViewModel>();
        }
    }
}

This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Missing System.Web.Http namespace

Quick fix

Within Visual Studio package manager enter,

Update-Package -reinstall Microsoft.AspNet.WebApi.Core


This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Sunday, June 3, 2018

Entityframework 6.2 Model Confuguration / Seed Initializer

Install package

  • Install-Package EntityFramework

Create Model Class

    public class Seed
    {
        public Guid SeedId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Link { get; set; }
        public Germination Germination { get; set; }
        public string Supplier { get; set; }
        public int Count { get; set; }
        public decimal Price { get; set; }

        public ICollection<Order> Orders { get; set; }
    }

    public class Order
    {
        public Guid OrderId { get; set; }
        public decimal Shipping { get; set; }
        public decimal Tax { get; set; }
        public Seed Seed { get; set; }

    }
Create DbContext Class

    public interface IYooperGreensDbContext
    {
        DbSet<Seed> Seeds { get; set; }
        DbSet<Order> Orders { get; set; }

    }

    public class YooperGreensDbContext : DbContext, IYooperGreensDbContext
    {
        public YooperGreensDbContext()
            :base("yoopergreens")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            ModelConfiguration configuration = new ModelConfiguration();

            modelBuilder.Configurations.Add(configuration.Seed);
            modelBuilder.Configurations.Add(configuration.Order);

        }
        public DbSet<Seed> Seeds { get; set; }
        public DbSet<Order> Orders { get; set; }
    }

Create Configuration Classes for each model class

    public class OrderConfiguration: EntityTypeConfiguration<Order>
    {
        public OrderConfiguration()
        {
            HasKey(o => o.OrderId);
            HasRequired(o => o.Seed).WithMany(o => o.Orders);
        }
    }

    public class SeedConfiguration : EntityTypeConfiguration<Seed>
    {
        public SeedConfiguration()
        {
            HasKey(s => s.SeedId);
        }
    }

Create Centralized Configuration file

     public class ModelConfiguration
    {
        public SeedConfiguration Seed { get { return new SeedConfiguration(); } }
        public OrderConfiguration Order { get { return new OrderConfiguration(); } }
    }

Create a custom DB initializer to seed data into database:

  • CreateDatabaseIfNotExists
  • DropCreateDatabaseIfModelChanges
  • DropCreateDatabaseAlways


    public class YooperGreensDbInitializer : DropCreateDatabaseAlways<YooperGreensDbContext>
    {
        public YooperGreensDbInitializer()
        {
        }

        protected override void Seed(YooperGreensDbContext context)
        {

            IList<Seed> seeds = new List<Seed>
            {
                new Seed {}
            };

            context.Seeds.AddRange(seeds);

            base.Seed(context);
        }
    }

Set this DB initializer class in context class's constructor


        public YooperGreensDbContext()
            :base("yoopergreens")
        {
            Database.SetInitializer(new YooperGreensDbInitializer());

            Configuration.ProxyCreationEnabled = false;

        }

File Structure



This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Wednesday, August 9, 2017

Self Referencing Loop Detected - Entity Framework

Error received:
self referencing loop detected for propert with type System.data.entity.dynamic.proxiesOccurs when trying to serialize the EF object collection directly.Some ways correcting:

Add to the db context constructor:

Configuration.ProxyCreationEnabled = false;

Or (better way),

HttpConfiguration config = GlobalConfiguration.Configuration;

config.Formatters.JsonFormatter
            .SerializerSettings
            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

Other ways of correcting found at Stackoverflow

This post is for the purpose of my notes only and sometimes a rant.

“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Sunday, August 6, 2017

Ninject IOC - ASP.NET WEB API

Nuget packages:
  • Ninject.Web.WebApi
  • Ninject.Web.WebApi.WebHost
  • Ninject.MVC5

<package id="Ninject" version="3.2.0.0" targetFramework="net461" />


<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net461" />


<package id="Ninject.Web.Common" version="3.2.0.0" targetFramework="net461" />


<package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net461" />


<package id="Ninject.Web.WebApi" version="3.2.4.0" targetFramework="net461" />


<package id="Ninject.Web.WebApi.WebHost" version="3.2.4.0" targetFramework="net461" />




NinjectWebCommon CreateKernal method

private static void RegisterServices(IKernel kernel)
{
     kernel.Bind<dbcontext>().ToSelf().InRequestScope();
     kernel.Bind<myclass>().To<myclass>();
}


Could not get property injection to work with Web API, so resorted using for property injection:

private myProperty = DependencyResolver.Current.GetService<myclass>();
public myProperty2 = DependencyResolver.Current.GetService<myclass2>();

DependencyResolver is in the namespace: System.Web.MVC. This is based on the current IOC container, so swapping out IOC containers would not break code.


This post is for the purpose of my notes only and sometimes a rant.

“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Saturday, July 15, 2017

"StrongTypingException: The value for column IsPrimaryKey in table TableDetails is DBNull" Entity Framework 5 and MySql Server 5.7.9

"StrongTypingException: The value for column IsPrimaryKey in table TableDetails is DBNull"

For future reference on this particular issue with Entity Framework 5 and MySql Server 5.7.9. It has been reported as a Bug. Below is the work around reported at Stackoverflow.

The work around solves the issue.

I have included this fix, so when the bug has been corrected, I can revert back from this work around.

Work Around
**Use MySql Command Line Client. Will not work within Workbench.
use <database>
set @@optimizer_switch='derived_merge=off';
SELECT @@optimizer_switch\G
At MySql website gives explanation.

This post is for the purpose of my notes only and sometimes a rant.

“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford


Friday, July 14, 2017

Visual Studio 2013 - Logging in as different user.

When Visual Studio informs you that someone is already logged in and you are unable to login under a different user, I found this solution solved this problem that I was experiencing.


There is a comment about this under this answer, but I think it's important to list it here. If you want to preserve your settings, export them first because they will be lost.

Preserve Visual Studio 2013 Settings:
  • Tools > Import and Export Settings...
  • Select Export selected environment settings.
  • Check ALL settings check box.
  • Enter backup filename and file's directory.
  • Click Finish
From MSDN forums - since I had to hunt around far too much to find the solution to this:
  1. Close Visual Studio
  2. Start the Developer Command prompt installed with Visual Studio as an administrator.
  3. type 'devenv /resetuserdata' ('wdexpress /resetuserdata' for Express SKUs)
  4. Start Visual Studio Normally.
Do not remember where I found this solution, but I know that I had Googlized for the solution and almost sure that I landed at Stackoverflow.

This post is for the purpose of my notes only and sometimes a rant.

“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

The Compatibility Checker Package package did not load correctly

Visual Studio 2013 - Receiving Error: The Compatibility Checker Package package did not load correctly.

Googlizing: found at Stackoverflow a solution solving the problem:

I attempted:
  • Deleted ComponentModelCache folder, which is located at:
    %localappdata%\Microsoft\VisualStudio\12.0\ComponentModelCache
  • Deleted Extensions folder, which is located at:
    %localappdata%\Microsoft\VisualStudio\12.0\Extensions
  1. Closed Visual Studio 2013
  2. Deleted both folders mentioned above.
  3. Restarted VS
*These attempts did not correct the problem, so I followed another suggestion.
  1. Closed VS
  2. Opened, as Administrator, the Developer Command Prompt for VS2013 located at:
    C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts
  3. At command line typed: devenv /setup.
  4. After typing in devenv /setup and hitting enter, the cursor moved down one line and blinked for about 30-45 seconds before returning back to a command prompt.
  5. Closing out Developer Command Prompt, VS was opened.
Everything is back to normal. No errors.

I remember having a similar issue a while back. At that time all I had to do was delete the ComponentModelCache folder.

This time I had to take an extra step running devenv /setup at the command prompt.

A resourceful link:
/Setup (devenv.exe)

This post is for the purpose of my notes only and sometimes a rant.

“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Sunday, December 4, 2016

Selenium IDE, C# Visual Studio, and MSTest

Within Visual Studio Package Manager install packages


Within Visual Studio package manager

  •     Install-Package Selenium.RC (optional)
  •     Install-Package Selenium.WebDriver
  •     Install-Package Selenium.WebDriverBackedSelenium
  •     Install-Package Selenium.Support

Or, download zip file from: Selenium Webpage

    Extact zip file.
    Within Visual Studio add reference to these dlls

  •     Selenium.WebDriverBackedSelenium.dll
  •     ThoughtWorks.Selenium.Core.dll
  •     WebDriver.dll
  •     WebDriver.Support.dll

Now, Visual Studio has reference Selenium

Download the Internet Explorer Driver Server from: Selenium Webpage


    Download should be a single .exe file: IEDriverServer.exe

    Very Important that the IE Driver is able to find IEDriverServer.exe


  • Move IEDriverServer.exe into MS Test project's bin\debug folder
  • Or, make sure IEDriverServer.exe absolute path is added to the Path environment variables.

Start > right click Computer > properties > Advance system settings


Environment Variables > scroll down to Path > Edit > add, at end of text, the folder's absolute path where IEDriverServer.exe is found.

 
Install Selenium IDE Firefox plugin


After installing plugin, open Firefox, click on Tools > Selenium IDE

 

Using Selenium IDE, record some actions by clicking IDE's record button.


Export as C# / NUnit / WebDriver and save into project's folder



Generated NUnit Test Class


After changer were made


Must Include reference to
  • Microsoft.VisualStudio.TestTools.UnitTesting
in projects.




Within Visual Studio, create a Unit Test Project




    Remove UnitTest1.cs file





This post is for the purpose of my notes only and sometimes a rant.

“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Monday, October 10, 2016

ASP.NET Bundling Rendering Media Attribute on Link Tag


Reading this post about making a site mobile friendly, I noticed ASP.NET bundling doesn’t render the media attribute on the HTML link tag.

Quick search, found a solution at stackoverflow:


From the posted solution, I changed it a little.

<!DOCTYPE html>

 

<html class=" js ">

<head>

    <title></title>

    @Styles.Render("~/Styles/Base")

</head>

<body class="master-body" id="index">

To…

@using com.dogPedaler.Models

 

<!DOCTYPE html>

 

<html class=" js ">

<head>

    <title></title>

    @Styles.RenderFormat(BundlesFormats.Screen, "~/Styles/Base")

</head>

<body class="master-body" id="index">



The change includes the namespace to a class with a static property call Screen:

@using com.dogPedaler.Models

The Created Class

namespace com.dogPedaler.Models

{

    public class BundlesFormats

    {

        private const string template = @"<link href=""{0}"" ";

        private const string template2 = @"rel=""stylesheet"" type=""text/css"" media=""{0}"" />";

        public static string Print

        {

            get

            {

                return template + String.Format(template2, "print");

            }

        }

        public static string Screen

        {

            get

            {

                return template + String.Format(template2, "Screen");

            }

        }

        public static string HandHeld

        {

            get

            {

                return template + String.Format(@"rel=""stylesheet"" type=""text/css"" media=""print"" />", "handheld");

            }

        }

 

    }

}

Notice three properties

  • print
  • Screen
  • handheld

There is a reason why the “S” is capitalized. This is a hack for Windows mobile browsers and can be found at:

https://perishablepress.com/the-5-minute-css-mobile-makeover/
 
 
This post is for the purpose of my notes only and sometimes a rant.

“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”

Henry Ford