Wednesday, 3 November 2021

git rebase command - baseed on master branch to our branch

Get the latest changes from master branch to our branch

below is the command to do rebase on top branch

git pull --rebase origin master

Monday, 18 October 2021

radial gradient - multipule color css

                                                

 <h2 class="text-center" style="margin-top: 0; padding-top: 30px; padding-bottom: 30px; background: radial-gradient(farthest-side circle at 100px 35px, #f6d0ea, #d8f7f8 86%);">Azure SignalR Group Chat</h2>

    <div class="container" style="height: calc(100% - 110px);"><div>

background: radial-gradient(farthest-side circle at 100px 35px, #f6d0ea, #d8f7f8 86%);




Monday, 11 October 2021

CROSS APPLY and get inner json node details

 SELECT s.StudentId,

s.StudentName,

s.[Message],

[m].MessageType,

[m].[Subject],

[m].[MessageBody]

FROM Student s 

CROSS APPLY OPENJSON([Message], '$.Messages') sm

CROSS APPLY OPENJSON(sm.value)

WITH

(

MessageType NVARCHAR(50),

[Subject] NVARCHAR(50),

[MessageBody] NVARCHAR(50)

) AS [m]


--Insert into Student values(1,'TestStudent','{"Messages": [{"MessageType": "Email","Subject": "Payment","MessageBody":"Kindly pay your school bill amount {amount}"},{"MessageType": "Sms","Subject": "Payment","MessageBody":"Kindly pay your school bill amount {amount}"}]}')


Friday, 1 October 2021

How to get Xml Inner node value using c#

How to get Xml Inner node value using c#

<?xml version="1.0"?>

<Document xmlns="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sdtc="urn:hl7-org:sdtc">

   <docTime value="19981001064138-0400"/> 

</Document>

Name space: xmlns="urn:hl7-org:v3"
Node: DocTime

C# code:

XDocument doc = XDocument.Parse(xmlData);

var docTime = doc.Descendants(XName.Get("{urn:hl7-org:v3}docTime")).FirstOrDefault().FirstAttribute.Value;

result of docTime: 19981001064138-0400


Dynamic Linq query in Core

Dynamic Linq:

namespace System.Linq.Dynamic.Core

https://dynamic-linq.net/

Example in Fiddler:

https://dotnetfiddle.net/GdxsMG


var context = new EntityContext();

// Example 1: Strongly styped = normal LINQ

var example1 = context.Customers

.OrderBy(c => c.City).ThenBy(c => c.CompanyName)

.ToList();

FiddleHelper.WriteTable(example1);


// Example 2: Dynamic

var example2 = context.Customers

.OrderBy("City, CompanyName")

.ToList();

FiddleHelper.WriteTable(example2);


// Example 3: Dynamic

var example3 = context.Customers

.OrderBy("City").ThenBy("CompanyName desc")

.ToList();

FiddleHelper.WriteTable(example3);


// Example 4: Dynamic

var example4 = context.Customers

.OrderBy("City, CompanyName desc")

.ToList();

FiddleHelper.WriteTable(example4);



Friday, 24 September 2021

String Split and get nth values in Sql (or) nth highest salary in sql and alternative of string_split

 DECLARE @ AS VARCHAR(MAX) = 'param0,param1,param3,param4'

SELECT VALUE FROM

(

    SELECT VALUE , ROW_NUMBER() OVER (ORDER BY (SELECT null)) rn FROM STRING_SPLIT(@, ',')

)x where rn = 3

GO


OR


DECLARE @str VARCHAR(100) = 'param0,param1,param3,param4';

SELECT *

FROM OPENJSON('["' +  REPLACE(@str,',','","') + '"]')

-----------


Get value By position in the string:

DECLARE @str VARCHAR(100) = 'param0,param1,param3,param4';

SELECT *

FROM OPENJSON('["' +  REPLACE(@str,',','","') + '"]')

WHERE [key]=2;


--------------------------

String_split altenative for string split with position: 


DECLARE @dlmt NVARCHAR(10)=N',';

DECLARE @pos INT = 2;

declare @input varchar(max)= 'a,b,c';

SELECT CAST(N'<x>' + REPLACE(@input,@dlmt,N'</x><x>') + N'</x>' AS XML).value('/x[sql:variable("@pos")][1]','nvarchar(max)')

Wednesday, 4 August 2021

xls file data import to database using c#

 xls ( Excel sheet ) file data import to database using c#

string path = string.Concat(Server.MapPath("~/UploadFileFolder/" + FileUpload1.FileName));  

                    FileUpload1.SaveAs(path);  

                    string excel = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);  

                    using (OleDbConnection con = new OleDbConnection(excel))  

                    {  

                        OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", con);  

                        con.Open();  

                        OleDbDataAdapter da = new OleDbDataAdapter(cmd);

                        DataSet ds = new DataSet();

                        da.Fill(ds);

                    }  

Monday, 26 July 2021

File input control with Upload buttion in AngularJs and WebAPI example

File upload in AngularJs and WebAPI example:

Index.html

<!DOCTYPE html>


<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <style type="text/css">

        body {

            font-family: Arial;

            font-size: 10pt;

        }


        .thumb {

            width: 24px;

            height: 24px;

            float: none;

            position: relative;

            top: 7px;

        }


        form .progress {

            line-height: 15px;

        }


        .progress {

            display: inline-block;

            width: 100px;

            border: 3px groove #ccc;

        }


        .progress > div {

            font-size: smaller;

            background-color: red;

            width: 0%;

        }

    </style>

</head>

<body>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js"></script>

    <script type="text/javascript">

        var app = angular.module('MyApp', ['ngFileUpload'])

        app.controller('MyController', function ($scope, Upload, $timeout) {

            $scope.SelectedFiles;

            $scope.UploadFiles = function (files) {

                $scope.SelectedFiles = files;

            }

            $scope.SaveFiles = function () {

                //$scope.SelectedFiles = files;

                if ($scope.SelectedFiles && $scope.SelectedFiles.length) {

                    Upload.upload({

                        url: '/Home/FileUpload/',

                        data: {

                            files: $scope.SelectedFiles

                        }

                    }).then(function (response) {

                        $timeout(function () {

                            $scope.Result = response.data;

                        });

                    }, function (response) {

                        if (response.status > 0) {

                            var errorMsg = response.status + ': ' + response.data;

                            alert(errorMsg);

                        }

                    }, function (evt) {

                        var element = angular.element(document.querySelector('#dvProgress'));

                        $scope.Progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));

                        element.html('<div style="width: ' + $scope.Progress + '%">' + $scope.Progress + '%</div>');

                    });

                }

            };

        });

    </script>

    <div ng-app="MyApp" ng-controller="MyController">

        <input type="file" multiple="multiple" ngf-select="UploadFiles($files)" />

        <input type="button" value="save" ng-click="SaveFiles()"/>

        <hr />

        Files:

        <ul><li ng-repeat="file in SelectedFiles">{{file.name}}</li></ul>

        <div id="dvProgress" class="progress" ng-show="Progress >= 0">

        </div>

    </div>

</body>

</html>



In WebAPI, HomeController

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ContentResult FileUpload()
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            foreach (string key in Request.Files)
            {
                HttpPostedFileBase postedFile = Request.Files[key];
                postedFile.SaveAs(path + postedFile.FileName);
            }

            return Content("Success");
        }
    }

Friday, 23 July 2021

Upload large files in Angular 2 or more and download files

Upload large files in Angular 2 or more:


For reference: 

https://stackoverflow.com/questions/60182054/upload-large-files-using-angular-8-and-net-core-web-api


download files:

https://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2-or-greater


Tuesday, 4 May 2021

Generate POCO classes in Asp.net Core

Generate POCO classes in  Asp.net Core:

Step1: Install NuGet packages

The following NuGet packages should be added to work with the SQL Server database and scaffolding. Run these commands in Package Manager Console:

Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Step2:

Scaffolding:
ASP.NET Core has a feature called scaffolding, which uses T4 templates to generate code

Run the following scaffold command in Package Manager Console:

Scaffold-DbContext "Server=***sqll.database.windows.net;Initial Catalog=TestDB;Persist Security Info=False;User ID=sa;Password=password1;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -force -Schemas "dbo","otherdbo" -OutputDir EFData -Context EFDataContext -DataAnnotations


or (with out schema)

Scaffold-DbContext "Server=***-sql.database.windows.net;Initial Catalog=TestDB;Persist Security Info=False;User ID=sa;Password=password1;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir EFData -Context EFDataContext 


Use -force flog to override existing generated classes:

Scaffold-DbContext "Server=***dev-sql.database.windows.net;Initial Catalog=HealthGrid;Persist Security Info=False;User ID=sa;Password=password1;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -force -OutputDir EFData -Context ClinicalTrialDataContext


Simply:

Scaffold-DbContext “DataContext “Server=***sql.database.windows.net;Database=TestDb;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir EFData"

or

Scaffold-DbContext "Data Source=***-sql.database.windows.net;Initial Catalog=TestDd;Persist Security Info=True;User ID=sa;Password=password1;MultipleActiveResultSets=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir EFData -Context DataContext

Generate for specific table:

Scaffold-DbContext "server=localhost;user=sa;password=pass;database=testdb"

     MySql.Data.EntityFrameworkCore -OutputDir EFData

     -Tables actor,film,film_actor,language -f 

Thursday, 29 April 2021

Load Partial view (MVC) into a div dynamically using Ajax in MVC or MVC Core

Load Partial view (MVC) into sectionPatient div dynamically using Ajax

<div id="sectionPatient"></div>

var patientInfoUrl = '@Url.Action("ActionName", "ControllerName")';


1. Using Post method

        var patientObj = {};

        patientObj.LastName = $('#s_txtLastName').val();

        patientObj.FirstName = $('#s_txtFirstName').val();

        patientObj.PatientBirthDate = $('#s_txtPatientDOB').val();

        patientObj.EMail = $('#s_txtEmailAddress').val();

        patientObj.MobileNumber = $('#s_txtMobilePhone').val();


        $.ajax({

            url: patientInfoUrl,

            contentType: "application/json; charset=utf-8",

            type: 'POST',

            dataType: 'html',

            data: JSON.stringify(patientObj),

            success: function (data) {

                $('#sectionPatient').html(data);

            },

            error: function (ehr) {

                console.log(ehr);

            }

        });


2. using Get method

$('#sectionPatient').load(patientInfoUrl, function () {

        });




Sunday, 29 December 2019

Display image center in the Div height

<div id="divMain">
<img src="#" class="image"/>
</div
#divMain {
    position: relative;
    width: 200px;
    height: 200px;
}
img {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
}
.image {
    min-height: 50px
}

Monday, 23 September 2019

Regular expression in c# - 7 digits with 2 decimal places


Regular expression  in c# - 7 digits with 2 decimal places
eg: 1234567.12
or 123.12
or 123
or 123.11


^-?(0|[1-9]\d{0,6})([,\.]\d{1,2})?$


BEFORE COMMA:

^ - beginning of the string

-? - there may be zero or one negative sign

0 - decimal may starts with only single zero at the beginning...

| - or ...

[1-9] - with any digit from 1 to 9

\d{0,6} - followed by any 7 digits

AFTER COMMA:

[,.] - there may be "," or "."

\d{1,2} - followed by 1 or 2 digits

(...)? - zero or one time

$ - end of the string

Wednesday, 18 September 2019

Factory Pattern - Live example


Factory Pattern - Live example


Definition:

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Example: Download

Taken a abstract class/interface which contain all factory methods(definitions/signatures).

Base Class: declare all abstract methods

Child Class 1: inherit base class
Child Class 2: inherit base class
In the creator class, object instance will create dynamically based on configuration.




Monday, 9 September 2019

Check if an object exists in a JavaScript array using jQuery


Check if an object exists in a JavaScript array using jQuery

If you would like to find an object in existing JavaScript array, below is the sample example.

var list= [];

var obj1 = {id:1,name:'paramesh'};

var exist=$.grep(list, function(obj) {
  return obj.name === 'john'; 
});

if(exist.length===0){
  list.push(obj1);
}

Friday, 23 August 2019

ObservableCollection in WPF


ObservableCollection:

1. An ObservableCollection is a dynamic collection of objects of a given type.

2. Objects can be added, removed or be updated with an automatic notification of actions. 

3. When an object is added to or removed from an observable collection, the UI is automatically updated. 

4. This happens because, when binding to an observable collection, WPF automatically adds a CollectionChanged event handler to the ObservableCollecion's events.

5. An ObservableCollection works essentially like a regular collection except that it implements the interfaces:
INotifyCollectionChanged,
INotifyPropertyChanged

6. As such it is very useful when you want to know when the collection has changed. 

7. An event is triggered that will tell the user what entries have been added/removed or moved.

8. More importantly they are very useful when using databinding on a form.

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Documents;

namespace MyObservable
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<Person> person; // Declare ObservableCollection with Person class

        public MainWindow()
        {
            InitializeComponent();

            //In the Minwindow constructor, we are adding 2 persons(Param,Smith)
            person = new ObservableCollection<Person>()
            {
                new Person() { FirstName = "G", LastName = "Param", Age =36, Address = "India", ZipCode = "530041"},
                new Person() {FirstName = "P", LastName = "Smith", Age =40, Address = "US", ZipCode = "555212"}
            };
            lstNames.ItemsSource = person;//lstNames is listbox, we have taken in the MainWindow.xaml

        }

        private void btnNames_Click(object sender, RoutedEventArgs e)
        {
            int age = 0;
            int.TryParse(txtAge.Text, out age);

            person.Add(new Person() { FirstName = txtFName.Text, LastName = txtLName.Text, Age = age, Address = txtAddress.Text, ZipCode = txtZipCode.Text });

            txtFName.Text = string.Empty;
            txtLName.Text = string.Empty;
            txtAge.Text = string.Empty;
            txtZipCode.Text = string.Empty;
            txtAddress.Text = string.Empty;
        }
    }

    //eg: Person contains 5 properties as below
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string ZipCode { get; set; }
    }
}

MainWindow.xaml:

<Window x:Class="MyObservable.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Observable Collection" Height="300" Width="400">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Grid.Column="0" Margin="5,5,5,5">
            <TextBlock x:Name="lblFName" Text="First Name"></TextBlock>
            <TextBox x:Name="txtFName"></TextBox>
            <TextBlock x:Name="lblLName" Text="Last Name"></TextBlock>
            <TextBox x:Name="txtLName"></TextBox>
            <TextBlock x:Name="lblAge" Text="Age"></TextBlock>
            <TextBox x:Name="txtAge"></TextBox>
            <TextBlock x:Name="lblAddress" Text="Address"></TextBlock>
            <TextBox x:Name="txtAddress"></TextBox>
            <TextBlock x:Name="lblZipCode" Text="ZipCode"></TextBlock>
            <TextBox x:Name="txtZipCode"></TextBox>
            <Button Grid.Column="0" Width="100" Height="20" Margin="5,5,5,5" x:Name="btnNames" Click="btnNames_Click" Content="Add"></Button>
        </StackPanel>

        <ListView x:Name="lstNames" Margin="5,5,5,5" Grid.Column="1" Grid.Row="0">
            <ListView.View>
                <GridView x:Name="grdNames">
                    <GridViewColumn Header="First Name"  DisplayMemberBinding="{Binding FirstName}"/>
                    <GridViewColumn Header="Last Name"  DisplayMemberBinding="{Binding LastName}"/>
                    <GridViewColumn Header="Age"  DisplayMemberBinding="{Binding Age}"/>
                    <GridViewColumn Header="Address"  DisplayMemberBinding="{Binding Address}"/>
                    <GridViewColumn Header="ZipCode"  DisplayMemberBinding="{Binding ZipCode}"/>
                </GridView>
            </ListView.View>
        </ListView>
        
    </Grid>

</Window>


Normal CLR Property and Dependency Property in WPF

Normal CLR Property and Dependency Property in WPF

Normal CLR Property:

private int count;
public int Count
{
   get
   {
      return count;
   }
   set
   {
      count = value;
   }
}

Dependency Property:

public static DependencyProperty PageSizeProperty =
DependencyProperty.RegisterAttached("PageSize",
typeof(int), typeof(AttachedPropertySample),
             new PropertyMetadata(25,
             new PropertyChangedCallback(OnPageSizePropertyChanged)));

public int PageSize
{
    get
    {
        return (int) GetValue(PageSizeProperty);
    }
    set
    {
        SetValue(PageSizeProperty, value);
    }
}

The Normal CLR property and the dependency property look quite similar but the dependency property is more powerful and has more features.

In WPF, dependency properties are used in Animation, Styles, Triggers, Templates, Validation, Data Binding, Layout etc.

1. In Built Change Notification:

Dependency provides change notification when its value has been changed. You can specify Call Back while registering dependency property so user will get notification. This is mainly used in Data Binding. But CLR property has not any inbuilt change notification. So if you want your normal CLR proprety also notify changes, you have to implement INotifyPropertyChanged.

2. Value Resolution

CLR property reads value directly from private member while dependency property dynamically resolves value when you call GetValue() method of dependency property. The GetValue and SetValue methods are inherited from Dependency Object.

3. Value Inheritance

If you specify dependency property to top element it will be inherited to all child elements until child element specifically override the property. 

Dependency property value is resolved at runtime when you call GetValue() method. 

Suggestion: If your property will commonly be the source of a databinding (e.g. providing the Text for a TextBlock), I would recommend using a standard CLR property and having the containing class implement INotifyPropertyChanged.


Wednesday, 14 August 2019

MemoryCache vs ObjectCache in .net 4.0


MemoryCache vs ObjectCache :

MemoryCache is the concrete implementation of ObjectCache.

1. ObjectCache is abstract and demonstrates how a cache should be built.
2. MemoryCache is the actual implementation of ObjectCache

Thursday, 25 July 2019

Difference between IEnumerable and IEnumerator

Difference between IEnumerable and IEnumerator

IEnumerable:

1. Make the syntax sorter.
2. IEnumerable uses IEnumerator internally
3. IEnumerable does not remember state(currently which row is currently through)

IEnumerator:

IEnumerable does remember state(currently which row is currently through)


List<int> years = new List<int>();
years.Add(2000);
years.Add(2001);
years.Add(2002);
years.Add(2003);
years.Add(2004);
years.Add(2005);

IEnumerable<int> ienum = (IEnumerable<int>)years;
ienum.GetEnumerator();//IEnumerable uses IEnumerator internally.

foreach(int i in ienum){
Console.WriteLine(i);
}


IEnumerator<int> ienumerat = year.GetEnumerator();

while(ienumerat.MoveNext()){
Console.WriteLine(ienumerat.Current.ToString());
}

https://www.youtube.com/watch?v=jd3yUjGc9M0

Monday, 15 July 2019

Masstransit .NET Messaging

Masstransit .NET Messaging

MassTransit

1. It is a message transport
2. Free, open source, lightweight message bus for creating distributed applications using the .NET framework. 

Features:

1. Developer friendly way to asynchronously connect services
2. Message-based communication is a reliable and scalable way to implement a service oriented architecture
3. Schedule a message in future delivery

Consume: Read a message from Queue
Publish: Send a message to Queue

Can use message brokers -- RabbitMQ (the Default), Azure Service Bus

https://masstransit-project.com/