Thursday, November 23, 2017

delete duplicate records from table and reference tables




declare @id varchar(MAX)


Create Table #MyDetails(cid BigInt,uqId varchar(max))

--select count(uniqueid) as t,uniqueID from companydetails group by uniqueid having count(uniqueid)>1 order by t desc

INSERT into #MyDetails(cid,uqId) (select count(uniqueid) as t,uniqueID from companydetails group by uniqueid having count(uniqueid)>1)




 DECLARE id_Cursor CURSOR FOR select uqId from #MyDetails
OPEN id_Cursor;
FETCH NEXT FROM id_Cursor into @id;
WHILE @@FETCH_STATUS = 0
   BEGIN
  --
    Exec [dbo].[sp_deleteDuplicateCompanyIds] @id
FETCH NEXT FROM id_Cursor into @id;
    END;
CLOSE id_Cursor;
DEALLOCATE id_Cursor;




create PROCEDURE [dbo].[sp_deleteDuplicateCompanyIds]
@uID   Nvarchar(Max)
AS
BEGIN

Declare @MaxId BigInt

--Set @uID='0000000003983694'
select @MaxId =  max(CompanyDetailsID) from [dbo].[CompanyDetails] where UniqueId=@uID

update [dbo].[BeneficialShareHolder] set companydetailsid=@MaxId where CompanyDetailsID in
(select [CompanyDetailsID] from [dbo].[CompanyDetails] where UniqueId=@uID and CompanyDetailsID <> (@MaxId))

--2.2

update [dbo].FundHolderDetails set companydetailsid=@MaxId where CompanyDetailsID in
(select [CompanyDetailsID] from [dbo].[CompanyDetails] where UniqueId=@uID and CompanyDetailsID <> (@MaxId))

--3
delete from [CompanyDetails]  where CompanyDetailsID in
(select [CompanyDetailsID] from [dbo].[CompanyDetails] where UniqueId=@uID and CompanyDetailsID <> (@MaxId))


/// <summary>
/// Remove duplicate records
/// </summary>
/// <param name="table">DataTable for removing duplicate records</param>
/// <param name="DistinctColumn">Column to check for duplicate values or records</param>
/// <returns></returns>
public DataTable RemoveDuplicateRows(DataTable table, string DistinctColumn)
{
    try
    {
        ArrayList UniqueRecords = new ArrayList();
        ArrayList DuplicateRecords = new ArrayList();

        // Check if records is already added to UniqueRecords otherwise,
        // Add the records to DuplicateRecords
        foreach(DataRow dRow in table.Rows)
        {
            if (UniqueRecords.Contains(dRow[DistinctColumn]))
                DuplicateRecords.Add(dRow);
            else
                UniqueRecords.Add(dRow[DistinctColumn]);
        }

        // Remove duplicate rows from DataTable added to DuplicateRecords
        foreach (DataRow dRow in DuplicateRecords)
        {
            table.Rows.Remove(dRow);
        }

        // Return the clean DataTable which contains unique records.
        return table;
    }
    catch (Exception ex)
    {
        return null;
    }
}

DataTable DuplicateRec = objDatabase.getTable("SQL Query");
DataTable UniqueRec = RemoveDuplicateRows
(DuplicateRec, "Column Name to check for duplicate records");




Tuesday, November 21, 2017

Find all duplicates in table


//uniqueid is columns with duplicate
select count(uniqueid) as t,uniqueID from companydetails group by
uniqueid having count(uniqueid)>1 order by t desc

Wednesday, November 15, 2017

Get all constraints in sql in specific db ( SQL CONSTRAINTS )

SELECT * FROM sys.objects
WHERE type_desc LIKE ‘%CONSTRAINT’




ALTER TABLE [dbo].[CompanyDetails]

ALTER COLUMN ClientName VARCHAR(35) COLLATE Latin1_General_CI_AS

Wednesday, October 25, 2017

simple cursor

Create table #tmp ( SalesOrderID int, OrderQty int ) GO --simple cursor in sql server Declare @orderid int, @orderqty int -- declare a cursor DECLARE insert_cursor CURSOR FOR SELECT SalesOrderId,OrderQty from Sales.SalesOrderDetail WHERE SalesOrderID=43659 -- open cursor and fetch first row into variables OPEN insert_cursor FETCH NEXT FROM insert_cursor into @orderid,@orderqty -- check for a new row WHILE @@FETCH_STATUS=0 BEGIN -- do complex operation here Insert into #tmp SELECT @orderid,@orderqty -- get next available row into variables FETCH NEXT FROM insert_cursor into @orderid,@orderqty END close insert_cursor Deallocate insert_cursor GO

temp tables in sql

http://www.c-sharpcorner.com/blogs/local-and-global-temporary-tables-using-stored-procedure-in-sql-server

Monday, October 23, 2017

Get list of all indexes in current database ----- find Index for all tables in DB

SELECT DB_NAME() AS Database_Name
, sc.name AS Schema_Name
, o.name AS Table_Name
, i.name AS Index_Name
, i.type_desc AS Index_Type
FROM sys.indexes i
INNER JOIN sys.objects o ON i.object_id = o.object_id
INNER JOIN sys.schemas sc ON o.schema_id = sc.schema_id
WHERE i.name IS NOT NULL
AND o.type = 'U'
ORDER BY o.name, i.type


Index naming convention:
PK_ for primary keys
UK_ for unique keys
IX_ for non clustered non unique indexes
UX_ for unique indexes
All of my index name take the form of
<index or key type>_<table name>_<column 1>_<column 2>_<column n>


Check index on specific table
select * from sys.indexes
where object_id = (select object_id from sys.objects where name = 'TableName')




Tuesday, October 10, 2017

(split) string with comma in SQL Server stored procedure (SQL COMMA SPLIT)



DECLARE @str VARCHAR(500) = '1,2,3'
CREATE TABLE #Temp (tDay VARCHAR(100),Tid BigInt)
WHILE LEN(@str) > 0
BEGIN
    DECLARE @TDay VARCHAR(100)
DECLARE @Tid BIGINT
    IF CHARINDEX(',',@str) > 0
BEGIN
        SET  @TDay = SUBSTRING(@str,0,CHARINDEX(',',@str))
SET @Tid=CAST(@TDay AS bigint)
END
    ELSE
        BEGIN
        SET  @TDay = @str
SET @Tid=0
        SET @str = ''
        END
  INSERT INTO  #Temp VALUES (@TDay,@Tid)
 SET @str = REPLACE(@str,@TDay + ',' , '')
 END




BELOW IS WITH LIVE EXAMPLE

USE [STRATEOwnership]
GO
/****** Object:  StoredProcedure [dbo].[sp_getBeneficialHolderDetails]    Script Date: 2017/10/10 11:30:02 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_getBeneficialHolderDetails]
@IDs varchar(500)
AS
BEGIN
SET NOCOUNT ON;

/* Get all IDS after splitting*/
DECLARE @str VARCHAR(500) = @IDs
CREATE TABLE #Temp (tDay VARCHAR(100),Tid BigInt)
WHILE LEN(@str) > 0
BEGIN
    DECLARE @TDay VARCHAR(100)
DECLARE @FundHolderDetailID BIGINT
    IF CHARINDEX(',',@str) > 0
BEGIN
        SET  @TDay = SUBSTRING(@str,0,CHARINDEX(',',@str))
SET @FundHolderDetailID=CAST(@TDay AS bigint)
END
    ELSE
        BEGIN
        SET  @TDay = @str
SET @FundHolderDetailID=0
        SET @str = ''
        END
  INSERT INTO  #Temp VALUES (@TDay,@FundHolderDetailID)
 SET @str = REPLACE(@str,@TDay + ',' , '')
 END


SELECT [t0].[Holdings], [t0].[Unique Identifier] AS [UniqueIdentifier], [t1].[Client Name] AS [ClientName], [t1].[ClientName1], [t1].[Address1], [t1].[Address2]
FROM [BeneficialShareHolder] AS [t0], [CompanyDetails] AS [t1]
WHERE ([t0].[FundHolderDetailID] in (SELECT Tid FROM #Temp)) AND ([t0].[CompanyDetailsID] = ([t1].[CompanyDetailsID]))


drop table #Temp

END

Monday, October 9, 2017

get all indexes in DB

SELECT DB_NAME() AS Database_Name
, sc.name AS Schema_Name
, o.name AS Table_Name
, i.name AS Index_Name
, i.type_desc AS Index_Type
FROM sys.indexes i
INNER JOIN sys.objects o ON i.object_id = o.object_id
INNER JOIN sys.schemas sc ON o.schema_id = sc.schema_id
WHERE i.name IS NOT NULL
AND o.type = 'U'
ORDER BY o.name, i.type

Tuesday, October 3, 2017

DateTimeCOnversions

  class Program
    {
        static void Main(string[] args)
        {
            //string date = "01 April 2017";
            string[] dates = { "20170404", "20170703", "20170601", "20170405" };
            string dt;
            int lastday;

            string Month = "April", Year = "2017";
            string date = "01" + " " + Month + " " + Year;
            foreach (var item in dates)
            {
                //string date conversion
                dt = DateTime.ParseExact(item, "yyyyMMdd",
                CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
                Console.WriteLine("dts:" + dt);
            }

            //long date conversion
            date = (Convert.ToDateTime(date).ToString("yyyy-MM-dd"));
            lastday = DateTime.DaysInMonth(Convert.ToDateTime(date).Year, Convert.ToDateTime(date).Month);

            string lastdate = lastday.ToString() + " " + Month + " " + Year;
            lastdate = (Convert.ToDateTime(lastdate).ToString("yyyy-MM-dd"));

            Console.WriteLine("lastDay:" + lastday);
            Console.WriteLine("first date:" + date);
            Console.WriteLine("lastdate:" + (Convert.ToDateTime(lastdate).ToString("yyyy-MM-dd")));
            DateTime ldate = Convert.ToDateTime((Convert.ToDateTime(lastdate).ToString("yyyy-MM-dd")));
            DateTime fdate = Convert.ToDateTime(date);

            Console.WriteLine("fdate:" + fdate + ";ldate" + ldate);
            Console.ReadLine();
        }
    }

Wednesday, September 27, 2017

WCF REST Verbs


 REST is usually used with these HTTP verbs:
  • GET - retrieving items
  • POST - inserting items
  • PUT - updating items
  • DELETE - deleting items
You should never use GET for anything else then retrieving items. Using HTTP GET for data modification is considered as a bad practice in whole web development. To trigger GET you just need to create link on the web page or simply type a URL to the browser. You will hit refresh 50 times and you have 50 same inserts. Data modification should be always done with POST. If you have form which triggers HTTP POST (Post cannot be triggered directly) and you hit refresh browser will usually ask you if you want the form to be submitted again = if you really want to post and process the data again to the server.
Another problem is that GET request can be cached and redirected but POST requests cannot.

Monday, September 25, 2017

Get all files in directory C#

class Program
{
    static void Main()
    {
        // Get list of files in the specific directory.
        // ... Please change the first argument.
        string[] files = Directory.GetFiles("C:\\myDir\\",
            "*.*",          SearchOption.AllDirectories);

        // Display all the files.
        foreach (string file in files)
        {
            Console.WriteLine(file);
        }
    }
}

Thursday, July 20, 2017

Git command line instructions




Command line instructions

Git global setup
git config --global user.name "Ranganayaki Sermoria"
git config --global user.email "git registered email id"

Create a new repository
git clone "GIT URL"

cd stratesample
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master


Existing folder
cd existing_folder
git init
git remote add origin "GIT URL"

git add .
git commit
git push -u origin master

Existing Git repository

cd existing_repo
git remote add origin "GIT URL"
git push -u origin --all
git push -u origin --tags

https://stackoverflow.com/questions/13507430/git-commit-in-terminal-opens-vim-but-cant-get-back-to-terminal

Git commit in terminal opens VIM, but can't get back to terminal

To save your work and exit press Esc and then :wq (w for write and q for quit).
Alternatively, you could both save and exit by pressing Esc and then :x
To set another editor do export EDITOR=myFavoriteEdior


Get latest from GIT

 git fetch origin
 git checkout master
 git merge origin/master
Push latest into GIT
git push -u origin --all

/* delete directory from GIT repository*

  1. git rm -r directoryName
  2. git commit -m "delete message"
  3. git push origin 'master'

Tuesday, July 18, 2017

Read from text File and display data on HTML page

<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader; //GLOBAL File Reader object for demo purpose only

/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}

/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}

/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>

Wednesday, May 17, 2017

Installing and configuring Bower




Install:
Use command line or terminal to install these packages:
$ npm install -g bower
$ npm install -g bower-art-resolver

Configure Bower

  • Go to your development root directory e.g. c:\code
  • Create new file named, .bowerrc
  • Add below content to the file
{
  "registry": {
    "search": [
      "http://bams-sami-api.int.thomsonreuters.com/artifactory/api/bower/default.bower.global",
      "https://bower.herokuapp.com"
    ]
  },
  "resolvers": [
    "bower-art-resolver"
  ],
  "proxy": "http://webproxy.int.westgroup.com:80/",
  "https-proxy": "http://webproxy.int.westgroup.com:80/",
  "strict-ssl": false
}
Note: The proxy and https-proxy are optional parameters.

Proxy

Depending on your proxy setting, you may have problems connecting to BAMS e.g. if you have HTTP_PROXY and HTTPS_PROXY.
You can pass a comma separated hostnames to NO_PROXY environment variable for which the proxy settings will be ignored e.g. the BAMS hostname and specific emea BAMS url: bams-sami-api.int.thomsonreuters.com,bams-emea-sami-api.int.thomsonreuters.com.

Install Elements

With .bowerrc in place, you can now install any elements by simply running bower install element-name:
example : $ bower install dependency_libraries
install jquery using bower :
$ bower install jquery
install typeScript using bower :
bower install DefinitelyTyped
install Inversify JS using bower :bower install inversify#v1.0.0
Default Installation by npm can be done,
  • check if there is package.json in your project
  • add all dependencies in package.json then save package.json in root folder of the project (as direct child)
  • below is sample code for package.json
{
"name": "Ownership",
"version": "12.1.0",
"private": true,
"config": {
"save-exact": true
},
"dependencies": {
"lodash": "3.10.1",
"request": "2.72.0",
"xmldom": "0.1.19"
},
"devDependencies": {
"autoprefixer-loader": "3.1.0",
"babel-core": "6.10.4",
"babel-eslint": "6.1.0",
"babel-loader": "6.2.4",
"babel-plugin-check-es2015-constants": "6.8.0",
"babel-plugin-transform-class-properties": "6.10.2",
"babel-plugin-transform-es2015-arrow-functions": "6.8.0",
"babel-plugin-transform-es2015-block-scoping": "6.10.1",
"babel-plugin-transform-es2015-classes": "6.9.0",
"babel-plugin-transform-es2015-computed-properties": "6.8.0",
"babel-plugin-transform-es2015-destructuring": "6.9.0",
"babel-plugin-transform-es2015-object-super": "6.8.0",
"babel-plugin-transform-es2015-parameters": "6.9.0",
"babel-plugin-transform-es2015-shorthand-properties": "6.8.0",
"babel-plugin-transform-es2015-spread": "6.8.0",
"babel-plugin-transform-es2015-template-literals": "6.8.0",
"babel-plugin-transform-exponentiation-operator": "6.8.0",
"babel-plugin-transform-function-bind": "6.8.0",
"babel-plugin-transform-object-rest-spread": "6.8.0",
"babel-plugin-transform-regenerator": "6.9.0",
"babel-polyfill": "6.9.1",
"connect-livereload": "0.4.0",
"css-loader": "0.19.0",
"eslint": "3.9.1",
"eslint-loader": "1.4.0",
"exports-loader": "0.6.3",
"expose-loader": "0.7.0",
"express": "4.10.2",
"extract-text-webpack-plugin": "0.8.2",
"file-loader": "0.8.4",
"grunt": "0.4.5",
"grunt-bump": "0.3.0",
"grunt-connect-proxy": "0.1.10",
"grunt-contrib-clean": "0.6.0",
"grunt-contrib-connect": "0.7.1",
"grunt-contrib-copy": "0.5.0",
"grunt-contrib-less": "1.4.0",
"grunt-exec": "0.4.5",
"grunt-githooks": "0.5.0",
"grunt-karma": "0.12.1",
"grunt-prompt": "1.3.0",
"grunt-webpack": "1.0.11",
"html-loader": "0.3.0",
"html-webpack-plugin": "1.6.2",
"istanbul-instrumenter-loader": "0.2.0",
"jasmine-core": "2.2.0",
"json-dup-key-validator-loader": "^1.0.0",
"json-loader": "0.5.3",
"karma": "0.13.22",
"karma-coverage": "1.1.0",
"karma-jasmine": "0.3.6",
"karma-phantomjs-launcher": "0.2.1",
"karma-sourcemap-loader": "0.3.6",
"karma-spec-reporter": "0.0.20",
"karma-webpack": "1.7.0",
"less": "2.5.3",
"less-loader": "2.2.1",
"load-grunt-tasks": "0.6.0",
"ng-annotate-loader": "0.0.10",
"ngtemplate-loader": "1.3.1",
"null-loader": "0.1.1",
"phantomjs": "1.9.18",
"semver": "4.3.6",
"style-loader": "0.12.4",
"time-grunt": "0.4.0",
"url-loader": "0.5.6",
"webpack": "1.12.2",
"webpack-dev-server": "1.12.0"
},
"scripts": {
"start": "grunt serve",
"postinstall": "grunt githooks"
}
}
run all below commands in npm (make sure you are in the project folder directory)
  • npm install -g bower-art-resolver
  • npm i
  • In order to run an application one should first build it and then publish this build into Eikon App Engine. Development build, which results in non-minified files with sourcemaps in /__dist/
Production build, results in minified files in /__dist/ npm run prod
Testing Tests are implemented very roughly and are subject to some further development. As for now unit testing is supported by running npm test You can also debug tests by running them in Chrome: karma start karma.conf.js --browsers=Chrome --single-run=false In initial version there's a single unit test for Jet Quote Service.

Thursday, April 13, 2017

Excel 2007 auto Refresh spreadsheet to update NOW()

place the below shown code in ThisWorkbook

Private Sub Workbook_Open()
    Call Application.OnTime(Now + TimeValue("00:00:01"), "AutoCalculate")

End Sub


and the AutoCalculate macro in the VBA project


Sub AutoCalculate()
' AutoCalculate Macro
    Calculate
    Call Application.OnTime(Now + TimeValue("00:00:10"), "AutoCalculate")
End Sub



The above macro calls itsefl every 1 minute and 5 seconds



https://sites.google.com/site/excelforbeginners/Home/vba-codes/clock-with-automatic-refresh




https://www.google.com/search?rlz=1C1CHFX_en__601__687&espv=2&biw=1439&bih=768&q=excel+auto+refresh+now()&sa=X&ved=0ahUKEwj32MvPkZ_TAhVRFMAKHfyFD78Q1QIIdygH

Wednesday, February 15, 2017

Node.JS

Node.js is an open source, cross-platform runtime environment for building server side and networking applications using JavaScript. Node.js provides an asynchronous, event driven framework to build highly scalable networking applications using JavaScript. And, yes -- Node.js leverages all the benefits that an open source technology has to offer. You can take advantage of the package manager called npm for publishing and sharing open source Node.js libraries with the Node.js community. This article presents a discussion on the concepts of Node.js, why it is needed and illustrates the concepts covered by implementing a simple TCP Server. This TCP Server is consumed using a console application written in C#.

Tuesday, January 10, 2017

MVC Basics


In Asp.Net MVC request flow in general moves as follows:-
Step 1:- The first hit comes to the controller.
Step 2:- Depending on the action controller creates the object of the model. Model in turn calls the data access layer which fetches data in the model.
Step 3:- This data filled model is then passed to the view for display purpose.




Controller:

Logic which will handle the user requests and user’s interaction with server. In short User Interaction Logic


What is Action Method?

Action method is simply a public method inside controller which accepts user’s request and returns some response


Views :
user interface design is termed as UI layer and in Asp.Net MVC it is termed as View.

What is ContentResult?

ViewResult represents a complete HTML response whereas ContentResult represents a scalar text response. It’s just like returning pure string. Difference is ContentResult is aActionResult wrapper around string result. ContentResult is also the child of ActionResult.


Model:
In Asp.Net MVC model represent the business data.