.

[resolved] npm certificate issues

Receiving the following error:

npm ERR! Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN

Upgrade your version of npm

npm install npm -g --ca=""

– OR –

Tell your current version of npm to use known registrars

<code>npm config set ca ""</code>

– OR –

Disable Strict-SSL 

npm config set strict-ssl false

 

– OR –

Switch from https to http 

npm config set registry="http://registry.npmjs.org/"

 

 

Manually setting a WordPress site to another location (after e.g. migration)

Edit your wp-config.php file

Add these two lines to your wp-config.php, where “example.com” is the correct location of your site.

define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');

PHP that has a file size restriction

Any of these

No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration

You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit.

find your php.ini file and ensure these are the settings:

php_value upload_max_filesize 120M //file size
php_value post_max_size 120M
php_value max_execution_time 200
php_value max_input_time 200

If this still doesn’t resolve the issue then follow these instructions below:

find and edit: config.inc.php file for PhpMyAdmin configuration

add this line at the end of the file BEFORE “?>”:
$cfg['UploadDir'] = ‘C:\tmp’;

save

create folder at
C:\tmp

copy your huge sql file there.

Restart server.

Go to your phpmyadmin import tab and you’ll see a list of files uploaded to c:\tmp.

Starting a WPF app programmatically (without a startup uri)

The default project template for WPF applications assumes that you want your main application class to be xaml-based. However, this is not a requirement and you can change it. Doing so allows you to write your own application entry point method and create your own application instance configured the way that you want.

So, you can delete your App.xaml and App.xaml.cs files and create an App.cs file in their place. In that file, do something like this:

internal class App : Application
{
    [STAThread]
    public static int Main(string[] args)
    {
        App app = new App();
        // Setup your application as you want before running it
        return app.Run(new MainWindow());
    }

    public App()
    {
        // (Optional) Load your application resources file (which has a "Page" build action, not "ApplicationDefinition",
        // and a root node of type "ResourceDictionary", not "Application")
        Resources = (ResourceDictionary)Application.LoadComponent(new Uri("/MyAssemblyName;component/Resources.xaml", UriKind.Relative));
    }
}

This allows you specify your main window whichever way you want before running the application. Your application resources file would look something like this:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- Put application resources here -->
</ResourceDictionary>

I always structure my WPF applications this way because it seems simpler and provides more control over how the application is run. (I created a custom WPF application project template in Visual Studio.)

setting up CORS

need the following in your WebAPI web.config:

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Editing system variables (such as path)

Open the Windows Environment Variables/Path Window.

  1. Right-click on My Computer -> Properties
  2. Click Advanced System Settings link from the left side column
  3. Click Environment Variables in the bottom of the window
  4. Then under System Variables look for the path variable and click edit

Getting started with SpecFlow in Visual Studio

I use VS 2013 for this example.

1) Create a new blank project (just a class library)

2) Install SpecFlow for Visual Studio from the menu (Tools -> Extensions & Updates)

3) right click -> add new item -> SpecFlow Feature File
Just name is “MyFirst.feature” for now.

4) just copy and paste the following in your editor window:

Feature: MyFirst
	In order to avoid silly mistakes
	As a math idiot
	I want to be told the sum of two numbers

@mytag
Scenario: Add two numbers
	Given I have entered 50 + 60 into the calculator
	When I press add
	Then the result should be 110 on the screen

Scenario: Add other numbers
	Given I have entered 6 + 8 into the calculator
	When I press add
	Then the result should be 14 on the screen

5) Right click on the file content and select “generate step definitions”.
use the style = regular expressions in attributes
and simply copy the methods to clipboard

6) create a new file ( just a plain class) and name it MyFirstSteps.cscopy and paste the following code (just a very simple basic implementation as example):

using System;
using NUnit.Framework;
using TechTalk.SpecFlow;

namespace specflow.tests
{
    [Binding]
    public class MyFirstSteps
    {
        Calc c = new Calc();
        [Given(@"I have entered (.*) \+ (.*) into the calculator")]
        public void GivenIHaveEnteredIntoTheCalculator(int p0, int p1)
        {
            c.add(p0, p1);
        }

        [When(@"I press add")]
        public void WhenIPressAdd()
        {
        }

        [Then(@"the result should be (.*) on the screen")]
        public void ThenTheResultShouldBeOnTheScreen(int p0)
        {
            Assert.AreEqual(p0, c.answer);
        }

        internal class Calc
        {

            internal void add(int p0, int p1)
            {
                answer = p0 + p1;
            }

            public int answer { get; set; }
        }
    }
}

7) if you use ReSharper, you can go to tools -> options -> specflow -> general, and change the test run a tool to ReSharper

8) Click Resharper -> Unit tests -> Run All Tests From Solution (Ctrl+U, Y)
This doesn’t do much: right click the specflow file and select “run specflow scenarios”

EF code first Fluent API link

https://msdn.microsoft.com/en-us/data/jj591617.aspx

 

Configuring/Mapping Properties and Types with the Fluent API

When working with Entity Framework Code First the default behavior is to map your POCO classes to tables using a set of conventions baked into EF. Sometimes, however, you cannot or do not want to follow those conventions and need to map entities to something other than what the conventions dictate.

There are two main ways you can configure EF to use something other than conventions, namely annotations or EFs fluent API. The annotations only cover a subset of the fluent API functionality, so there are mapping scenarios that cannot be achieved using annotations. This article is designed to demonstrate how to use the fluent API to configure properties.

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext. The following samples are designed to show how to do various tasks with the fluent api and allow you to copy the code out and customize it to suit your model, if you wish to see the model that they can be used with as-is then it is provided at the end of this article.

 

The following topics are covered on this page:

 

Model-Wide Settings

Default Schema (EF6 onwards)

Starting with EF6 you can use the HasDefaultSchema method on DbModelBuilder to specify the database schema to use for all tables, stored procedures, etc. This default setting will be overridden for any objects that you explicitly configure a different schema for.

<code id="c_e60d0d7c010547988f8b21b4fb07d242">modelBuilder.HasDefaultSchema(“sales”);</code>

Custom Conventions (EF6 onwards)

Starting with EF6 you can create your own conventions to supplement the ones included in Code First. For more details, see Custom Code First Conventions.

 

Property Mapping

The Property method is used to configure attributes for each property belonging to an entity or complex type. The Property method is used to obtain a configuration object for a given property. The options on the configuration object are specific to the type being configured; IsUnicode is available only on string properties for example.

Configuring a Primary Key

The Entity Framework convention for primary keys is:

1.       Your class defines a property whose name is “ID” or “Id”

2.       or a class name followed by “ID” or “Id”

To explicitly set a property to be a primary key, you can use the HasKey method. In the following example, the HasKey method is used to configure the InstructorID primary key on the OfficeAssignment type.

<code id="c_c033a6987d4e46318ceec28b8c4a051a">modelBuilder.Entity&lt;OfficeAssignment&gt;().HasKey(t =&gt; t.InstructorID);</code>

Configuring a Composite Primary Key

The following example configures the DepartmentID and Name properties to be the composite primary key of the Department type.

<code id="c_ff293df133474a6183875508171b1ca2">modelBuilder.Entity&lt;Department&gt;().HasKey(t =&gt; new { t.DepartmentID, t.Name });</code>

Switching off Identity for Numeric Primary Keys

The following example sets the DepartmentID property to System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None to indicate that the value will not be generated by the database.

<code id="c_cc443fe389704c54be1e5a488b9fb500">modelBuilder.Entity&lt;Department&gt;().Property(t =&gt; t.DepartmentID) 
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);</code>

Specifying the Maximum Length on a Property

In the following example, the Name property should be no longer than 50 characters. If you make the value longer than 50 characters, you will get a DbEntityValidationException exception. If Code First creates a database from this model it will also set the maximum length of the Name column to 50 characters.

<code id="c_6957502263a94fafa55f27c4196738fd">modelBuilder.Entity&lt;Department&gt;().Property(t =&gt; t.Name).HasMaxLength(50);</code>

Configuring the Property to be Required

In the following example, the Name property is required. If you do not specify the Name, you will get a DbEntityValidationException exception. If Code First creates a database from this model then the column used to store this property will usually be non-nullable.

Note: In some cases it may not be possible for the column in the database to be non-nullable even though the property is required. For example, when using a TPH inheritance strategy data for multiple types is stored in a single table. If a derived type includes a required property the column cannot be made non-nullable since not all types in the hierarchy will have this property.

<code id="c_32da7145233b415b90b50175a58ca565">modelBuilder.Entity&lt;Department&gt;().Property(t =&gt; t.Name).IsRequired();</code>

Configuring an Index on one or more properties


EF6.1 Onwards Only – The Index attribute was introduced in Entity Framework 6.1. If you are using an earlier version the information in this section does not apply.


Creating indexes isn’t natively supported by the Fluent API, but you can make use of the support for IndexAttribute via the Fluent API. Index attributes are processed by including a model annotation on the model that is then turned into an Index in the database later in the pipeline. You can manually add these same annotations using the Fluent API.

The easiest way to do this is to create an instance of IndexAttribute that contains all the settings for the new index. You can then create an instance of IndexAnnotation which is an EF specific type that will convert the IndexAttribute settings into a model annotation that can be stored on the EF model. These can then be passed to the HasColumnAnnotation method on the Fluent API, specifying the name Index for the annotation.

<code id="c_589a883b2621456183e553ba09b72d23">modelBuilder 
    .Entity&lt;Department&gt;() 
    .Property(t =&gt; t.Name) 
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute()));</code>

For a complete list of the settings available in IndexAttribute, see the Index section of Code First Data Annotations. This includes customizing the index name, creating unique indexes, and creating multi-column indexes.

You can specify multiple index annotations on a single property by passing an array of IndexAttribute to the constructor of IndexAnnotation.

<code id="c_23a70456a79a46999be18f30110ebe3f">modelBuilder 
    .Entity&lt;Department&gt;() 
    .Property(t =&gt; t.Name) 
    .HasColumnAnnotation( 
        "Index",  
        new IndexAnnotation(new[] 
            { 
                new IndexAttribute("Index1"), 
                new IndexAttribute("Index2") { IsUnique = true } 
            })));</code>

Specifying Not to Map a CLR Property to a Column in the Database

The following example shows how to specify that a property on a CLR type is not mapped to a column in the database.

<code id="c_9740566172d04116a8a174a9cfd0938e">modelBuilder.Entity&lt;Department&gt;().Ignore(t =&gt; t.Budget);</code>

Mapping a CLR Property to a Specific Column in the Database

The following example maps the Name CLR property to the DepartmentName database column.

<code id="c_157a9ff99a23467d987de7cdf12a33bc">modelBuilder.Entity&lt;Department&gt;() 
    .Property(t =&gt; t.Name) 
    .HasColumnName("DepartmentName");</code>

Renaming a Foreign Key That Is Not Defined in the Model

If you choose not to define a foreign key on a CLR type, but want to specify what name it should have in the database, do the following:

<code id="c_e5fd1623e98547a89feb5a177c732b6a">modelBuilder.Entity&lt;Course&gt;() 
    .HasRequired(c =&gt; c.Department) 
    .WithMany(t =&gt; t.Courses) 
    .Map(m =&gt; m.MapKey("ChangedDepartmentID"));</code>

Configuring whether a String Property Supports Unicode Content

By default strings are Unicode (nvarchar in SQL Server). You can use the IsUnicode method to specify that a string should be of varchar type.

<code id="c_bb491f3042324b23877643fb0f706611">modelBuilder.Entity&lt;Department&gt;() 
    .Property(t =&gt; t.Name) 
    .IsUnicode(false);</code>

Configuring the Data Type of a Database Column

The HasColumnType method enables mapping to different representations of the same basic type. Using this method does not enable you to perform any conversion of the data at run time. Note that IsUnicode is the preferred way of setting columns to varchar, as it is database agnostic.

<code id="c_5d082f9b3091488d8c5fa793df2053a4">modelBuilder.Entity&lt;Department&gt;()   
    .Property(p =&gt; p.Name)   
    .HasColumnType("varchar");</code>

Configuring Properties on a Complex Type

There are two ways to configure scalar properties on a complex type.

You can call Property on ComplexTypeConfiguration.

<code id="c_294b10ed85c24d33a4700122f39a7309">modelBuilder.ComplexType&lt;Details&gt;() 
    .Property(t =&gt; t.Location) 
    .HasMaxLength(20);</code>

You can also use the dot notation to access a property of a complex type.

<code id="c_586511da93bc48c9948c2a309dc5408e">modelBuilder.Entity&lt;OnsiteCourse&gt;() 
    .Property(t =&gt; t.Details.Location) 
    .HasMaxLength(20);</code>

Configuring a Property to Be Used as an Optimistic Concurrency Token

To specify that a property in an entity represents a concurrency token, you can use either the ConcurrencyCheck attribute or the IsConcurrencyToken method.

<code id="c_588b0b2d69294871b6880c4f65a61742">modelBuilder.Entity&lt;OfficeAssignment&gt;() 
    .Property(t =&gt; t.Timestamp) 
    .IsConcurrencyToken();</code>

You can also use the IsRowVersion method to configure the property to be a row version in the database. Setting the property to be a row version automatically configures it to be an optimistic concurrency token.

<code id="c_be6e1de2be1a4626b21412ac1d4e8c81">modelBuilder.Entity&lt;OfficeAssignment&gt;() 
    .Property(t =&gt; t.Timestamp) 
    .IsRowVersion();</code>

 

Type Mapping

Specifying That a Class Is a Complex Type

By convention, a type that has no primary key specified is treated as a complex type. There are some scenarios where Code First will not detect a complex type (for example, if you do have a property called ID, but you do not mean for it to be a primary key). In such cases, you would use the fluent API to explicitly specify that a type is a complex type.

<code id="c_4eedd237f3554ed1900a1f95dd1745dd">modelBuilder.ComplexType&lt;Details&gt;();</code>

Specifying Not to Map a CLR Entity Type to a Table in the Database

The following example shows how to exclude a CLR type from being mapped to a table in the database.

<code id="c_9f6b1f534f1b4dcca428552d5c0f249e">modelBuilder.Ignore&lt;OnlineCourse&gt;();</code>

Mapping an Entity Type to a Specific Table in the Database

All properties of Department will be mapped to columns in a table called t_ Department.

<code id="c_cbb18aba3f7944e988ddaf919564065c">modelBuilder.Entity&lt;Department&gt;()  
    .ToTable("t_Department");</code>

You can also specify the schema name like this:

<code id="c_bc83b99ddfa945bcab942a2890b93291">modelBuilder.Entity&lt;Department&gt;()  
    .ToTable("t_Department", "school");</code>

Mapping the Table-Per-Hierarchy (TPH) Inheritance

In the TPH mapping scenario, all types in an inheritance hierarchy are mapped to a single table. A discriminator column is used to identify the type of each row. When creating your model with Code First, TPH is the default strategy for the types that participate in the inheritance hierarchy. By default, the discriminator column is added to the table with the name “Discriminator” and the CLR type name of each type in the hierarchy is used for the discriminator values. You can modify the default behavior by using the fluent API.

<code id="c_c22b183233254e92be3d6786f79829dc">modelBuilder.Entity&lt;Course&gt;()  
    .Map&lt;Course&gt;(m =&gt; m.Requires("Type").HasValue("Course"))  
    .Map&lt;OnsiteCourse&gt;(m =&gt; m.Requires("Type").HasValue("OnsiteCourse"));</code>

Mapping the Table-Per-Type (TPT) Inheritance

In the TPT mapping scenario, all types are mapped to individual tables. Properties that belong solely to a base type or derived type are stored in a table that maps to that type. Tables that map to derived types also store a foreign key that joins the derived table with the base table.

<code id="c_a425da16c72846e89c046fada12cf2d3">modelBuilder.Entity&lt;Course&gt;().ToTable("Course");  
modelBuilder.Entity&lt;OnsiteCourse&gt;().ToTable("OnsiteCourse");</code>

Mapping the Table-Per-Concrete Class (TPC) Inheritance

In the TPC mapping scenario, all non-abstract types in the hierarchy are mapped to individual tables. The tables that map to the derived classes have no relationship to the table that maps to the base class in the database. All properties of a class, including inherited properties, are mapped to columns of the corresponding table.

Call the MapInheritedProperties method to configure each derived type. MapInheritedProperties remaps all properties that were inherited from the base class to new columns in the table for the derived class.

Note: Note that because the tables participating in TPC inheritance hierarchy do not share a primary key there will be duplicate entity keys when inserting in tables that are mapped to subclasses if you have database generated values with the same identity seed. To solve this problem you can either specify a different initial seed value for each table or switch off identity on the primary key property. Identity is the default value for integer key properties when working with Code First.

<code id="c_5a6cba7f50d54b29903d3ef3a18ee996">modelBuilder.Entity&lt;Course&gt;() 
    .Property(c =&gt; c.CourseID) 
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); 
 
modelBuilder.Entity&lt;OnsiteCourse&gt;().Map(m =&gt; 
{ 
    m.MapInheritedProperties(); 
    m.ToTable("OnsiteCourse"); 
}); 
 
modelBuilder.Entity&lt;OnlineCourse&gt;().Map(m =&gt; 
{ 
    m.MapInheritedProperties(); 
    m.ToTable("OnlineCourse"); 
});</code>

Mapping Properties of an Entity Type to Multiple Tables in the Database (Entity Splitting)

Entity splitting allows the properties of an entity type to be spread across multiple tables. In the following example, the Department entity is split into two tables: Department and DepartmentDetails. Entity splitting uses multiple calls to the Map method to map a subset of properties to a specific table.

<code id="c_ece124b6905f43cabcbe5b720f345ef6">modelBuilder.Entity&lt;Department&gt;() 
    .Map(m =&gt; 
    { 
        m.Properties(t =&gt; new { t.DepartmentID, t.Name }); 
        m.ToTable("Department"); 
    }) 
    .Map(m =&gt; 
    { 
        m.Properties(t =&gt; new { t.DepartmentID, t.Administrator, t.StartDate, t.Budget }); 
        m.ToTable("DepartmentDetails"); 
    });</code>

Mapping Multiple Entity Types to One Table in the Database (Table Splitting)

The following example maps two entity types that share a primary key to one table.

<code id="c_3e593cfb58574185980d28846386df8f">modelBuilder.Entity&lt;OfficeAssignment&gt;() 
    .HasKey(t =&gt; t.InstructorID); 
             
modelBuilder.Entity&lt;Instructor&gt;() 
    .HasRequired(t =&gt; t.OfficeAssignment) 
    .WithRequiredPrincipal(t =&gt; t.Instructor); 
 
modelBuilder.Entity&lt;Instructor&gt;().ToTable("Instructor"); 
 
modelBuilder.Entity&lt;OfficeAssignment&gt;().ToTable("Instructor");</code>

Mapping an Entity Type to Insert/Update/Delete Stored Procedures (EF6 onwards)

Starting with EF6 you can map an entity to use stored procedures for insert update and delete. For more details see, Code First Insert/Update/Delete Stored Procedures.

 

Model Used in Samples

The following Code First model is used for the samples on this page.

<code id="c_26192682dcbf48e98da9559a07fad38e">using System.Data.Entity; 
using System.Data.Entity.ModelConfiguration.Conventions; 
// add a reference to System.ComponentModel.DataAnnotations DLL 
using System.ComponentModel.DataAnnotations; 
using System.Collections.Generic; 
using System; 
 
public class SchoolEntities : DbContext 
{ 
    public DbSet&lt;Course&gt; Courses { get; set; } 
    public DbSet&lt;Department&gt; Departments { get; set; } 
    public DbSet&lt;Instructor&gt; Instructors { get; set; } 
    public DbSet&lt;OfficeAssignment&gt; OfficeAssignments { get; set; } 
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        // Configure Code First to ignore PluralizingTableName convention 
        // If you keep this convention then the generated tables will have pluralized names. 
        modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;(); 
    } 
} 
 
public class Department 
{ 
    public Department() 
    { 
        this.Courses = new HashSet&lt;Course&gt;(); 
    } 
    // Primary key 
    public int DepartmentID { get; set; } 
    public string Name { get; set; } 
    public decimal Budget { get; set; } 
    public System.DateTime StartDate { get; set; } 
    public int? Administrator { get; set; } 
 
    // Navigation property 
    public virtual ICollection&lt;Course&gt; Courses { get; private set; } 
} 
 
public class Course 
{ 
    public Course() 
    { 
        this.Instructors = new HashSet&lt;Instructor&gt;(); 
    } 
    // Primary key 
    public int CourseID { get; set; } 
 
    public string Title { get; set; } 
    public int Credits { get; set; } 
 
    // Foreign key 
    public int DepartmentID { get; set; } 
 
    // Navigation properties 
    public virtual Department Department { get; set; } 
    public virtual ICollection&lt;Instructor&gt; Instructors { get; private set; } 
} 
 
public partial class OnlineCourse : Course 
{ 
    public string URL { get; set; } 
} 
 
public partial class OnsiteCourse : Course 
{ 
    public OnsiteCourse() 
    { 
        Details = new Details(); 
    } 
 
    public Details Details { get; set; } 
} 
 
public class Details 
{ 
    public System.DateTime Time { get; set; } 
    public string Location { get; set; } 
    public string Days { get; set; } 
} 
     
public class Instructor 
{ 
    public Instructor() 
    { 
        this.Courses = new List&lt;Course&gt;(); 
    } 
 
    // Primary key 
    public int InstructorID { get; set; } 
    public string LastName { get; set; } 
    public string FirstName { get; set; } 
    public System.DateTime HireDate { get; set; } 
 
    // Navigation properties 
    public virtual ICollection&lt;Course&gt; Courses { get; private set; } 
} 
 
public class OfficeAssignment 
{ 
    // Specifying InstructorID as a primary 
    [Key()] 
    public Int32 InstructorID { get; set; } 
 
    public string Location { get; set; } 
 
    // When the Entity Framework sees Timestamp attribute 
    // it configures ConcurrencyCheck and DatabaseGeneratedPattern=Computed. 
    [Timestamp] 
    public Byte[] Timestamp { get; set; } 
 
    // Navigation property 
    public virtual Instructor Instructor { get; set; } 
}</code>

Simple WPF input prompt

This is the simplest way to prompt a user for input from a WPF app:

var inputBox = Microsoft.VisualBasic.Interaction.InputBox("Prompt here",
                            "Title here",
                            "Default data",
                            -1, -1);
if (inputBox == "")
    return;

you have to add a reference to the Microsoft.VisualBasic assembly

 

WPF stringformat currency to pound (£)

default formatting of currencies etc happens to US, so to override that for GB / UK etc. :

<TextBlock Text="{Binding Path=CurrentPrice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat={}{0:c}, ConverterCulture=en-GB}" />