Tuesday, September 19, 2017

XML CRUD SQL Bulk Operation

//NOTE: Input XML file, Resulting SQL Data Operation Insert, Modify, etc.

---------------
USE [DatabaseName]
GO
/****** Object:  StoredProcedure [DatabaseName].[recurring_account_transaction_add]  ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =====================================================================
-- Description: Bulk operation to add recurring transaction records for
-- transitioning subscribers from System1 to System2
-- =====================================================================
CREATE PROCEDURE [DatabaseName].[recurring_account_transaction_add] 
(@Rts xml)
AS
BEGIN
SET NOCOUNT ON;

-- declare table
create table #table(account_id int, merchant_category_code char(4), amount money, expiration_date datetime)

INSERT INTO #table(account_id, merchant_category_code, amount, expiration_date)
SELECT rt.value('@account_id','int') account_id 
,rt.value('@merchant_category_code','char(4)') merchant_category_code
,rt.value('@amount','money') amount
,rt.value('@expiration_date','datetime') expiration_date
FROM @Rts.nodes('/rtList/rt') p(rt)

-- insert new recurring transaction records
insert into DatabaseName.recurring_account_transaction(account_id, merchant_category_code, amount, expiration_date) 
select account_id, merchant_category_code, amount, expiration_date from #table

drop table #table

END

-------------------------
USE [DatabaseName]
GO
/****** Object:  StoredProcedure [DatabaseName].[account_health_plan_sync_modify] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- ====================================================
-- Description: Bulk operation to add/update/delete subscribers health 
-- plan information from 3 systems 
-- ====================================================
CREATE procedure [DatabaseName].[account_health_plan_sync_modify]
(@Hps xml,
@EmployerID int)
AS
BEGIN
set nocount on;

create table #table(employer_id int, account_id int, member_id int, insurance_plan_name varchar(50), system2_plan_name varchar(50), vendor_plan_name varchar(50), [type] char(3), vendor_id int)

insert into #table(employer_id, account_id, member_id, insurance_plan_name, system2_plan_name, vendor_plan_name, [type], vendor_id)
select p.hp.value('@employer_id','int') employer_id 
,p.hp.value('@account_id','int') account_id
,p.hp.value('@member_id','int') member_id
,p.hp.value('@insurance_plan_name','varchar(50)') insurance_plan_name
,p.hp.value('@system2_plan_name','varchar(50)') system2_plan_name
,p.hp.value('@vendor_plan_name','varchar(50)') vendor_plan_name
,p.hp.value('@type','char(3)') [type]
,p.hp.value('@vendor_id','int') vendor_id
from @hps.nodes('hpList/hp') p(hp)

merge DatabaseName.account_health_plan_sync as s
using #table as t
on (s.employer_id = t.employer_id
and s.member_id = t.member_id
and s.vendor_id = t.vendor_id
and s.[type] = t.[type])
when not matched by source and s.employer_id = @EmployerID then
delete
when 
matched and (s.insurance_plan_name<>t.insurance_plan_name or s.system2_plan_name<>t.system2_plan_name or s.vendor_plan_name<>t.vendor_plan_name)
then update set s.insurance_plan_name=t.insurance_plan_name, s.system2_plan_name=t.system2_plan_name, s.vendor_plan_name=t.vendor_plan_name, modify_date=getdate()
when
not matched then
insert (employer_id, account_id, member_id, insurance_plan_name, system2_plan_name, vendor_plan_name, [type], vendor_id) 
values (t.employer_id, t.account_id, t.member_id, t.insurance_plan_name, t.system2_plan_name, t.vendor_plan_name, t.[type], t.vendor_id );

END

----------------------------------------------
AccountHealthPlanSynchronizeList

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System2.Common;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace System1
{
  public class AccountHealthPlanSynchronizeList : BusinessListBase<AccountHealthPlanSynchronizeList, AccountHealthPlanSynchronizeObject>
  {
    #region constructors

    public AccountHealthPlanSynchronizeList()
      : base(DatabaseType.System1)
    {
    }

    #endregion

    #region xml

    public void SaveWithXml(int employerId)
    {
      XElement hpList = new XElement("hpList",
                                      from h in this
                                      select new XElement("hp",
                                            new XAttribute("employer_id", h.EmployerId),
                                            new XAttribute("account_id", h.AccountId),
                                            new XAttribute("member_id", h.MemberId),
                                            new XAttribute("System1_plan_name", h.System1PlanName),
                                            new XAttribute("System2_plan_name", h.System2PlanName),
                                            new XAttribute("vendor_plan_name", h.VendorPlanName),
                                            new XAttribute("type", h.Type),
                                            new XAttribute("vendor_id", h.VendorId)
                                       ));

      using (SqlConnection cn = new SqlConnection(Context.ConnectionString))
      {
        cn.OpenWithContext();
        using (SqlCommand cmd = cn.CreateCommand())
        {
          cmd.CommandType = System.Data.CommandType.StoredProcedure;
          cmd.CommandTimeout = System2.Common.Database.CommandTimeout();
          cmd.CommandText = "DatabaseName.account_health_plan_sync_modify";
          cmd.Parameters.Add("@Hps", System.Data.SqlDbType.Xml);
          cmd.Parameters["@Hps"].Value = hpList.ToString();
          cmd.Parameters.AddWithValue("@EmployerId", employerId);
          cmd.ExecuteNonQuery();
        }
      }
    }

    #endregion
  }
}





Website Default Redirect for testing, in combination with locally mapped host file. (Windows)

----------------
Web.config

<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="false" strict="false" explicit="true" />
        <pages />
<authentication mode="Windows"/>
        <customErrors mode="off" defaultRedirect="default.asp" />  /** OR default.aspx
   </system.web>
</configuration>

----------------
Default.aspx

<SCRIPT Runat="Server">
Sub Page_Load
If HttpContext.Current.Request.Url.Port = 80 Then
Response.Write("Requested Url was http://" & HttpContext.Current.Request.Url.Host & HttpContext.Current.Request.ApplicationPath)
Response.Write("<br />")
Else
Response.Write("Requested Url was http://" & HttpContext.Current.Request.Url.Host & ":" & HttpContext.Current.Request.Url.Port & HttpContext.Current.Request.ApplicationPath)
Response.Write("<br />")
End If
Response.Write("home site currently under construction. Destination virtual directories home(s) are not set correctly.<br />")
Response.Write("<a href='http://www.my-new-website.net/staging-site/default.aspx' >see forced path- http://www.my-new-website.net</a><br />")
End Sub
</SCRIPT>
<html>
<body>

</body>
</html>


---------------
Default.asp

<%EnableSessionState=False

host = Request.ServerVariables("HTTP_HOST")

if host = "virtualDirectoryTest.com" or host = "www.virtualDirectoryTest.com" then
response.redirect("http://www.my-new-website.net/staging-site/index.aspx")

elseif host = "host.com" or host = "www.host.com" then
response.redirect("http://www.my-old-website.net/staging-site/index.aspx")

else
response.redirect("http://www.my-old-website.net/error.htm")

end if
%>

ASPX - ZipCountyLookup.aspx 

//NOTE: This sample is great for an ASP/ASPX website page, where the code pages (and session) were combined during a 3 year upgrade of 3000 ASP pages... which explains some of the "loosely coupled ends" demonstrated below... The result of this code page essentially builds a dynamic list of counties, to be placed into another web control...

**** ZipCountyLookup.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class ZipCountyLookup_ZipCountyLookup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
try
{
string zipCode = Request["ZipCode"];
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbDatabaseConnection"].ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand("select szCounty from dbDatabaseName..tblZipcodes     where szZip_Code = @szZip_Code", cn);
cmd.Parameters.Add(new SqlParameter("szZip_Code", zipCode));
SqlDataReader dr = cmd.ExecuteReader();

Response.Write("<counties>");
int i = 0;
while (dr.Read())
{
Response.Write("<county cid=\"" + i + "\">" + dr["szCounty"] + "</county>");
i++;
}
Response.Write("</counties>");
dr.Close();
Response.End();
}
}
catch (Exception)
{
Response.End();
}
    }

}

----------------------------------------------------------------------------------------------------------
**** ZipCountyLookup.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ZipCountyLookup.aspx.cs" Inherits="ZipCountyLookup_ZipCountyLookup" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ZipcodeLookups</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         {intentionally blank...}
    </div>
    </form>
</body>
</html>