Pages

Monday, October 17, 2016

.Net CF 3.5: Unable to read project file, Microsoft.CompactFramework.CSharp.targets was not found

Below is the screenshot of the error message shown in Visual Studio:
error
To get rid of this error you must install the .Net Compact Framework PowerToys into your Windows 10 OS!!

Thursday, July 7, 2016

Crystal Reports shows blank page

Copy the folders under "\inetpub\wwwroot\aspnet_client\" and paste them under the  root of the custom web site

 Add the following to the application web.config file:

<configSections>

    <sectionGroup name="businessObjects">
      <sectionGroup name="crystalReports">
        <section name="crystalReportViewer" type="System.Configuration.NameValueSectionHandler"/>
      </sectionGroup>
    </sectionGroup>
  </configSections>

  <businessObjects>
    <crystalReports>
      <crystalReportViewer>
        <add key="UseBrowserLocale" value="true"/>
        <add key="resourceURI" value="~/aspnet_client/system_web/4_0_30319/crystalreportviewers13" />
      </crystalReportViewer>
    </crystalReports>
  </businessObjects>

Monday, June 6, 2016

Traditonal Yoga - Breath Meditation



Lord Buddha also says that “he knows, ‘I am breathing….’” “Knows” means that it is a matter of conscious experience, of intentional awareness of the breath. But perhaps even more important is the Buddha’s assertion that the practicer will know “I am breathing.” This has more than one significant truth for us.

The first one is supremely practical: Breathing is not utterly automatic, nor is it a purely physical function. A friend told me that in his first conversation with a great yogi, the yogi asked him: “How do the lungs breathe, the heart beat, and the cells divide?” When he replied that they were activities of the involuntary nervous system, the yogi told him: “Then get busy and know that which is behind the involuntary nervous system, for that is the root of life. That is what you really are–not the shallow phantom of your conscious mind.” Buddha’s declaration assures us that through anapanasati the subconscious becomes conscious, that we become aware of The Breather.

Secondly, the Buddha’s statement that we will know: “I am breathing” informs us that although we are watching the breath and letting it be spontaneous, at the same time we are engaging in a subtle act of will (or: feeling, imagining, intending, sensing or thinking) for the breath to move at/in the nosetip during our inhalations and exhalations. It is not a matter of forcing or of intense will, but it is a subtle “setting of the sails” to ensure that the breath and awareness of the breath will continually be centered in the tip of the nose. It is something that we are doing, though in the subtlest possible way.

Thirdly, Buddha is saying that by means of Breath Meditation we shall come to know the true nature of our “I;” that by observing the breath we come to be aware of the observer, the “who” of us that is separate from and untouched by the duality that is embodied in the breath process, that full awareness of the dual breath leads us to the non-dual consciousness which both produces and perceives the breath. We breathe, and we know we breathe, and we come to know who we are. This is the purpose of Breath Meditation. - See more at: http://breathmeditation.org/the-buddhist-tradition-of-breath-meditation#sthash.vGnI2roP.dpuf

http://www.daviddarling.info/encyclopedia/B/Big_Bang.html
Universe - Big Bang theory

http://www.crystalinks.com/multiverse.html
Multi Universe

https://www.youtube.com/watch?v=qyPWvg9dxD4
Sceience vs Patanjali yoga (check from 14 mints after)

https://www.youtube.com/watch?v=DfPeprQ7oGc
Double Slit Experiment

https://www.youtube.com/watch?v=DsxA7OU7fR0
Explaination of double slit experiment



Thursday, June 2, 2016

Crystal Report Viewer bobj is undefined

Web.config.

<configSections>
    <sectionGroup name="businessObjects">
      <sectionGroup name="crystalReports">
        <section name="crystalReportViewer" type="System.Configuration.NameValueSectionHandler" />
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <businessObjects>
    <crystalReports>
      <crystalReportViewer>
        <add key="resourceURI" value="~/crystalreportviewers13" />
      </crystalReportViewer>
    </crystalReports>
  </businessObjects>

Following are the solutions :
  1. Copy the folder "crystalreportviewers12" from “C:Inetpubwwwrootsystem_web2_0_50727" under “Default Website” to the “Custom Website” directory in IIS. Or, create a virtual directory pointing ‘aspnet_client’ folder in the custom web site directory.
  2. In the IIS Manger, select the Application Pool and Basic Settings. Under Managed Pipeline Mode, change Integrated Mode to Classic Mode.
  3. The value of resoureURI should be "~/crystalreportviewers12" not "/crystalreportviewers12".
  4. Copy the CrystalReportViewers12 folder from
    "C:Program FilesBusiness ObjectsCommon4.0" and paste it to "C:WindowsMicrosoft.NETFrameworkv3.5ASP.NETClientFiles".
          Note: Framework may vary as per the Visual Studio version used.

Thursday, May 26, 2016

DataGrid extensions for the Compact Framework

DataGrid extensions for the Compact Framework

InfoDabble > Tech Notes > DataGrid extensions for the Compact Framework
By Eric Hartwell -- February 25, 2008
Customized DataGrid control sample showing the ComboBox column in action.
Customized DataGrid control sample showing the ComboBox column in action.
Microsoft says, "The DataGrid class in the .NET Compact Framework provides the core functionality of the Windows Forms DataGrid class in the full .NET Framework." That's a bit like saying a rock provides the core functionality of a nuclear submarine.
The Compact Framework provides a subset of the functionality of the full .NET Framework. That's what makes it compact. Ok, but ...
<rant>did it never occur to anyone at Microsoft that the user interface is even more important in mobile applications than in Windows or web applications?</rant>
To be honest, it's not as bad as it looks. Way back in April, 2006, the Microsoft .NET Compact Framework Team published atech note with samples showing how to customize the DataGrid control, adding such field types as editable, formatted text, checkbox, pulldown lists, a date picker, and an up/down control. Unfortunately there's very little documentation with the sample.
 I've added a C# version of the sample application, updated to target Windows Mobile 5.0. Download it here.

C# code

The SetupTableStyles function must be called in the form's Load event handler rather than the constructor since the data and screen need to be initialized before it will work.
It would be nice to add designer support so the custom grid can be initialized directly from the screen builder. As always, adding designer support to compact framework controls is needlessly painful, but I'll try ...
private void SetupTableStyles()
{
   Color alternatingColor = SystemColors.ControlDark;
   DataTable vehicle = dataSource.Tables[1];
 
   // ID Column 
   DataGridCustomTextBoxColumn dataGridCustomColumn0 = new DataGridCustomTextBoxColumn();
   dataGridCustomColumn0.Owner = this.dataGrid1;
   dataGridCustomColumn0.Format = "0##";
   dataGridCustomColumn0.FormatInfo = null;
   dataGridCustomColumn0.HeaderText = vehicle.Columns[0].ColumnName;
   dataGridCustomColumn0.MappingName = vehicle.Columns[0].ColumnName;
   dataGridCustomColumn0.Width = dataGrid1.Width * 10 / 100;    // 10% of grid size
   dataGridCustomColumn0.AlternatingBackColor = alternatingColor;
   dataGridCustomColumn0.ReadOnly = true;
   dataGridTableStyle1.GridColumnStyles.Add(dataGridCustomColumn0);
 
   // Make column
   DataGridCustomTextBoxColumn dataGridCustomColumn1 = new DataGridCustomTextBoxColumn();
   dataGridCustomColumn1.Owner = this.dataGrid1;
   dataGridCustomColumn1.HeaderText = vehicle.Columns[1].ColumnName;
   dataGridCustomColumn1.MappingName = vehicle.Columns[1].ColumnName;
   dataGridCustomColumn1.NullText = "-Probably Ford-";
   dataGridCustomColumn1.Width = dataGrid1.Width * 40 / 100;     // 40% of grid size
   dataGridCustomColumn1.Alignment = HorizontalAlignment.Right;
   dataGridCustomColumn1.AlternatingBackColor = alternatingColor;
   dataGridTableStyle1.GridColumnStyles.Add(dataGridCustomColumn1);
 
   // Mileage column
   DataGridCustomUpDownColumn dataGridCustomColumn2 = new DataGridCustomUpDownColumn();
   dataGridCustomColumn2.Owner = this.dataGrid1;
   dataGridCustomColumn2.HeaderText = vehicle.Columns[2].ColumnName;
   dataGridCustomColumn2.MappingName = vehicle.Columns[2].ColumnName;
   dataGridCustomColumn2.NullText = "-Unknown-";
   dataGridCustomColumn2.Width = dataGrid1.Width * 20 / 100;     // 20% of grid size
   dataGridCustomColumn2.Alignment = HorizontalAlignment.Left;
   dataGridCustomColumn2.AlternatingBackColor = alternatingColor;
   dataGridTableStyle1.GridColumnStyles.Add(dataGridCustomColumn2);
 
   // Availability column 
   DataGridCustomCheckBoxColumn dataGridCustomColumn3 = new DataGridCustomCheckBoxColumn();
   dataGridCustomColumn3.Owner = this.dataGrid1;
   dataGridCustomColumn3.HeaderText = vehicle.Columns[3].ColumnName;
   dataGridCustomColumn3.MappingName = vehicle.Columns[3].ColumnName;
   dataGridCustomColumn3.NullText = "-Unknown-";
   dataGridCustomColumn3.Width = dataGrid1.Width * 10 / 100;     // 10% of grid size
   dataGridCustomColumn3.Alignment = HorizontalAlignment.Left;
   dataGridCustomColumn3.AlternatingBackColor = alternatingColor;
   dataGridTableStyle1.GridColumnStyles.Add(dataGridCustomColumn3);
 
   // Fuel Level column
   DataGridCustomComboBoxColumn dataGridCustomColumn4 = new DataGridCustomComboBoxColumn();
   dataGridCustomColumn4.Owner = this.dataGrid1;
   dataGridCustomColumn4.HeaderText = vehicle.Columns[4].ColumnName;
   dataGridCustomColumn4.MappingName = vehicle.Columns[4].ColumnName;
   dataGridCustomColumn4.NullText = "-Unknown-";
   dataGridCustomColumn4.Width = dataGrid1.Width * 30 / 100;     // 30% of grid size
   dataGridCustomColumn4.Alignment = HorizontalAlignment.Left;
   dataGridCustomColumn4.AlternatingBackColor = alternatingColor;
   dataGridTableStyle1.GridColumnStyles.Add(dataGridCustomColumn4);
 
   // Last Used column
   DataGridCustomDateTimePickerColumn dataGridCustomColumn5 = new DataGridCustomDateTimePickerColumn();
   dataGridCustomColumn5.Owner = this.dataGrid1;
   dataGridCustomColumn5.HeaderText = vehicle.Columns[5].ColumnName;
   dataGridCustomColumn5.MappingName = vehicle.Columns[5].ColumnName;
   dataGridCustomColumn5.NullText = "-Unknown-";
   dataGridCustomColumn5.Width = dataGrid1.Width * 30 / 100;     // 30% of grid size
   dataGridCustomColumn5.Alignment = HorizontalAlignment.Left;
   dataGridCustomColumn5.AlternatingBackColor = alternatingColor;
   dataGridTableStyle1.GridColumnStyles.Add(dataGridCustomColumn5);
 
   // Grid, mapping
   dataGridTableStyle1.MappingName = vehicle.TableName;                       // Setup table mapping name
   dataGrid1.DataSource = vehicle;         
 
   // Setup grid's data source
   ComboBox cb = (ComboBox)dataGridCustomColumn4.HostedControl;
   DataTable fuel = dataSource.Tables[0];                                                    // Set up data source
   cb.DataSource = fuel;           
 
   // For combo box column
   cb.DisplayMember = fuel.Columns[0].ColumnName;
   cb.ValueMember = fuel.Columns[0].ColumnName;
 
   dataGrid1.CurrentRowIndex = 50;                                                            // Move to the middle of the table
}

Code notes

Note the funky cast when setting up the combo box's data source. This is because the HostedControl is exposed as the base Control class.
ComboBox cb = (ComboBox)dataGridCustomColumn4.HostedControl;

How did they do that?

The Compact Framework 2.0 Service Pack 1 introduced the following extensions to provide better data formatting and custom cell drawing:
  • DataGridColumnStyle
    • PropertyDescriptor descriptor allows access to this column data in the data source so it could be processed as needed.
    • Paint() method is called as cell is drawn. Overriding it allows representing data from data source in any way imaginable. Colors, fonts, formatting, alignment, pictures and more - anything is possible as long as it can be painted. CurrencyManager and row number along with PropertyDescriptor allows fetching data from data source to convert and format the way you want.
  • DataGridTextBoxColumn
    • Format string to be used to format data in the column. To be used the same way as on desktop or in simple data binding.
    • IFormatProvider FormatInfo Format provider to be used to format data in the column. To be used the same way as on desktop or in simple data binding.

Links

Friday, May 20, 2016

Android Phone Screen on PC debug

It's likely that the device is no longer authorized on ADB for whatever reason.
ADB path C:\Users\LoggedinUser\AppData\Local\Android\sdk\platform-tools
1. Check if authorized:
<ANDROID_SDK_HOME>\platform-tools>adb devices
List of devices attached
4df798d76f98cf6d        unauthorized
2. Revoke USB Debugging on phone
If the device is shown as unauthorized, go to the developer options on the phone and click "Revoke USB debugging authorization" (tested with JellyBean & Samsung GalaxyIII).
3. Restart ADB Server:
Then restarted adb server
adb kill-server
adb start-server
4. Reconnect the device
The device will ask if you are agree to connect the computer id. You need to confirm it.
5. Now Check the device
It is now authorized!
adb devices
<ANDROID_SDK_HOME>\platform-tools>adb devices
List of devices attached
4df798d76f98cf6d        device

Wednesday, January 28, 2015

ITextSharp PDF editing

In any case, you need a font that knows how to display Arabic glyphs:
BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
For Adding text
  Dim oldFile As String = "D:\PdfGenerator_VB\nf.pdf"
        Dim newFile As String = "D:\PdfGenerator_VB\newnf.pdf"

        ' open the reader
        Dim reader As New PdfReader(oldFile)
        Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
        Dim document As New Document(size)

        ' open the writer
        Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
        Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
        document.Open()

        ' the pdf content
        Dim cb As PdfContentByte = writer.DirectContent

        ' select the font properties
        Dim bf As BaseFont = BaseFont.CreateFont("C:\Windows\Fonts\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
        cb.SetColorFill(BaseColor.DARK_GRAY)
        cb.SetFontAndSize(bf, 8)
      
        Dim f As New Font(bf, 8)
        Dim ct As New ColumnText(writer.DirectContent)
        ct.RunDirection = PdfWriter.RUN_DIRECTION_RTL
        ct.SetSimpleColumn(50, 50, 480, 270, 24, Element.ALIGN_RIGHT)
        Dim chunk = New Chunk("الأربعاء", f)
        ct.AddElement(chunk)
        ct.Go()


        cb.BeginText()
        text = "28"
        ' put the alignment and coordinates here
        cb.ShowTextAligned(2, text, 405, 260, 0)
        cb.EndText()

        cb.BeginText()
        text = "01"
        ' put the alignment and coordinates here
        cb.ShowTextAligned(2, text, 390, 260, 0)
        cb.EndText()

        cb.BeginText()
        text = "2015"
        ' put the alignment and coordinates here
        cb.ShowTextAligned(2, text, 370, 260, 0)
        cb.EndText()

        ' create the new page and add it to the pdf
        Dim page As PdfImportedPage = writer.GetImportedPage(reader, 1)
        cb.AddTemplate(page, 0, 0)

        ' close the streams and voilá the file should be changed :)
        document.Close()
        fs.Close()
        writer.Close()
        reader.Close()
For Fields using
  Dim pdfTemplate As String = "D:\PdfGenerator_VB\nf.pdf"

        ' title the form
        Me.Text += " - " + PdfTemplate

        ' create a new PDF reader based on the PDF template document
        Dim pdfReader As PdfReader = New PdfReader(pdfTemplate)

        ' create and populate a string builder with each of the 
        ' field names available in the subject PDF
        Dim sb As New StringBuilder()

        Dim de As New DictionaryEntry
        For Each kvp As KeyValuePair(Of String, AcroFields.Item) In pdfReader.AcroFields.Fields
            sb.Append(kvp.Key.ToString() + Environment.NewLine)
        Next

        ' Write the string builder's content to the form's textbox
        textBox1.Text = sb.ToString()
        textBox1.SelectionStart = 0
  Dim pdfTemplate As String = "D:\PdfGenerator_VB\nf.pdf"
        Dim newFile As String = "D:\PdfGenerator_VB\Final_nf.pdf"

        Dim pdfReader As New PdfReader(pdfTemplate)
        Dim pdfStamper As New PdfStamper(pdfReader, New FileStream( _
                    newFile, FileMode.Create))

        Dim pdfFormFields As AcroFields = pdfStamper.AcroFields

        ' set form pdfFormFields

        ' The first worksheet and W-4 form
        pdfFormFields.SetField("untitled1", "1")
        pdfFormFields.SetField("untitled2", "2")
        pdfFormFields.SetField("f1_03(0)", "1")
     ' report by reading values from completed PDF
        Dim sTmp As String = "W-4 Completed for " + pdfFormFields.GetField("f1_09(0)") + " " + _
        pdfFormFields.GetField("f1_10(0)")
        MessageBox.Show(sTmp, "Finished")

        ' flatten the form to remove editting options, set it to false
        ' to leave the form open to subsequent manual edits
        pdfStamper.FormFlattening = True

        ' close the pdf
        pdfStamper.Close()
http://www.dotnettips.info/Post/582/%D9%81%D8%A7%D8%B1%D8%B3%D9%89-%D9%86%D9%88%DB%8C%D8%B3%D9%89-%D9%88-itextsharp

How to Create a PDF with Editable Fields

PDFescape

http://smallbusiness.chron.com/create-pdf-editable-fields-55640.html

Sunday, December 14, 2014

HOW TO: FIX ERROR - "the 'microsoft.ace.oledb.12.0' provider is not registered on the local machine


this resolution works with:
  • 64-bit Windows 7
  • 64-bit MS Office
  • Please reply to this thread if it worked for you so i can make this a full "compatibility list"

trying to connect to an Access database in visual studio but keep getting this error?

however if, like me, that doesnt work for you, try the following method:
NOTE: this DOES work for office 2010 even though it is for 2007 office, dont ask me why it just does :)
2. in VS click add data source, follow the wizard and enjoy! :)

Monday, June 2, 2014

Oracle Linked Server in Sql Server

EXEC sp_addlinkedserver 'OraCMSRFID', 'CMSRFID', 'MSDAORA', 'CMSRFID'
                                           name                   service name                        servicename

EXEC sp_addlinkedsrvlogin 'OraCMSRFID', false, 'sa', 'oraUID', 'OraPwd'

select * from openquery(OraCMSRFID, 'select * from tabemp')

If variable is blank then no where clause

use OR:
select * from yourTable
where @test = '' OR Agent = @test
if @test coming with null value (instead of ''), you must use:
select * from yourTable
where @test is null OR Agent = @test
And
case when @Status = 1 then tbl1.Status end != 'Done' Or
case when @Status = 2 then tbl1.Status end = 'Done' 

TSQL dummy where clause

This is common when a query is being built programatically, so for every condition you will add:
 AND (SOMECONDITION)
so the 1=1 starts the WHERE section, it is always true, and it doesn't hurt the performance.

1=1 is usually used at the top of the where clause for formatting reasons and for ease of debugging. It is correct syntax and has no bearing on the output of the actual query.

Wednesday, May 21, 2014

Faulting module path: KERNELBASE.dll


It is a CLR exception, you cannot use DependencyWalker to analyze .NET dependencies. Use fuslogvw.exe instead.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
Add:
DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
String LogPath set value to folder for logs (e.g. C:\FusionLog\)
Make sure you include the backslash after the folder name and that the Folder exists.
You need to restart the program that you're running to force it to read those registry settings.

Saturday, May 17, 2014

Proverb


SQL Server 2008 Script all objects in a Schema

DECLARE @TotalObject INT
DECLARE @ObjectCount INT
DECLARE @CurrentObjectName NVARCHAR(250)
SELECT @TotalObject = COUNT(*) from dbo.TabSchema
SET @ObjectCount = 1
WHILE (@TotalObject >= @ObjectCount)
BEGIN
SELECT @CurrentObjectName = TableName FROM dbo.TabSchema WHERE Seq = @ObjectCount
exec util_ScriptSchema 'dbo','ORG003',@CurrentObjectName
SET @ObjectCount = @ObjectCount + 1
END

--PROCEDURES
DECLARE @CurrentObjectName NVARCHAR(250)
DECLARE @MyCursor CURSOR

SET @MyCursor = CURSOR FAST_FORWARD
FOR Select ROUTINE_NAME from kegx.information_schema.routines where Left(Routine_Name, 3) NOT IN ('sp_', 'xp_', 'ms_') AND routine_type = 'PROCEDURE' and SPECIFIC_SCHEMA='dbo'

OPEN @MyCursor
FETCH NEXT FROM @MyCursor INTO @CurrentObjectName

WHILE @@FETCH_STATUS = 0
BEGIN
exec util_ScriptSchema 'dbo','ORG003',@CurrentObjectName

FETCH NEXT FROM @MyCursor INTO @CurrentObjectName
END

CLOSE @MyCursor
DEALLOCATE @MyCursor
GO


create PROCEDURE [dbo].[util_ScriptSchema]
@CopyFromSchema Varchar(50),
@CopyToSchema Varchar(200),
@ObjectName NVarchar(max)
AS
BEGIN
---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
---- SET THE PARAMENTER
---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

--SET @CopyFromSchema = 'Marketing'
--SET @CopyToSchema = 'Sales, Account, Economics, Employee, Manager'
--SET @ObjectName = 'Table_1, Table_2, Table_3, View_1, View_2, View_3, Proc_1, Proc_2, Proc_3, Func_1, Func_2, Func_3'


DECLARE @SqlString nvarchar(max) = ''
DECLARE @TotalSchema INT
DECLARE @TotalObject INT  
DECLARE @SchemaCount INT
DECLARE @ObjectCount INT
DECLARE @XML XML
DECLARE @Flag INT
DECLARE @SchemaName Varchar(100)
DECLARE @CurrentObjectName NVarchar(max)
DECLARE @ObjectsWithSchema NVarchar(max)
DECLARE @ObjectType varchar(100)
DECLARE @Count_Total int = -1
DECLARE @Count_Current int = 1
DECLARE @Count_CurrentText nvarchar(500)
DECLARE @Count_String Varchar(max) = ''

DECLARE @SchemaList Table (ID INT Identity(1,1), SchemaName Varchar(200))
DECLARE @ObjectList Table (CreateOrder INT , DropOrder INT , ObjectName Varchar(200), ObjectType char(100), ObjectCreateDate Datetime, ObjectDefinitation Datetime)

SET @SqlString = ''
SET @SchemaName = ''
SET @SchemaCount = 1
SET @ObjectCount = 1
SET @Flag = 0

---- Get All Schema List
SET @XML = N'<root><Schema>' + replace(@CopyToSchema,',','</Schema><Schema>') + '</Schema></root>'
INSERT INTO @SchemaList
SELECT RTRIM(LTRIM(t.value('.','varchar(100)'))) from @XML.nodes('//root/Schema') as a(t)
SELECT @TotalSchema = max(ID) from @SchemaList

---- Get All Object List
SET @XML = N'<root><Schema>' + replace(@ObjectName,',','</Schema><Schema>') + '</Schema></root>'
INSERT INTO @ObjectList ( ObjectName )
SELECT RTRIM(LTRIM(t.value('.','varchar(100)'))) from @XML.nodes('//root/Schema') as a(t)


SET @ObjectsWithSchema = ''
select @ObjectsWithSchema=@ObjectsWithSchema+'Object_ID(''['+@CopyFromSchema+'].'+OBJECTNAME+'''),' from @ObjectList
select @ObjectsWithSchema=SUBSTRING(@ObjectsWithSchema,1,LEN(@ObjectsWithSchema)-1)



---- Check @CopyFromSchema Variable
IF NOT EXISTS ( SELECT 1 FROM sys.schemas WHERE NAME = @CopyFromSchema)
BEGIN
 RAISERROR ('SCHEMA NOT FOUND. PLEASE CHECK "@CopyFromSchema" Parameter.',16,1)
 RETURN
END

---- Check @CopyToSchema Variable
IF ((SELECT COUNT(*) FROM sys.schemas WHERE name IN (SELECT SchemaName FROM  @SchemaList))!= @TotalSchema)
BEGIN
 RAISERROR ('ONE OR MORE SCHEMA NOT FOUND. PLEASE CHECK "@CopyToSchema" Parameter.',16,1)
 RETURN
END

---- Check @ObjectName Variable
SET @SqlString = 'SELECT @Flag_OUT =  Count(*) FROM sys.objects WHERE [object_id] IN ('+@ObjectsWithSchema+')'
EXEC Sp_executesql @SqlString,N'@Flag_OUT int OUTPUT',@Flag_OUT = @Flag OUTPUT


IF (@Flag!=@TotalObject)
BEGIN
 RAISERROR('SOME OBJECT(S) NOT FOUND. PLEASE CHECK "@ObjectName" Parameter.',16,1)
 RETURN
END


---- Update @ObjectList Table

UPDATE OBJ_LST SET
 OBJ_LST.ObjectType = ALL_Obj.type_desc,
 OBJ_LST.ObjectCreateDate = ALL_Obj.create_date
FROM @ObjectList OBJ_LST
INNER JOIN SYS.all_objects ALL_Obj
on ALL_Obj.name = OBJ_LST.ObjectName AND SCHEMA_NAME(ALL_Obj.SCHEMA_ID)= @CopyFromSchema


UPDATE OBJ_LST SET OBJ_LST.CreateOrder = Obj_Rank_Table.CreateOrder,
          OBJ_LST.DropOrder = Obj_Rank_Table.DropOrder
FROM @ObjectList OBJ_LST
INNER JOIN
(
 SELECT ROW_NUMBER() OVER(ORDER BY ObjectCreateDate ASC) AS CreateOrder,
     ROW_NUMBER() OVER(ORDER BY ObjectCreateDate DESC) AS DropOrder,
     ObjectName, ObjectType FROM @ObjectList
) AS Obj_Rank_Table
ON OBJ_LST.ObjectName = Obj_Rank_Table.ObjectName
AND OBJ_LST.ObjectType = Obj_Rank_Table.ObjectType

SELECT @TotalObject = max(CreateOrder) from @ObjectList


IF EXISTS(SELECT * FROM tempdb.sys.tables where Object_ID = OBJECT_ID('tempdb.dbo.Table_Col_String'))  
 DROP TABLE [tempdb].[dbo].[Table_Col_String]

IF EXISTS(SELECT * FROM tempdb.sys.tables where Object_ID = OBJECT_ID('tempdb.dbo.Table_Index_String'))  
 DROP TABLE [tempdb].[dbo].[Table_Index_String]

IF EXISTS(SELECT * FROM tempdb.sys.tables where Object_ID = OBJECT_ID('tempdb.dbo.Table_Const_String'))  
 DROP TABLE [tempdb].[dbo].[Table_Const_String]


CREATE TABLE [tempdb].[dbo].[Table_Col_String]
(
 [TableName] [sysname] NOT NULL,
 [ColumnName] [sysname] NULL,
 [column_id] [int] NOT NULL,
 [Column_Text] [nvarchar](max) NULL,
)


CREATE TABLE [tempdb].[dbo].[Table_Index_String]
(
 [Idx_Column_Order] [bigint] NULL,
 [SchemaName] [nvarchar](128) NULL,
 [TableName] [sysname] NOT NULL,
 [ConstraintName] [sysname] NULL,
 [index_id] [int] NOT NULL,
 [type_desc] [nvarchar](60) NULL,
 [is_primary_key] [bit] NULL,
 [is_unique_constraint] [bit] NULL,
 [index_column_id] [int] NULL,
 [column_id] [int] NULL,
 [key_ordinal] [tinyint] NULL,
 [is_descending_key] [bit] NULL,
 [is_included_column] [bit] NULL,
 [ColumnName] [sysname] NULL,
 [Index_String] [nvarchar](max) NULL
)


CREATE TABLE [tempdb].[dbo].[Table_Const_String]
(
 [SchemaName] [nvarchar](128) NULL,
 [TableName] [sysname] NULL,
 [Const_ID] [int] NOT NULL,
 [Constraint_String] [nvarchar](max) NULL
)


---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
---- GET DETIALS OF TABLE COLUMNS. LIKE DATA TYPE, SIZE
---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
SET @SqlString = '
WITH TableColumns
AS
(
 SELECT TAB.[name] AS TableName, TAb.object_id,
 Col.[Name] AS ColumnName, Col.[column_id], Col.[user_type_id], Col.[max_length], Col.[precision], Col.[scale],
 Col.[is_nullable], Col.[is_identity], Col.[is_computed], Col.[default_object_id], Col.[is_sparse],
 TYP.[name] AS DataType,TAB.create_date,
 idColumns.seed_value, idColumns.increment_value,
 COM_COL.[definition]
  FROM SYS.COLUMNS COL
 INNER JOIN SYS.TYPES TYP
 ON COL.user_type_id = TYP.user_type_id
 INNER JOIN SYS.TABLES TAB
 ON TAB.object_id = COL.object_id
 LEFT JOIN sys.identity_columns idColumns
 ON idColumns.object_id = Col.object_id AND Col.is_identity = 1
 LEFT JOIN sys.computed_columns COM_COL
 ON COL.object_id = COM_COL.object_id AND COl.is_computed = 1
 WHERE Schema_Name(TAB.Schema_ID) ='''+@CopyFromSchema+'''
 AND TAB.name in ('''+REPLACE(REPLACE(@ObjectName,' ',''),',',''',''')+''')

)
INSERT INTO [tempdb].[dbo].[Table_Col_String]
SELECT  TableName,ColumnName,column_id
, ''[''+ColumnName+''] ''+
CASE WHEN is_computed = 1 Then ''AS (''+[definition]+'')''
ELSE '' [''+ DataType +''] '' END +
CASE is_identity WHEN 1 THEN ''Identity (''+Convert(Varchar(10),increment_value)+'',''+Convert(Varchar(10),seed_value)+'')'' ELSE '''' END +
CASE
 
 WHEN DataType in (''binary'',''char'') Then ''(''+Convert(Varchar(10),max_length)+'')''
 WHEN DataType in (''nchar'') Then ''(''+Convert(Varchar(10),(max_length/2))+'')''  
 WHEN DataType in (''nvarchar'') AND max_length != -1 Then ''(''+Convert(Varchar(10),(max_length/2))+'')''  
 WHEN DataType in (''nvarchar'') AND max_length = -1  Then ''(MAX)''
 WHEN DataType in (''varbinary'', ''varChar'') AND max_length = -1 Then ''(MAX)''
 WHEN DataType in (''varbinary'', ''varChar'') AND max_length != -1 Then ''(''+Convert(Varchar(10),max_length)+'')''
 WHEN DataType in (''decimal'',''numeric'') Then ''(''+Convert(Varchar(10),[precision])+'', ''++Convert(Varchar(10),(scale))+'')''
 ELSE ''''
 END +
CASE is_sparse WHEN 1 THEN '' SPARSE ''ELSE '''' END +
CASE WHEN IS_computed = 1 THEN '''' WHEN Is_Nullable = 1 THEN '' NULL '' ELSE '' NOT NULL '' END AS Column_Text
FROM TableColumns
ORDER BY create_date,column_id'
--PRINT @sqlString
EXEC (@sqlString)

---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
---- GET DETIALS OF TABLE PRIMARY KEY, UNIQUE KEY AND INDEX PART -I
---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
SET @SqlString = '
;WITH IndexString
AS
(
 SELECT
 --TAb.object_id,Tab.name,
 --idx.*,IDX_COL.*, Col.NAME
 Schema_Name(TAB.schema_id) AS SchemaName,
 TAB.name AS TableName,idx.name AS ConstraintName,
 IDX.index_id,Idx.type_desc,idx.is_primary_key,idx.is_unique_constraint,
 IDX_Col.index_column_id, IDX_COL.column_id,IDX_COL.key_ordinal,IDX_COL.is_descending_key, IDX_col.is_included_column,
 COL.Name AS ColumnName
 FROM SYS.indexes IDX
 INNER JOIN SYS.TABLES TAB
 ON IDX.object_id = TAB.object_id
 LEFT JOIN SYS.index_columns IDX_COL
 ON IDX.object_id = IDX_COL.object_id
 and IDX.index_id = IDX_COL.index_id
 LEFT JOIN SYS.COLUMNS COL
 ON IDX_COL.object_id = COL.object_id
 AND IDX_COL.column_id = COL.column_id
)
INSERT INTO [tempdb].[dbo].[Table_Index_String]
SELECT DISTINCT
DENSE_RANK() OVER(Partition By TableName, index_id ORDER BY TableName, index_id, key_ordinal, is_included_column), * ,''''
FROM IndexString
WHERE ConstraintName IS NOT NULL
AND SchemaName ='''+@CopyFromSchema+'''
AND TableName in ('''+REPLACE(REPLACE(@ObjectName,' ',''),',',''',''')+''')'
EXEC (@sqlString)

---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
---- GET DETIALS OF TABLE PRIMARY KEY, UNIQUE KEY AND INDEX PART -II
---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
SET @SqlString = '
UPDATE IndexString SET [Index_String] =
''
   IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE NAME = ''''IDX_''+Convert(Varchar(10),index_id)+''_''+type_desc+''_''+SchemaName+''_''+TableName  COLLATE SQL_Latin1_General_CP1_CI_AS +'''''') ''+
    CASE WHEN is_primary_key = 1 THEN ''
     ALTER TABLE [''+SchemaName+''].[''+TableName+'']''+'' ADD PRIMARY KEY ''+type_desc+'' (''
     + STUFF((SELECT '', [''+T2.ColumnName+'']''+ CASE WHEN T2.is_descending_key = 1 THEN '' DESC '' ELSE '' ASC '' END FROM [tempdb].[dbo].[Table_Index_String] T2
      WHERE IndexString.SchemaName = T2.SchemaName AND IndexString.TableName = T2.TableName
       AND IndexString.index_id = T2.index_id  AND T2.is_included_column = 0 FOR XML PATH('''')),1,2,'''') +'') ''

      WHEN is_unique_constraint = 1 THEN ''
     ALTER TABLE [''+SchemaName+''].[''+TableName+'']''+'' ADD UNIQUE ''+type_desc+'' (''
     + STUFF((SELECT '', [''+T2.ColumnName+'']''+ CASE WHEN T2.is_descending_key = 1 THEN '' DESC '' ELSE '' ASC '' END FROM [tempdb].[dbo].[Table_Index_String] T2
      WHERE IndexString.SchemaName = T2.SchemaName AND IndexString.TableName = T2.TableName
       AND IndexString.index_id = T2.index_id  AND T2.is_included_column = 0 FOR XML PATH('''')),1,2,'''') +'') ''  
     ELSE
     ''
     CREATE ''+type_desc+'' INDEX [IDX_''+Convert(Varchar(10),index_id)+''_''+type_desc+''_''+SchemaName+''_''+TableName  COLLATE SQL_Latin1_General_CP1_CI_AS +''] ON [''+SchemaName+''].[''+TableName+'']''+
'' (''+ STUFF((SELECT '', [''+T2.ColumnName+'']''+ CASE WHEN T2.is_descending_key = 1 THEN '' DESC '' ELSE '' ASC '' END FROM [tempdb].[dbo].[Table_Index_String] T2
 WHERE IndexString.SchemaName = T2.SchemaName AND IndexString.TableName = T2.TableName
 AND IndexString.index_id = T2.index_id  AND T2.is_included_column = 0 FOR XML PATH('''')),1,2,'''') +'')''  
END + '' '' +
CASE WHEN is_included_column = 1 THEN
'' INCLUDE (''
   + STUFF((SELECT '', [''+T2.ColumnName+'']'' FROM [tempdb].[dbo].[Table_Index_String] T2
    WHERE IndexString.SchemaName = T2.SchemaName AND IndexString.TableName = T2.TableName
     AND IndexString.index_id = T2.index_id  AND T2.is_included_column = 1 FOR XML PATH('''')),1,2,'''') +'')
     ''
 ELSE ''
 ''
END
FROM [tempdb].[dbo].[Table_Index_String]AS IndexString '
EXEC (@sqlString)

---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
---- GET DETIALS OF TABLE CONSTRAINTS
---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
SET @SqlString = '

WITH TAB_Const
AS
(
 select
 ALL_Const.[constid], ALL_Const.[id] AS TABLE_ID, ALL_Const.[Colid],
 SCHEMA_NAME(TAB.schema_id) AS SchemaName, TAB.name AS TableName,COL.name AS ColumnName,
 ISNULL(ISNULL(D_Const.type_desc,C_Const.type_desc),F_Const.type_desc) AS Const_Type,
 ISNULL(ISNULL(D_Const.[name] ,C_Const.[name]),F_Const.[name] ) AS Const_Name,
 ISNULL(D_Const.[definition] ,C_Const.[definition]) AS Const_Definition
 FROM sysconstraints ALL_Const
 LEFT JOIN sys.default_constraints D_Const
 ON ALL_Const.constid = D_Const.object_id
 LEFT JOIN sys.check_constraints C_Const
 ON ALL_Const.constid = C_Const.object_id
 LEFT JOIN Sys.all_objects F_Const
 ON ALL_Const.constid = F_Const.object_id AND F_Const.[type] =''F''
 LEFT JOIN SYS.TABLES TAB
 ON TAB.object_id = ALL_Const.id
 LEFT JOIN SYS.columns COL
 ON COL.object_id = ALL_Const.id
 AND COL.column_id  = ALL_Const.colid
),
foreignKey
AS
(
 select FK.name,FK.type_desc ,FKC.*
 ,(SELECT Name from sys.tables Tab where FKC.parent_object_id = Tab.object_id)  AS parent_object_Name
 ,(SELECT Name from sys.Columns Col where FKC.parent_object_id = Col.object_id AND FKC.parent_column_id = Col.column_id)  AS parent_column_Name
 ,(SELECT Name from sys.tables Tab where FKC.referenced_object_id = Tab.object_id)  AS referenced_object_Name
 ,(SELECT Name from sys.Columns Col where FKC.referenced_object_id = Col.object_id AND FKC.referenced_column_id = Col.column_id)  AS referenced_object_Column_Name
  from sys.foreign_keys FK
 LEFT JOIN sys.foreign_key_columns FKC
 ON FK.object_id = FKC.constraint_object_id
)
INSERT INTO [tempdb].[dbo].[Table_Const_String]
select DISTINCT TAB_Const.SchemaName,TAB_Const.TableName,
Dense_Rank() over(partition by TAB_Const.TableName order by TAB_Const.[constid]) AS Const_ID,
''
   IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE NAME = ''''''+Const_Type+''__''+Convert(Varchar(10),Dense_Rank() over(partition by TAB_Const.TableName order by TAB_Const.[constid])) +''_''+
SchemaName+''_''+TableName  COLLATE SQL_Latin1_General_CP1_CI_AS +'''''')'' +

CASE Const_Type
WHEN ''FOREIGN_KEY_CONSTRAINT''
 THEN
  ''
     ALTER TABLE [''+SchemaName+''].[''+parent_object_Name+''] Add constraint ''+Const_Type+''__''+Convert(Varchar(10),Dense_Rank() over(partition by TAB_Const.TableName order by TAB_Const.[constid])) +''_''+
SchemaName+''_''+TableName  COLLATE SQL_Latin1_General_CP1_CI_AS+
  '' FOREIGN KEY (''+STUFF((SELECT '', ''+parent_column_Name FROM foreignKey T2 WHERE T1.constraint_object_id = T2.constraint_object_id FOR XML PATH('''')),1,2,'''')+'')''+
  '' REFERENCES [''+SchemaName +''].[''+ referenced_object_Name+''] (''+STUFF((SELECT '', ''+ referenced_object_Column_Name FROM foreignKey T2 WHERE T1.constraint_object_id = T2.constraint_object_id FOR XML PATH('''')),1,2,'''')+'')''
ELSE
 ''
     ALTER TABLE [''+SchemaName+''].[''+TableName+''] ADD CONSTRAINT ''+CASE Const_Type
 WHEN ''DEFAULT_CONSTRAINT'' THEN ''DEFAULT_CONSTRAINT__''
 WHEN ''CHECK_CONSTRAINT'' THEN ''CHECK_CONSTRAINT__''
 END
 +Convert(Varchar(10),Dense_Rank() over(partition by TAB_Const.TableName order by TAB_Const.[constid])) + ''_''+
 +SchemaName+''_''+TableName
 +CASE Const_Type
 WHEN ''DEFAULT_CONSTRAINT'' THEN '' DEFAULT ('' + Const_Definition +'') FOR [''+ ColumnName +''] ''
 WHEN ''CHECK_CONSTRAINT'' THEN '' CHECK ('' + Const_Definition +'')''
 END
END AS Constraint_String
--INTO Table_Const_String
FROM TAB_Const
LEFT JOIN foreignKey T1
ON constraint_object_id = T1.constraint_object_id AND TAB_Const.Const_Name = T1.Name
WHERE TAB_Const.Const_Type IS NOT NULL
AND SchemaName ='''+@CopyFromSchema+'''
AND TableName in ('''+REPLACE(REPLACE(@ObjectName,' ',''),',',''',''')+''')'
EXEC (@sqlString)



SET @SqlString='
SET XACT_ABORT ON
--SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
--BEGIN TRANSACTION
'


WHILE ( @TotalSchema >= @SchemaCount )
BEGIN
 SET @ObjectCount = 1
 SELECT @SchemaName = SchemaName FROM @SchemaList WHERE ID = (@SchemaCount)

 IF (@SchemaCount=1)
 BEGIN
  SET  @SqlString = @SqlString+'
  SELECT ''[ BEFORE ]'',Schema_ID,SCHEMA_NAME(Schema_ID) AS ''Schema_Name'',Name,create_date,modify_date
  FROM SYS.OBJECTS WHERE Name IN ('''+REPLACE(REPLACE(@ObjectName,' ',''),',',''',''')+''') ORDER BY CREATE_DATE DESC, MODIFY_DATE DESC
  DECLARE @SQL nvarchar(max)
  '
 END

 ---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 ---- THIS IS ONLY FOR DROP TABLES
 ---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 WHILE (@TotalObject >= @ObjectCount)
 BEGIN

  SELECT @CurrentObjectName = ObjectName , @ObjectType = ObjectType FROM @ObjectList WHERE DropOrder = (@ObjectCount)
 
  IF (@ObjectType in ('USER_TABLE'))
  BEGIN
   SET @SqlString=@SqlString+'

   ----##################### ['+@SchemaName+'].['+@CurrentObjectName+']  #####################----

   IF EXISTS (SELECT 1 FROM sys.Objects WHERE NAME ='''+@CurrentObjectName+''' AND SCHEMA_ID= SCHEMA_ID('''+@SchemaName+'''))
   DROP TABLE ['+@SchemaName+'].['+@CurrentObjectName+']'
  END

  SET @ObjectCount = @ObjectCount + 1
 END

 SET @SchemaCount = @SchemaCount +1
END


SET @SchemaCount = 1

WHILE ( @TotalSchema >= @SchemaCount )
BEGIN
 SELECT @SchemaName = SchemaName FROM @SchemaList WHERE ID = (@SchemaCount)

 SET @ObjectCount = 1
 
 WHILE (@TotalObject >= @ObjectCount)
 BEGIN
  SELECT @CurrentObjectName = ObjectName , @ObjectType = ObjectType FROM @ObjectList WHERE CreateOrder = (@ObjectCount)

  IF (@ObjectType in ('VIEW','SQL_STORED_PROCEDURE','SQL_SCALAR_FUNCTION'))
  BEGIN
 
   SET @SqlString=@SqlString+'
   IF EXISTS (SELECT 1 FROM sys.Objects WHERE NAME ='''+@CurrentObjectName+''' AND SCHEMA_ID= SCHEMA_ID('''+@SchemaName+'''))
   BEGIN
    DROP '+CASE @ObjectType WHEN 'VIEW' THEN 'VIEW' WHEN 'SQL_STORED_PROCEDURE' THEN 'PROCEDURE' WHEN 'SQL_SCALAR_FUNCTION' THEN 'FUNCTION' END
     +' ['+@SchemaName+'].['+@CurrentObjectName+']
   END'
 
   SET @SqlString=@SqlString+'
   SELECT @SQL = REPLACE(REPLACE(OBJECT_DEFINITION (object_id('''+@CopyFromSchema+'.'+@CurrentObjectName+''')),'''+@CopyFromSchema+''','''+@SchemaName+'''),'''+@CopyFromSchema+'.'','''+@SchemaName+'.'')
   exec sp_executeSQL @SQL
   '
  END
  ELSE IF (@ObjectType = 'USER_TABLE' )
  BEGIN

   SET @SqlString=@SqlString+'

    ----$$$$$$$$$$$$$$$$$$$$$ ['+@SchemaName+'].['+@CurrentObjectName+']  $$$$$$$$$$$$$$$$$$$$$----

   CREATE TABLE ['+@SchemaName+'].['+@CurrentObjectName+'] (
    '

    SET @Count_Total = -1
    SET @Count_String = ''
    SET @Count_Current = 1

    ---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ---- GENERATE TABLE COLUMNS
    ---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    SET @Count_Current = 1
    SELECT @Count_Total = -1

    SELECT @Count_Total = MAX(column_id) From [tempdb].[dbo].[Table_Col_String] WHERE TableName = @CurrentObjectName

    WHILE (@Count_Current <= @Count_Total)
    BEGIN
     SELECT @Count_String = Column_Text FROM [tempdb].[dbo].[Table_Col_String] WHERE TableName = @CurrentObjectName AND column_id = @Count_Current
     
     IF (@Count_Current = 1)
     BEGIN
      SET @SqlString = @SqlString + @Count_String

      IF (@Count_Current < @Count_Total)
       SET @SqlString = @SqlString + ' , '
     END

     IF (@Count_CurrentText != @Count_String)
     BEGIN
      SET @SqlString = @SqlString + @Count_String

      IF (@Count_Current < @Count_Total)
       SET @SqlString = @SqlString + ' , '
     END
     SET @Count_CurrentText = @Count_String

     SET @Count_Current = @Count_Current + 1
    END
    SET @SqlString = @SqlString + ' )
    '

    ---+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ---- GENERATE TABLE INDEX
    ---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   
    SET @Count_Total = -1
    SET @Count_String = ''
    SET @Count_Current = 1

    SELECT @Count_Total = MAX(Index_id) From  [tempdb].[dbo].[Table_Index_String] WHERE TableName = @CurrentObjectName

    WHILE (@Count_Current <= @Count_Total)
    BEGIN
   
     SELECT TOP 1 @Count_String = Index_String FROM [tempdb].[dbo].[Table_Index_String] WHERE TableName = @CurrentObjectName AND Index_id = @Count_Current
     SET @SqlString = @SqlString + @Count_String

     SET @Count_Current = @Count_Current + 1
    END

    SET @SqlString = REPLACE(REPLACE(@SqlString,'_'+@CopyFromSchema+'_','_'+@SchemaName+'_'),'['+@CopyFromSchema+']','['+@SchemaName+']')


 
    ---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ---- GENERATE TABLE CONSTRAINTS
    ---++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    SET @Count_Total = -1
    SET @Count_String = ''
    SET @Count_Current = 1

    SELECT @Count_Total = MAX(Const_ID) From  [tempdb].[dbo].[Table_Const_String] WHERE TableName = @CurrentObjectName

    WHILE (@Count_Current <= @Count_Total)
    BEGIN
     SELECT @Count_String = Constraint_String FROM [tempdb].[dbo].[Table_Const_String] WHERE TableName = @CurrentObjectName AND Const_ID = @Count_Current
     SET @SqlString = @SqlString + @Count_String

     SET @Count_Current = @Count_Current + 1
    END

    SET @SqlString = REPLACE(REPLACE(@SqlString,'_'+@CopyFromSchema+'_','_'+@SchemaName+'_'),'['+@CopyFromSchema+']','['+@SchemaName+']')
    --exec sp_executeSQL @SqlString
  END

  SET @ObjectCount = @ObjectCount + 1
 END
 
 SET @SchemaCount = @SchemaCount + 1
END

SET @SqlString = @SqlString +'
--IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
--IF @@TRANCOUNT>0 COMMIT TRANSACTION

SELECT ''[ AFTER ]'',Schema_ID,SCHEMA_NAME(Schema_ID) AS ''Schema_Name'',Name,create_date,modify_date
FROM SYS.OBJECTS WHERE Name in ('''+REPLACE(REPLACE(@ObjectName,' ',''),',',''',''')+''')  ORDER BY CREATE_DATE DESC, MODIFY_DATE DESC
'


IF EXISTS(SELECT * FROM tempdb.sys.tables where Object_ID = OBJECT_ID('tempdb.dbo.Table_Col_String'))  
 DROP TABLE [tempdb].[dbo].[Table_Col_String]

IF EXISTS(SELECT * FROM tempdb.sys.tables where Object_ID = OBJECT_ID('tempdb.dbo.Table_Index_String'))  
 DROP TABLE [tempdb].[dbo].[Table_Index_String]

IF EXISTS(SELECT * FROM tempdb.sys.tables where Object_ID = OBJECT_ID('tempdb.dbo.Table_Const_String'))  
 DROP TABLE [tempdb].[dbo].[Table_Const_String]


PRINT @SqlString
EXEC (@SqlString)

END
SET NOCOUNT OFF