Saturday, December 10, 2022

Difference between TAG hierarchies of BOOTSTRAP NAV and NAVBAR components

  --NAVBAR--                 --NAV--

NAVBAR                  ----------

NAVBAR-NAV                         NAV

NAV-ITEM                 NAV-ITEM

NAV-LINK                 NAV-LINK

Browser autocomplete behaviors

 Found the following strange autocomplete behaviors on both Google and Edge. 

Consider the following html for input : 


  <div class="form-group">

    <label for="emailid">Email Id :</label>

    <input type="email" class="form-control" placeholder="Enter User" id="emailid">

  </div>


In this code, note the following "HOTSPOTS" :

  <div class="form-group">

    <label for="emailid">Email Id :</label>

    <input type="email" class="form-control" placeholder="Enter User" id="emailid">

  </div> 


If you ever set these two hotspots to values like "email" , "emailaddress" , "user" , "password", the browser is likely to autofill this field. (tested with chrome and edge). 

To avoid this, just change the name slightly. e.g. from "email" to "emailid" . You will have to test which name is working by trial and error. But you have to make changes in these two places mostly, plus may be in the <label for="XXXX"> place. 


If you google on autocomplete behavior, most of the links will tell you to set autocomplete to "off" or some junk value "dsf" or some different value "differentname" or set name to some different value that id of the control. But practically none of these tricks work. 

I also found this SO https://stackoverflow.com/questions/55591018/autocomplete-off-in-html5 

which tells to include autocomplete="off" in form tag and then include a hidden input in the form with autocomplete="false". But this also did not work. 

<form autocomplete="off" >
    <input autocomplete="false" name="hidden" type="text" style="display:none;">

Wednesday, November 2, 2022

Surreal DB

 


Surreal DB does not start on alpine container, 

use ubuntu container instead 


1. Create an Ubuntu container 


docker run -d -p 17000:8000 --name ub_surreal ubuntu tail -f /dev/null


2. Exec the container  in it mode


docker exec -it -u 0 ub_surreal sh


3. Update apt  ( this is required to install curl)


apt update


This will take some time may be 2-3 mins because apt coming with container is bare minimum


4. Install curl

 

apt install curl


Press 'Y' when prompted 


5. 


curl -sSf https://install.surrealdb.com | sh


This will install surreal db. 


6. Start surreal db


surreal start --log debug --user root --pass root memory


This will start surreal and keep it started. 


7. Open another command prompt and again open the same container with EXEC command: 


docker exec -it -u 0 ub_surreal sh


8. Now you can give the command and use surrealdb. 

For example you can give the following command: 


curl --request POST --header "Accept: application/json"    --header "NS: test" --header "DB:test" --user "root:root"  --data "INFO FOR DB;"  http://localhost:8000/sql


you should get a response like 

[{"time" : "47.432ms" , "status" : "OK" , "result" : { "d1" : {} , "dt" : {}, "sc" : {} , "tb" : {}}}]









https://www.freecodecamp.org/news/how-to-use-surrealdb-with-fresh-framework/



========================================================================

Start Surreal using dockerfile


1. Execute the following dockerfile:

========================================================================

Dockerfile

========================================================================

FROM ubuntu

RUN apt update 

RUN apt-get install -y  curl 

RUN curl -sSf https://install.surrealdb.com | sh

CMD surreal start --log debug --user root --pass root memory

========================================================================



NOTE the use of  apt and apt-get : apt-get has more features than apt, 

i.e. apt is a stripped down vesrion of apt-get



2. Build the above docker file:


docker build  -t surreal-image . 


NOTE : image name must be all smalls.


3. Run it: 

docker run -p 17000:8000 -d --name surrealdb surreal-image


4. Execute it: 

docker exec -it -u 0 surrealdb sh


5. Execute the following command on shell: 

surreal sql -c http://localhost:8000


You will be presented with surreal sql prompt. ( >) 


>info for db <Enter>

[{"time" : "23.728ms" , "status" : "ERR" , "detail" : "Specify a namespace to use"}]



6. Now exit sql shell by pressing ctrl + C and enter the following command: 

surreal sql -c http://localhost:8000 --ns test --db test

>info for db


[{"time" : "50.292ms" , "status" : "OK" , "result" : { "d1" : {} , "dt" : {}, "sc" : {} , "tb" : {}}}]


> create account set name = 'test' , created_at = time::now()



> CREATE author:john SET name.first = 'John' ,  name.last = 'Adams' , name.full = string::join(' ', name.first, name.last) , age = 29, admin  = true,  signup_at = time::now();


> select * from author, account;


Sunday, September 25, 2022

KUBERNETES COMMANDS

 minikube version 

kubectl version 


minikube start   #starts cluster 

kubectl cluster-info

kubectl get nodes

kubectl get pods

kubectl get services


kubectl create deployment kubernetes-bootcamp --image=gcr.io/google-samples/kubernetes-bootcamp:v1


kubectl proxy 



kubectl get pods -o  go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'


$export POD_NAME=$(kubectl get pods -o  go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}')



kubectl get pods -o  go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'


Saturday, August 20, 2022

C# Linq Min method

// Online C# Editor for free

// Write, Edit and Run your C# code using C# Online Compiler


using System;

using System.Linq;

using System.Collections.Generic;


public class HelloWorld

{

    public static void Main(string[] args)

    {

        List<test> testlist = new List<test>();

        testlist.Add(new test { id = 5});

        testlist.Add(new test { id = 7});

        testlist.Add(new test { id = 2});

        testlist.Add(new test { id = 8});

        //find the min

        var min = testlist.Min(x=>x.id);

        

        //get the object with min component

        var y = testlist.Where(x=>x.id == min).FirstOrDefault();

        Console.WriteLine ($"The min is  {min} {y}  {y.id}");

    }

    

    public class test { 

        public int id { get;set;} 

    } 

}

Output: 

The min is  2 HelloWorld+test  2


NOTE: {y} prints "HelloWorld+test" which is the object hierarchy of parent class and contained class.


Wednesday, July 13, 2022

Nuget PMC Error while adding migration: The entity type 'Employee' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.

 This happens when you dont define primary key for an entity type. 


Define a primary key either explicitly or implicitly. 

Nuget PMC error: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

 This error means you have created the DbContext but not configured/added  it to the project using either DI in startup.cs or by using DbContext.OnConfiguring method. 


Add DbContext in starup.cs or configure it by overriding the virtual  DbContext.OnConfiguring  method.

============================================================

  1. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  2. {
  3. optionsBuilder.UseSqlServer("server=.;database=myDb;trusted_connection=true;");
  4. }

NOTE to use connectionString from appsetting.json. follow these steps:
1. In appsettings.json add ConnectionStrings section below allowedhosts and add a name-value pair for connection string.
2. Inject IConfiguration in DbContext constructor. You will need to add "using Microsoft.Extensions.Configuration" statement for this.
3. You can now get the conn string by using configuration.GetConnectionString("name");
    public class EmployeeContext : DbContext
    {
        
        private readonly IConfiguration configuration;
        public DbSet<Employee> Employees { get; set; }

        public EmployeeContext(IConfiguration configuration)
        {
            this.configuration = configuration;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string str = configuration.GetConnectionString("conn");
            optionsBuilder.UseSqlServer(str);
        }
    }

===================================================================================


  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddDbContext<MyDbContext>(options => {
  4. options.UseSqlServer("server=.;database=myDb;trusted_connection=true;"));
  5. });
  6. }

OR
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<EmployeeContext>(options => {
            options.UseSqlServer(Configuration.GetConnectionString("conn")));
        }



NOTE that once you configure DbContext in ConfigureServices, you must wire it with DbContext by using a constructor that takes DbContextOptions as parameter and passes it to base contructor.


public class EmployeeContext : DbContext { public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options) { } DbSet<Employee> Employees { get; set; } }
  1. ===================================================================================

Monday, July 11, 2022

Git Pull Request

 1. Create new branch 

git checkout -b test 



2. Make changes and do add, commit and push. 

While pushing  changes, keep in mind you have to mention 

branch name as "test" 


git push origin test 


3. Now go to Azure and create a Pull Request. 


Select "test" as source branch and "main" as destination branch


Friday, July 1, 2022

Sql Server OFFSET and FETCH

 https://www.sqlservertutorial.net/sql-server-basics/sql-server-offset-fetch/



SQL Server OFFSET and FETCH

Sunday, June 26, 2022

flexbox form example

 https://webdesign.tutsplus.com/tutorials/building-responsive-forms-with-flexbox--cms-26767



<style>

body {

  font: normal 18px/1.5 "Fira Sans", "Helvetica Neue", sans-serif;

  background: #3AAFAB;

  color: #fff;

  padding: 50px 0;

}


.container {

  width: 80%;

  max-width: 1200px;

  margin: 0 auto;

}


.container * {

  box-sizing: border-box;

}


.flex-outer,

.flex-inner {

  list-style-type: none;

  padding: 0;

}


.flex-outer {

  max-width: 800px;

  margin: 0 auto;

}


.flex-outer li,

.flex-inner {

  display: flex;

  flex-wrap: wrap;

  align-items: center;

}


.flex-inner {

  padding: 0 8px;

  justify-content: space-between;  

}


.flex-outer > li:not(:last-child) {

  margin-bottom: 20px;

}


.flex-outer li label,

.flex-outer li p {

  padding: 8px;

  font-weight: 300;

  letter-spacing: .09em;

  text-transform: uppercase;

}


.flex-outer > li > label,

.flex-outer li p {

  flex: 1 0 120px;

  max-width: 220px;

}


.flex-outer > li > label + *,

.flex-inner {

  flex: 1 0 220px;

}


.flex-outer li p {

  margin: 0;

}


.flex-outer li input:not([type='checkbox']),

.flex-outer li textarea {

  padding: 15px;

  border: none;

}


.flex-outer li button {

  margin-left: auto;

  padding: 8px 16px;

  border: none;

  background: #333;

  color: #f2f2f2;

  text-transform: uppercase;

  letter-spacing: .09em;

  border-radius: 2px;

}


.flex-inner li {

  width: 100px;

}

</style>




<div class="container">

  <form>

    <ul class="flex-outer">

      <li>

        <label for="first-name">First Name</label>

        <input type="text" id="first-name" placeholder="Enter your first name here">

      </li>

      <li>

        <label for="last-name">Last Name</label>

        <input type="text" id="last-name" placeholder="Enter your last name here">

      </li>

      <li>

        <label for="email">Email</label>

        <input type="email" id="email" placeholder="Enter your email here">

      </li>

      <li>

        <label for="phone">Phone</label>

        <input type="tel" id="phone" placeholder="Enter your phone here">

      </li>

      <li>

        <label for="message">Message</label>

        <textarea rows="6" id="message" placeholder="Enter your message here"></textarea>

      </li>

      <li>

        <p>Age</p>

        <ul class="flex-inner">

          <li>

            <input type="checkbox" id="twenty-to-twentynine">

            <label for="twenty-to-twentynine">20-29</label>

          </li>

          <li>

            <input type="checkbox" id="thirty-to-thirtynine">

            <label for="thirty-to-thirtynine">30-39</label>

          </li>

          <li>

            <input type="checkbox" id="fourty-to-fourtynine">

            <label for="fourty-to-fourtynine">40-49</label>

          </li>

          <li>

            <input type="checkbox" id="fifty-to-fiftynine">

            <label for="fifty-to-fiftynine">50-59</label>

          </li>

          <li>

            <input type="checkbox" id="sixty-to-sixtynine">

            <label for="sixty-to-sixtynine">60-69</label>

          </li>

          <li>

            <input type="checkbox" id="other">

            <label for="other">Othessr</label>

          </li>

        </ul>

      </li>

      <li>

        <button type="submit">Submit</button>

      </li>

    </ul>

  </form>

</div>

Tuesday, May 17, 2022

EF irrelevant error when creating migration It was not possible to find any compatible framework version

 When adding a migration you may get following error: 

It was not possible to find any compatible framework version
The framework 'Microsoft.NETCore.App', version '2.0.0' (x64) was not found.
- The following frameworks were found:
3.1.22 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
5.0.13 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
6.0.1 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

You can resolve the problem by installing the specified framework and/or SDK.



Please note that this error is totally wrong and irrelevant. This is not an error of framework version, but error of path declarations. 


The best way to resolve this error is  

1. Make the Web API project a startup project. 

2. Select the project where DBContext resides as default in PM console. 

3. In PM Console, navigate to the path of Web API project. 

4. Now give the following command : 

dotnet ef migrations add NameOfYourMigration --project  ..\PathOfDbContextProject\DbContextProject.csproj


Remember the command "dotnet ef migrations add"  some people forget to write "migrations" , they write "migration" instead. 


Sunday, May 15, 2022

for ref

 what is proxy.conf.ts 


what is @ViewChild and @ViewChildren



What is parallel.ForEach 


What is Plinq


How can we check the query generated by entity framework ? 

What is global assembly cache ? 


What is CLR and CTS ? 


These are parts of a larger specification called CLI (common language infrastructure) 


CLI consists of: 

1. CTS 

2. Metadata (PE files specification - portable executables) 

3. CLS (Common Language Specification)  - common set of  features that every CLI compliant language must expose

4. VES (Virtual Execution System) - CLR 

All the CLI compliant languages are statically compiled to CIL (Common Intermediate Language) code 

CLR JIT compiles CIL to native code, caches the code and executes it. 

High Level Code to CIL -> static compilation  (generates dlls , 

or if Portable options is selected generates PE file for 32 bit, PE+ for 64 bit)

CIL to native code -> JIT compilation by CLR

AOT compiler-> translate IL to machine code -> can better optimize code

JIT compiler ->  translate IL to machine code 

There are two versions of CLR : CLR and CoreCLR. CoreCLR can JIT for targets such as Windows, linux and macOS.

CLR Handles memeory management and garbage collection. 


Which are the languages supported by CLI/CLR ? 

C#, VB.NET , Python/PASCAL ports are also available.



Which are the types supported by CTS ? 

Classes

Structures

Enumeration

Interfaces

Delegates


Are delegates type  safe than a function pointer ? how ? 

Delegates are guranteed to be refer to  a valid method with correct signature, a pointer can mistakenly be assigned to something else also. 

Secondly delegates can bind to a method of an object , rather than a class. 



The type double in C# is a floating point type. How do classify C# numeric types 

in floating and fixed point types ? 



Is EntityFramework (or Dbcontext) thread safe ? 

No. EF /DbContext are safe only when each thread uses separate Dbcontext. 

So if you are using DbContext in Parallel.ForEach loop, better to instantiate 

a new DbContext on every iteration. 

=============================================================================

https://www.codemag.com/article/1407051/Python-for-C#Back2article

Python for C# Developers  By Michael Kennedy 

A very important article comparing features of Python and C#


https://www.red-gate.com/simple-talk/development/dotnet-development/10-reasons-python-better-than-c-sharp/

10 reasons why Python is better than C# (or almost any other programming language)

By Andy Brown

=============================================================================

What is Task Parallel Library ? 

Most of the desktops/laptops in today's scenario use multicore CPUs. 

The true adavantage of multicore CPUs can only be taken when the we can run 

tasks simultaneously on multiple cores. 

C# provides parallel computing through TPL. 

TPL provides two types of parallelism : 

Data Parallelism : 

Parallel.For method 

Parallel,ForEach method

Task Parallelism: 

Parallel.Invoke


What types of tasks can be executed parallely ? 

For parallel execution : 

Tasks should be independent of each other. 

Order of execution should not matter


What is the difference between standard For loop and Parallel.For loop ? 

1. Standard for loop executes in a single thread where as Parallel.For loop executes in multiple threads

2.Standard for loop executes in sequential order but Paralllel.For loop will not execute in order. 



Parallel is a static class with static For, ForEach and Invoke methods. 


 public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body);

NOTE that the first parameter is  Inclusive and  end parameter is Exclusive. 



How do you control the degree of parallelism in Parallel.For loop ? 


By using MaxDegreeOf Parallelism. 


We can pass a ParallelOptions parameter to Parallel.For loop as third parameter. 

In this ParallelOptions object we can set MaxDegreeOfParalllism: 


var options = new ParallelOptions (){ 

MaxDegreeOfParallelism = 2 


Parallel.For( 0, 100 , options, x=> {} );


If MaxDegreeOfParallelism is set to -1, then there is no limit on the number of concurrently running tasks.


How to limit MaxDegreeOfParallelism to use maximum 75% of resources ? 

int NoOfCoresPerProcessor = 2;

new ParallelOptions

{

    MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * NoOfCoresPerProcessor ))

};


ParallelLoopState.Stop and ParallelLoopState.Break methods 

In Break: 

all the previous iterations are completed (index < LowestBreakIteration) 

all the higher index iterations will exit at their convenience

In Stop: 

all iterations will exit at thier convenience


What is the difference between parallelism and concurrency ? 

In concurrency, tasks take turn for execution. So if tasks T1 and T2 

are executing, when T1 executes, T2 waits for its turn and vice versa. 

But in parallelism, both tasks execute at same time. 



How to determine if the parallel loop is complete ? 

By using ParallelLoopResult.IsCompleted flag. 

Console.WriteLine("IsCompleted: {0}", parallelLoopResult.IsCompleted);


Potential pitfalls : 

https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/potential-pitfalls-in-data-and-task-parallelism


===================================================================

Blockchain C# 

https://www.c-sharpcorner.com/article/building-a-blockchain-in-net-core-p2p-network/

Building A Blockchain In .NET Core - P2P Network

Henry He

===================================================================

http://dotnetpattern.com/top-linq-interview-questions

code with mukesh 

C# Corner  sarathlal saseendran

===================================================================

Repository and dapper 

http://www.mukeshkumar.net/articles/web-api/dapper-and-repository-pattern-in-web-api

https://cpratt.co/truly-generic-repository-2/

https://www.c-sharpcorner.com/article/implement-unit-of-work-and-generic-repository-pattern-in-a-web-api-net-core-pro/

https://www.c-sharpcorner.com/article/implement-unit-of-work-and-generic-repository-pattern-in-a-web-api-net-core-pro/

====================================================================

How do put a cap on the maximum size of a file that can be uploaded in a WEB API using multiplart mime type ? 
services.Configure<FormOptions>(options => { // Set the limit to 256 MB options.MultipartBodyLengthLimit = 268435456; });

Saturday, May 14, 2022

EF Error : Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side.

 I was trying out code from an article on c# corner  related to angular and web api. 

In one of the methods, there was a code like: 

        public IQueryable<Authors> GetAuthors()

        {

            return _dbContext.ArticleMatrices.GroupBy(author => author.AuthorId)

                  .Select(group =>

                        new Authors

                        {

                            AuthorId = group.FirstOrDefault().AuthorId,

                            Author = group.FirstOrDefault().Author,

                            Count = group.Count()

                        }).

                  .OrderBy(group => group.Author);

        }


This was a GET web api method so I tried calling it from browser. Suddenly I encountered following error : 

Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side.


I found that the extension methods GroupBy , Select and OrderBy work on different input types. 

GroupBy works on IEnumerable 

Select works on  IEnumerable

But OrderBy works on IQueryable


GroupBy above gives error because _dbContext.EntityName returns IQueryable and GroupBy expects IEnumerable. 

Select works on IEnumberable so no issue for it. 

But OrderBy expects IQueryable ! 


Changing the above code as following worked: 


        public IQueryable<Authors> GetAuthors()

        {

            return _dbContext.ArticleMatrices.AsEnumerable().GroupBy(author => author.AuthorId)

                  .Select(group =>

                        new Authors

                        {

                            AuthorId = group.FirstOrDefault().AuthorId,

                            Author = group.FirstOrDefault().Author,

                            Count = group.Count()

                        }).AsQueryable()

                  .OrderBy(group => group.Author);

        }

What is application bootstrapping in angular ?

 Bootstrapping is the process of starting application in angular. 

The entry point for an angular application is index.html. 


Index.html loads required javascripts. Then angular loads the main module and components which are by default app.module and app.component. 


Angular booting is a six step process: 

  1. Load index.html
  2. Load Angular, Other Libraries, and App Code
  3. Execute main.ts File
  4. Load App-Level Module
  5. Load App-Level Component
  6. Process Template



https://www.pluralsight.com/guides/bootstrapping-an-application-in-angular

https://angular.io/guide/bootstrapping


Angular NgModule is a component which specifies how different part of the application fit togather.

@NgModule decorator takes  four metadata objects: 


declarations

imports

providers 

bootstrap



Frequently used Angular modules 

BrowserModule

CommonModule  (NgIf and NgFor)

FormsModule

ReactiveFormsModule

RouterModule

HttpClientModule

Note that BrowserModule imports CommonModule and re-exports it.

Sunday, May 8, 2022

Kamil Grzybek

 

https://www.kamilgrzybek.com/

https://www.kamilgrzybek.com/


https://github.com/kgrzybek/modular-monolith-with-ddd




seeing sharply


https://www.blog.jamesmichaelhickey.com/Practical-Coding-Patterns-For-Boss-Developers-Special-Case/

Some good links for Redis

Sitepoint Redis


Redis C# Corner Sarathlal




Difference between Include and ThenInclude 

Difference between Select and SelectMany ==> 

SelectMany flattens the resultset if it contains collections of collections 

Is there any difference if there is no collection of collections in resultset 

Monday, April 18, 2022

Simplest Angular Popup box

 1. app.component.html (Note that we are using same method call on two buttons: this is your choice. you can use different method calls also.) Also note the property binding [] for style in popup div. It should be [] and not () !.



<div >
  <label>This is main page div</label>
  <button (click)="onButtonClick()">Open Popup</button>
</div>


<div  [style]="popupHideShow" class="modal">
  <div class="modal-content">
    <label>This is popup</label>
    <button (click)="onButtonClick()">Close Popup</button>
  </div>
</div>

2. app.component.ts   : The sole work is to toggle "display:block" or "display:none" depending on button press.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'simplest-popup';
  popupHideShow = "display:none";

  onButtonClick()
  {
    if ( this.popupHideShow == "display:none")
    {
      this.popupHideShow = "display:block";
    }
    else
    {
      this.popupHideShow = "display:none";
    }
  }
}

3. The Most important : app.component.css



.modal {
    display: none;
    position: fixed; /* this is imp, otherwise popup will not fill entire screen */
    z-index: 1;
    top: 0;
    left:0;
    width:100%;
    height:100%;
    overflow: auto;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0, 0.4);
}

.modal-content {
    width:80%;  /* as per your requirement , width of popup relative to screen */
    margin:15% auto;
    padding:20px;
    border: 1px solid #888;
    background-color: #fefefe;
}

 using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...