Tuesday, 7 May 2019

JSON with SQL Server

JSON with SQL Server


1. Select from Json Data Object

--Select from Json String--
DECLARE @jsonEmp varchar(max) 
set @jsonEmp = '[
 { "id" : 1,"EmpName": "DK", "SurName": "Shaw", "DeptID": 25, "DOBirth": "2007-03-25T12:00:00", "Active": true },
 { "id" : 4,"EmpName": "Mick", "SurName": "smith", "DeptID": 35, "DOBirth": "2005-11-04T12:00:00", "Active": true },
 { "id" : 5,"EmpName": "Paul", "SurName": "Dang", "DeptID": 15, "DOBirth": "1983-10-28T12:00:00", "Active": false },
 { "id" : 7,"EmpName": "Mohan", "SurName": "Kumar", "DeptID": 12, "DOBirth": "1995-07-05T12:00:00", "Active": true },
 { "id" : 9,"EmpName": "Bhushan", "SurName": "Kal", "DeptID": 37, "DOBirth": "2015-03-25T12:00:00", "Active": true }]'
 
    SELECT * FROM OPENJSON(@jsonEmp)
    WITH (id int, EmpName nvarchar(50), SurName nvarchar(50),
 
                 DeptID int, DOBirth datetime2, Active bit) AS TEmployee

2. Select Database Table as Json Data output
 --Create Employees Table --
CREATE TABLE [dbo].[TEmployees](
 [EMPID] [int] IDENTITY(1,1) NOT NULL,
 [Name] [nchar](50) NOT NULL,
 [SurName] [nchar](50) NULL,
 [DataOfBirth] [date] NOT NULL,
 [Nationality] [nchar](3) NULL,
 [Salary] [float] NULL,
 [DEPTID] [int] NULL,
 [ActiveEmp] [bit] NULL,
 [InDate] [datetime] NULL,
 CONSTRAINT [PK_TEmployees] PRIMARY KEY CLUSTERED 
(
 [EMPID] ASC
)WITH (
PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
 
ALTER TABLE [dbo].[TEmployees] ADD  CONSTRAINT [DF_TEmployees_ActiveEmp]  
DEFAULT ((0)) FOR [ActiveEmp]
GO
 
ALTER TABLE [dbo].[TEmployees] ADD  CONSTRAINT [DF_TEmployees_InDate]  
DEFAULT (getdate()) FOR [InDate]
GO
 
--INSERT sample data: Employee-- 
INSERT INTO [dbo].[TEmployees] ([Name],[SurName],[DataOfBirth],[Nationality],
[Salary],[DEPTID],[ActiveEmp])
VALUES ('JAG','KIM','2001-01-10','RU',1000.50,10,0)
 
--Select Data: Employee as Json array--
SELECT [name], [SurName] as b FROM [dbo].[TEmployees] FOR JSON AUTO;
SELECT [name], [SurName] as b FROM [dbo].[TEmployees] FOR JSON  PATH, ROOT('Employees');
SELECT [name], [SurName] as b FROM [dbo].[TEmployees] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;

3. Insert Json Object to Database Table
 /**Topic3: Insert Json array to SQL Employees Table**/
DECLARE @EmpJson varchar(max) 
set @EmpJson = '[
 { "theName": "Sam", "SurName": "Joshi","DateOfBirth": "1980-03-25",
 "Nationality": "IND", "Salary":1001.11, "DEPTID":10, "ActiveEmp":1},
 { "theName": "Kin", "SurName": "Tej","DateOfBirth": "1971-01-31",
 "Nationality": "USA", "Salary":2501.11, "DEPTID":2, "ActiveEmp":1}
]'
 
--Select @EmpJson
INSERT INTO [TEmployees] ([Name],[SurName],[DataOfBirth],[Nationality],[Salary],[DEPTID],[ActiveEmp]) 
 SELECT theName, SurName, DateOfBirth, Nationality, Salary, DEPTID, ActiveEmp 
 FROM OPENJSON(@EmpJson)
 WITH (theName nchar(50), SurName nchar(50), DateOfBirth date, Nationality nchar(3), Salary float, DEPTID int, ActiveEmp bit)
 
--SELECT TOP (1000) *   FROM [dbo].[TEmployees]
--delete from [TEmployees]
4. Update Json Object to Database Table
/**Topic4: Update SQL Employees Table using 
Json array data object 
 
**/

DECLARE @EmpJson varchar(max) 
set @EmpJson = '[
 {"EID":2, "theName": "Sam", "SurName": "Joshi","DateOfBirth": "1980-03-25",
 "Nationality": "IND", "Salary":1001.11, "DEPTID":10, "ActiveEmp":1},
 { "EID":17,"theName": "Keli", "SurName": "Tej","DateOfBirth": "1971-01-31",
 "Nationality": "USA", "Salary":2501.11, "DEPTID":2, "ActiveEmp":1}
]'
UPDATE [TEmployees]
 SET [Name] = json.theName,
 [SurName] = json.SurName,
 [DataOfBirth] = json.dateOfBirth,
 [Nationality] = json.Nationality,
 [Salary] = json.salary,
 [DEPTID] = json.deptid,
 [ActiveEmp] = json.ActiveEmp
 FROM OPENJSON(@EmpJson)
 WITH (EID int, theName nchar(50), SurName nchar(50), DateOfBirth date, 
 Nationality nchar(3), Salary float, DEPTID int, ActiveEmp bit) AS json
  WHERE [TEmployees].EMPID = json.eid
4. Conditional UPDATE or INSERT to sql Table Using Json DATA Object
 
/**Topic5: Inser or Update SQL Employees Table using 
Json array data object 
  
**/
 
 
 ---MERGE statement that will insert row if it does not exist in the TEmployees table,
 -- and update it if there is a match
 DECLARE @EmpJson varchar(max) 
set @EmpJson = '[
 {"EID":1, "theName": "Kali", "SurName": "Sala","DateOfBirth": "1980-03-25",
 "Nationality": "IND", "Salary":1001.11, "DEPTID":10, "ActiveEmp":1},
 { "EID":17,"theName": "Jem", "SurName": "Farrero","DateOfBirth": "1971-01-31",
 "Nationality": "USA", "Salary":2501.11, "DEPTID":2, "ActiveEmp":1}
]'
MERGE TEmployees AS P
USING (
    SELECT *
FROM OPENJSON(@EmpJson)
WITH (EID int, theName nchar(50), SurName nchar(50), DateOfBirth date, 
Nationality nchar(3), Salary float, DEPTID int, ActiveEmp bit)) AS json
   ON P.EMPID = json.EID
 
WHEN MATCHED THEN
    UPDATE SET
 P.[Name] = json.theName,
 P.[SurName] = json.SurName,
 P.[DataOfBirth] = json.dateOfBirth,
 P.[Nationality] = json.Nationality,
 P.[Salary] = json.salary,
 P.[DEPTID] = json.deptid,
 P.[ActiveEmp] = json.ActiveEmp
 
WHEN NOT MATCHED THEN
    INSERT ([Name],[SurName],[DataOfBirth],[Nationality],[Salary],[DEPTID],[ActiveEmp]) 
    VALUES (json.theName, json.SurName, json.dateOfBirth, json.Nationality, 
 json.salary,json.deptid,json.ActiveEmp);

Sunday, 16 December 2018

Upload Multiple Projects to GitHub Repository

Open Command Prompt and go to the root folder where your Projects Files/Folders are located
Clean 1st GitHub local folder (in case it was configured earlier)
> rd .git /S/Q

Initialize GitHub local folder
>git init

Add files/folders to GitHub local (Note: space between add and dot)
>git add .

commit file/folder to git local repository
git commit -m "BizTalk Projects commit"

Push to file/folders to GitHub cloud repository
>git remote add origin https://github.com/DeepakkSHAW/Dummy.git

Finally need to push (Note: you may need to provide git credentials, and wait for the upload to complete)
>git push -u origin master


Go to online and GitHub web portal, hopefully, it’s all done.

Monday, 14 May 2018

Visio stencils collection for BizTalk, Azure, Infra and more..

Visio stencils collection
Downloaded Visio stencils from various sites from the net, Related to Microsoft Integration BizTalk, Azure, Infra and many more Stencils
Hoping this will be helpful & useful.
Enjoy!




Monday, 7 May 2018

BizTalk BTDF deployment on top of exiting BizTalk Application

This deployment method will only add BizTalk resources to the existing application without underpaying it or throwing an error during fresh deployment.

Step1:
    <!--Add the line in your BTDF Project in Node: Project >> PropertyGroup -->
    <SkipRemoveApp>True</SkipRemoveApp>   

Step2:
  <!--Add below lines in your Deployment.btdfproj file Assuming you have BizTalkAppName defined in a veriable -->
  <Target Name="DeployAppDefinition" Condition="'$( SkipRemoveApp)' == 'False'">
    <Exec Command="BTSTask.exe AddApp -ApplicationName:&quot;$(BizTalkAppName)&quot; -Description:&quot;$(ProjectName)&quot;" />
    <AddAppReference ApplicationName="$(BizTalkAppName)" AppsToReference="@(AppsToReference)" Condition="%(Identity) == %(Identity) and '@(AppsToReference)' !=''"/> 
  </Target>

Happy coding..

Sunday, 26 March 2017

Schema referenced by Map has been deleted - unable to open BizTalk Admin Console >> Work around

Error: Schema referenced by Map has been deleted. The local, cached version of the BizTalk Server group configuration is out of date.


This issue will not let you open BizTalk Admin Console

The Work around is Just like:
Create a new application to BizTalk group and surprisingly it opens up Application tree.


(If you just want to open admin console>> BT Group>>Applications, create a new application (a test application), surprisingly it open the BT Gr Application tree..)


Thursday, 16 June 2016

Adding Icon to BizTalk Custom Pipeline Components

Adding Icon to BizTalk Custom Pipeline Components

In BizTalk customization of Receive or Send Pipeline is very popular; However BizTalk developer ignores putting any Icon to their pipeline components. Giving pictorial notification/annotation adds value and in long run it really pays back. Moreover adding icon to your pipeline components gives professional touch to your component and showcases your sophisticated skills.
Add Icon to your Receive or Send Pipeline in not so convoluted..
Using Resource file technique it make rather simpler, follow the blow steps in your exiting custom pipeline component project and see the changes..
I assume your custom pipeline component project has name like DK.POC.BT.PipelineComponents.
Project structure some like below image:

Figure 1

Step 1:
Right Click on Pipeline component project (e.g. DK.POC.BT.PipelineComponents) and new items, search for resource item in add New Item window.
Figure 2

Add the resource as Resource.resx.
Step 2:
Double Click on newly added Resource.resx file and add Description, Name and Version as String
Figure 3
Step 3:
Select Images Menu (Ctrl+2) from left most Strings Menu
Figure 4

Add few images which could be Iconic representation of your custom pipeline (I have added 3) by selecting Menu itmes Add Resource >> Add Existing File.. ( you may convert your icon to create some images online https://iconverticons.com/online/)
Select each image from the resource and change its property from Linked at compile time to Linked at compile time (this is very critical to set). Now your project explore supposed to look like figure 5.
Figure 5


And just Delete the newly added in your project folder Resources.
Step 4:
Open your component class file, in my case the name is DKMessageArchiver.cs. (also you may close Resource.resx window)
Go to your Class Variable declaration and add new Private object of type ResourceManager (you can find this type in namespace System.Resources.ResourceManager) .
Your Object declaration will be similar to below line
private System.Resources.ResourceManager rsManager = new System.Resources.ResourceManager("DK.POC.BT.PipelineComponents.Resource", Assembly.GetExecutingAssembly());

Make sure the base name DK.POC.BT.PipelineComponents.Resource matches with project namespace and Resource file name.
DK.POC.BT.PipelineComponents => project namespace
Resource => and Resource file name
Step 5:
Implement and new method using IComponentUI interface. (Just write click on IComponentUI and select “Implement Interface Explicitly” (as show in figure 6).
Figure 6

I will create 2 new methods.
        IntPtr IComponentUI.Icon
        {
            get { throw new NotImplementedException(); }
        }

        IEnumerator IComponentUI.Validate(object projectSystem)
        {
            throw new NotImplementedException();
        }
Change the methods as shown below:
        IntPtr IComponentUI.Icon
        {
            get { return ((System.Drawing.Bitmap)(this.rsManager.GetObject("Backup_Archive16", System.Globalization.CultureInfo.InvariantCulture))).GetHicon(); }
        }

        IEnumerator IComponentUI.Validate(object projectSystem)
        {
            return null;
        }
Note:
String Name parameters should match exactly the you have given to your images during uploading to resource file. Here the name is "Backup_Archive16" same name matching with 2nd picture in figure 5.
Step 6:
Additional steps to read Name, version and description from Resource file for your pipeline component.
Same as previous steps generate 3 methods from IBaseComponent , something like below months.
        string IBaseComponent.Description
        {
            get { throw new NotImplementedException(); }
        }

        string IBaseComponent.Name
        {
            get { throw new NotImplementedException(); }
        }

        string IBaseComponent.Version
        {
            get { throw new NotImplementedException(); }
        }
 Change the methods such Name, version and populates from Resource file:
        string IBaseComponent.Description
        {
               get{ return rsManager.GetString("Name", System.Globalization.CultureInfo.InvariantCulture);}
        }

        string IBaseComponent.Name
        {
               get{ return rsManager.GetString("Description", System.Globalization.CultureInfo.InvariantCulture);}
        }

        string IBaseComponent.Version
        {
            get { return rsManager.GetString("Version", System.Globalization.CultureInfo.InvariantCulture); }
        }
Note: read Name, Version and Description are declared in Resource file as String Resources.
Step 7:
You pipeline component is not ready with ICON, just one more step below building it..
Go to project Property >> Build Events and in Post-build event command line add below script (it put your assembly in GAC after build, not extra effort required to GAC your assembly)
For Visual Studio 2013:
CALL "%VS120COMNTOOLS%vsvars32.bat"
gacutil.exe /i "$(TargetPath)"
For Visual Studio 2010:
CALL "%VS100COMNTOOLS%vsvars32.bat"
gacutil.exe /i "$(TargetPath)"

Figure 7

Finally build your pipeline component. After successful build you can see your pipeline component in GAC.
Run >> %windir%\Microsoft.NET\assembly >> GAC_MSIL
Figure 8

Step 8:
Open your BizTalk Pipeline Project add a new Pipeline (e.g. RcvArchivalPipeline.btp), double click on btp file and right click on Toolbox and select “Choose Items..”
Figure 9

Go to BizTalk Pipeline Components TAB and select your pipeline component dll file from GAC (e.g. C:\Windows\Microsoft.NET\assembly\GAC_MSIL\DK.POC.BT.PipelineComponents).
Figure 10

After opening the dll you need to check the checkbox against the Pipeline component Name.
Figure 11

Once your select  and press ok from the dialog box your pipeline component will appeared in Toolbox panel, with the same Icon you have assigned. As shown in figure 12.

Figure 12

Step 9:
Drag and drop the pipeline component to your pipeline on to a desire stage and it will come with proper icon you have assigned. Also see in property window all assigned property has been populated like Name, Description and Version.  
Figure 13

Scenario:
Icon you have assigned is not suitable and you want to change this to a more meaningful icon or which suits to your test.
If you are unhappy with your Pipeline component icon you can changes this very easy..
Add a new Images as explained in step 3.
Change the code with new image name.
IntPtr IComponentUI.Icon
        {
            get { return ((System.Drawing.Bitmap)(this.rsManager.GetObject("NewImageName", System.Globalization.CultureInfo.InvariantCulture))).GetHicon(); }
        }
Before Rebuilding you code
-          Delete pipeline component from pipeline stage.
-          Remove reference of pipeline component from pipeline project.
-          Right Click and delete pipeline component from ToolBox.
Rebuild you project, make sure in GAC you have new date time for Pipeline component.
If this pipeline component already used by BizTalk restart related Host Instances.
Restart your Visual Studio IDE. Then add the Pipeline component from GAC as explained in step 8.

Errors.
Most commonly you will see Error “you have selected an invalid pipeline component assembly. please check security settings for the assembly if you are loading it from an UNC path” when working with Pipeline components Interfaces like IBaseComponent or IComponentUI.
Figure 14

This happened basically because your code don’t find the required resources from your *.resx file.
You need to cross check each item which has a reference to your resources file.
In my case Resouce file name is declared in code DKResource where as physical file name only Resource. Which cause the issue. Or if I change the name space of the project.
private System.Resources.ResourceManager rsManager = new System.Resources.ResourceManager("DK.POC.BT.PipelineComponents.DKResource", Assembly.GetExecutingAssembly());
I hope it’s clear and not complex to implement. Let me know your Questions/Feedbacks..

Enjoy professional coding.