Vuejs: Communication among components

To communicate from the parent to the child component, use props. Props are one-way: from parent to child.
Any time the parent changes the prop, the new value is sent to the child and rerendered.
However, you should never mutate a prop inside the child component.
To communicate from the child component to the parent component, use events.

Parent.vue

<template>
    <div>
        <Child :color="green" @clickedChildComponent="handleClickInParent" />
    </div>
</template>
<script>
    import Child from "./Child.vue";
    export default {
        name: "App",
        components: {
            Child,
        },
        data() {
            return {
                color: "white",
            };
        },
        methods: {
          handleClickInParent(parameter1, parameter2) {
          //...
        }
    };
</script>

Child.vue

<template>
    <p>{{ color}}</p>
</template>
<script>
    export default {
    props: {
    color{
    type:String,
    required:true,
    default:'white'
    }
    },
    methods: {
     //some control in child component generating the handleClick event.
     handleClick() {
       this.$emit('clickedChildComponent', parameter1, parameter2)
     }
    },

    }
</script>
Continue Reading

Add Log4Net to WCF application

Adding log4Net to your WCF application is straightforward.
a. Add Log4Net library into your application using Nuget.
b. Add the following code to your web.config file.

c. Add the following code to your application’s property file.

d. Add code to load Log4Net configuration from web.config file.

e. You can now log errors using your CustomLog4Net._log Log4Net instance.

Continue Reading

VueJs warning: “Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value”.

If you get a "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value" warning when working on your VueJs application, look at your code to see if you are manipulating the element’s state directly.
Not working:

<vs-tabs id="tabs" ref="tabs"> 
...............
data() {
return {
}
},
selectOperation()
{
this.$refs.tabs.value=1;
},

Working:

<vs-tabs id="tabs" ref="tabs" :value="currentTab"> 
...............
data() {
return {
currentTab:0,
}
},
selectOperation()
{
this.currentTab=1;
},
Continue Reading

“The computed property “fields” is already defined as a prop” error.

I started using Syncfusion excellent vueJs controls in my web application and I immediately started getting The computed property "fields" is already defined as a prop. error.

Solution:
I was using vee-validate in my application for validation and syncfusion controls were conflicting with my vee-validate library.
Before:
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);

After:
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate, {fieldsBagName: 'formFields'});

Continue Reading

Vuejs: custom Events

Custom Events: To call a function in Parent Parent.vue from a button in the child Child.vue, we need to use custom events for child to parent communication:

Child.vue

<template>
  <div>
    <div :id="childName"></div>
    <button v-on:click="doStuff()">Do stuff</button>  
  </div>
</template>
<script>
  export default {
    methods: {
      doStuff () {
        this.$emit('childStuff', 'some value from child')
      }
    }
  }
</script>

Parent.vue

<template>
  <div>
    <Child v-on:childStuff="value => { parentStuff(value) }"></Child>
  </div>
</template>
<script>
  import Child from './components/Child';
  export default {
    components: {Child},
    methods: {
      parentStuff (value) {
        alert(value)
      }
    }
  }
</script>
Continue Reading

Vuelidate validation without v-model

Vuelidate validation without v-model

If you don’t want to modify your model directly, you can still use separate :input and @event bindings. This is especially useful if you are using data from external source, like Vuex store or props. In that case you have to manually take care of setting the $dirty by calling $touch() method when appropriate.

javascript:


import { required, minLength, between } from 'vuelidate/lib/validators'
export default {
  data() {
    return {
      name: '',
      age: 0
    }
  },
  validations: {
    name: {
      required,
      minLength: minLength(4)
    },
    age: {
      between: between(20, 30)
    }
  },
  methods: {
    setName(value) {
      this.name = value
      this.$v.name.$touch()
    },
    setAge(value) {
      this.age = value
      this.$v.age.$touch()
    }
  }
}

html:

<div>
  <div class="form-group" :class="{ 'form-group--error': $v.name.$error }">
    <label class="form__label">Name</label>
    <input class="form__input" v-model.trim="name" 
@input="setName($event.target.value)"/>
  </div>
  <div class="error" v-if="!$v.name.required">Field is required</div>
  <div class="error" v-if="!$v.name.minLength">Name must have at least 
{{$v.name.$params.minLength.min}} letters.</div>
  <div class="form-group" :class="{ 'form-group--error': $v.age.$error }">
    <label class="form__label">Age</label>
    <input class="form__input" :value="age" @change="setAge($event.target.value)"/>
  </div>
  <div class="error" v-if="!$v.age.between">Must be between {{$v.age.$params.between.min}} and {{$v.age.$params.between.max}}</div><span tabindex="0">Blur to see changes</span>
</div>
Continue Reading

What’s New in C# 6.0 using examples.

The null-conditional operator avoids having to explicitly check for null before calling a method or accessing a type member.

System.Text.StringBuilder sb = null;
string result = sb?.ToString(); // result is null

Expression-bodied functions allow methods, properties, operators, and indexers that comprise a single expression to be written more tersely, in the style of a lambda expression:

public int TimesTwo (int x) => x * 2;
public string SomeProperty => "Property value";

Property initializers let you assign an initial value to an automatic property:

public DateTime TimeCreated { get; set; } = DateTime.Now;

Read-only properties can also be set in the constructor, making it easier to create immutable (read-only) types.
Index initializers allow single-step initialization of any type that exposes an indexer:

var dict = new Dictionary()
{
[3] = "three",
[10] = "ten"
};

String interpolation offers a succinct alternative to string.Format:

string s = $"It is {DateTime.Now.DayOfWeek} today";

Exception filters let you apply a condition to a catch block:

string html;
try
{
html = new WebClient().DownloadString ("//asef");
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.Timeout)
{
...
}

The using static directive lets you import all the static members of a type, so that you can use those members unqualified:

using static System.Console;
...
WriteLine ("Hello, world"); // WriteLine instead of Console.WriteLine

The nameof operator returns the name of a variable, type, or other symbol as a string. This avoids breaking code when you rename a symbol in Visual Studio:

int capacity = 123;
string x = nameof (capacity); // x is "capacity"
string y = nameof (Uri.Host); // y is "Host"

You’re now allowed to await inside catch and finally blocks.

Reference: C# 7.0 in a nutshell by Oreilly publications

Continue Reading

What’s New in C# 7.0 using examples.

Numeric literal improvements
Numeric literals in C# 7 can include underscores to improve readability. These are ignored by the compiler:

int million = 1_000_000;

Out variables and discards
You can now declare out variables on the fly:

bool successful = int.TryParse ("123", out int result);

And when calling a method with multiple out parameters, you can discard ones you’re uninterested in with the underscore character:

SomeBigMethod (out _, out _, out _, out int x, out _, out _, out _);

Patterns
You can also introduce variables on the fly with the is operator(pattern variables):

if (x is string s)

The switch statement also supports patterns, so you can switch on type as well as constants. You can also switch on the null value:

switch (x)
{
case bool b when b == true: // Matches only when b is true
..........
break;
case null:
...............
break;
}

Local methods
A local method is a method declared inside another function. Local methods are visible only to the containing function, and can capture local variables in the same way that lambda expressions do.

void WriteCubes()
{
Console.WriteLine (Cube (3));
int Cube (int value) => value * value * value;
}

More expression-bodied members
C# 6 introduced the expression-bodied “fat-arrow” syntax for methods, read-only properties, operators, and indexers. C# 7 extends this to constructors, read/write properties, and finalizers:

public class Person
{
string name;
public Person (string name) => Name = name;
public string Name
{
get => name;
set => name = value ?? "";
}
~Person () => Console.WriteLine ("finalize");
}

Deconstructors
C# 7 introduces the deconstructor pattern. Whereas a constructor typically takes a set of values (as parameters) and assigns them to fields, a deconstructor does the reverse and assigns fields back to a set of variables:

public void Deconstruct (out string firstName, out string lastName)
{
int spacePos = name.IndexOf (' ');
firstName = name.Substring (0, spacePos);
lastName = name.Substring (spacePos + 1);
}

Deconstructors are called with the following special syntax:

var joe = new Person ("Joe Bloggs");
var (first, last) = joe; // Deconstruction
Console.WriteLine (first); // Joe
Console.WriteLine (last); // Bloggs

Tuples
Tuples provide a simple way to store a set of related values:

var tuple = (Name:"Bob", Age:23);
Console.WriteLine (tuple.Name); // Bob

With tuples, functions can return multiple values without resorting to out parameters:

static (int row, int column) GetFilePosition() => (3, 10);
static void Main()
{
var pos = GetFilePosition();
Console.WriteLine (pos.row); // 3
Console.WriteLine (pos.column); // 10
}

Tuples implicitly support the deconstruction pattern, so they can easily be deconstructed into individual variables.

static void Main()
{
(int row, int column) = GetFilePosition(); // Creates 2 local variables
Console.WriteLine (row); // 3
}

throw expressions
With C# 7, throw can also appear as an expression in expression-bodied functions:

public string Foo() => throw new NotImplementedException();

A throw expression can also appear in a ternary conditional expression:

string Capitalize (string value) => value == null ? throw new ArgumentException ("value") : value == "" ? "" : char.ToUpper (value[0]) + value.Substring (1);

Reference: C# 7.0 in a nutshell by Oreilly publications

Continue Reading

Configure error logging using Serilog.Sinks.Postgres and appSettings.json

Install nuget packages
Serilog.Sinks.PostgreSQL
Microsoft.Extensions.Configuration.Json

Program.cs:

public class Program
   {
     public static void Main(string[] args)
     {
       var path = Directory.GetCurrentDirectory();
       var environmentName =Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
      var configuration = new ConfigurationBuilder()
         .SetBasePath(path)
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
         .AddEnvironmentVariables()
         .Build();
       Log.Logger = new LoggerConfiguration().
         Enrich.FromLogContext().
         ReadFrom.Configuration(configuration).
         CreateLogger();
      try
       {
         var iWebHost = CreateWebHostBuilder(args).Build();
         Log.Information("Application starting");
         iWebHost.Run();
       }
       catch (Exception exception)
       {
         Log.Error(exception.ToString());
       }
       finally
       {
         Log.CloseAndFlush();
       }
     }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup()
        .UseSerilog();
   }

appsettings.json:

"Serilog": {
     "Using": [ "Serilog.Sinks.PostgreSQL" ],
     "MinimumLevel": "Warning",
     "WriteTo": [
       {
         "Name": "PostgreSQL",
         "Args": {
           "connectionString": "",
           "tableName": "Logs",
           "needAutoCreateTable": true,
           "batchPostingLimit": 1
         }
       }
     ]
   }
Continue Reading

Fix for ‘’Npgsql.PostgresException: syntax error at or near ‘[‘”

We decided to change our database from SQL server to Postgres in our application. When I tried to apply the database migrations to the database it failed with a
Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "[" error.
On further analyzing the issue I found that this issue occurs as the migrations were created on SQL Server and contain SQL Server-specific code.

To fix this issue, I
a. Removed the Migrations folder in your application.
b. Ran “Add-Migration Init” in the package manager console
c. Ran “Update-Database”, to flush the SQL Server predefined context.

Continue Reading
1 2 3 6