Saturday, December 24, 2011

Use unpivot to convert columns into rows


blog
In a previous blog we converted rows into columns using pivot, now this time i needed to convert columns into rows. This was simply achieved using the unpivot functionality in sql server.

declare @tbl table(name varchar(50), amt1 numeric(12,2), 
    amt2 numeric(12,2))
    
insert into @tbl(name, amt1, amt2)values('ppv', 1, 3)
insert into @tbl(name, amt1, amt2)values('ppvs', 41, 43)

select * from @tbl 

select * from @tbl unpivot
 ([Amt] for Types in (amt1, amt2)) as unpv
 
 
Credits:
Thanks to Sachin for this!!

Thursday, December 22, 2011

Running total with cross join

Declare @tbl table (branch varchar(100), date date, amt numeric(12,2))insert into @tbl(branch, date, amt)select Branch, DATE, SUM(amount) from RPT_PledgedAmount awhere a.Branch in ('f001','F008','F009','F010','F011','F012','F013','F014')group
order
by Branch, DATE by Branchselect
group
a.branch, a.date, a.amt, sum(b.amt) from @tbl a cross join @tbl b where a.branch = b.branch and b.date <= a.date by a.branch, a.date, a.amtorder by a.branch,a.date

Wednesday, December 14, 2011

Sql Server

From this string
'D:\DBF_004_11_12_14_V11\FDMS\024.dbf' we need to extract the file name 024

Declare @fileName Varchar(500)set @fileName = 'D:\DBF_004_11_12_14_V11\FDMS\024.dbf'select LEFT(RIGHT(@fileName , charINDEX('\', reverse(@fileName )) - 1), 3)
Split string into a table using table valued functions

create Function dbo.fn_split(@Message Varchar(1000), @delimiter char(1), @index int ) Returns @TblSplit Table(Id Int Identity(1,1),Value
)
Varchar(500)As
Begin
Declare
@curIndex
@pos
@prevPos
@result





int = 0, int = 1, int = 0, varchar(1000) while @pos > 0 Begin set @pos = CHARINDEX(@delimiter, @Message, @prevPos); if(@pos > 0) begin-- get the chars between the prev position to next delimiter pos


set @result = SUBSTRING(@message, @prevPos, @pos-@prevPos) end else begin--get last delim message


set @result = SUBSTRING(@message, @prevPos, LEN(@message)) end iNSERT INTO @TblSplit(Value) vALUES(@result)



set @prevPos = @pos + 1 set @curIndex = @curIndex + 1; end return; End

test:
select * FROM dbo.fn_SPLIT('D:\DBF_004_11_12_14_V11\FDMS\024.dbf','\', 2)

Sunday, December 4, 2011

Get datetime in YYYYMM format–Sql Server

 

I need to get the date in YYYYMM format i.e. ‘2011-01-23’ becomes ‘201101’

declare @date date = '2016-11-23'
select convert(varchar(6), @date, 112)

Saturday, December 3, 2011

Get Running Total with CTE

 

Declare @Table table (id int identity(1,1), amount numeric(12,2), run_total numeric(12,2))
Insert into @Table(amount) Values( 1000)
Insert into @Table(amount) Values( 2000)
Insert into @Table(amount) Values(4000)
Insert into @Table(amount) Values(4000)
Insert into @Table(amount) Values(6000)
Insert into @Table(amount) Values(3000)


;With CTE_Tbl(id, amount, run_total)
As
(
select id, amount, amount as run_total
from @Table t where id = 1
union all
select t1.id, t1.amount, cast (t1.amount + c.run_total as numeric(12,2)) as rt
from @Table t1
join CTE_Tbl c on c.id+1 = t1.id
)
select * from CTE_Tbl

Sql Function to display Financial Quarter



Create Function fn_FinancialQuarter(@Date date )Returns Varchar(50)As
Begin
Declare @Quarter Varchar(50)Declare @Month Int = MOnth(@Date)
If(@Month <= 3)BeginSET @Quarter = 'Q-4 ' + Cast(YEAR(DATEADD(Year, -1, @date)) as varchar(10))EndElseBeginSET @Quarter = 'Q ' + Cast(((MONTH(@Date) - 4) / 3) + 1 as varchar(50)) + '-' + cast(YEAR(@date) as varchar(10))EndReturn @QuarterEnd

Thursday, December 1, 2011

Use CTE & Row_Number to update the Row Number

I had a table where i needed the row number and i had forgotten to insert it. I got this solved using CTE and the Row_Number function.

Declare @test table (name varchar(50), rowno int)
insert into @test (name, rowno) Values ('pramod', 1)
insert into @test (name, rowno) Values ('dileep', 1)
insert into @test (name, rowno) Values ('hari', 1);

with r_SomeTable
as
(
select *
, row_number() over(order by name) as rnk
from @test
)
update r_SomeTable
set rowno = rnk;
select * from @test

Monday, November 28, 2011

Thursday, November 17, 2011

A Script Combiner to combine sql scripts

While preparing a release for our tour operator software TourMast, building the sql release script is always a night mare especially when you have many clients at different versions of the application. In the current situation we have the following folder structure for sql server scripts.

Sql scripts folder structure

Tuesday, November 8, 2011

Backspace - return to previous page fix

In chrome, pressing of backspace will cause the page to return to the previous page, thought at first look this doesn’t seem like an issue, it becomes one when using chrome for data entry into forms.

Googling for this led to the extension “Back Space Means Backspace” for google chrome which prevents this functionality. You can use this link http://www.chromeextensions.org/appearance-functioning/backspacemeansbackspace/

Sunday, October 9, 2011

Extending Javascript Date functions

I often come across the need for the following functionality in the Date object in javascript. I believe these are basic functionality that should have been there, but then who cares!! anyone can extend these. So in a series of blogs i will be extending the Date object using the javascript prototype :-)

Functionality Sample
Date.AddDay Date.AddDays Javascript
   

 

Wednesday, September 28, 2011

Render a tree with knockout.js

While developing the software for backoffice tour operators, we came across the need to display hierarchical data with knockout.js. Let us consider the following sample situation:

We need to display the features of our software for tour operators in a tree structure as shown below.

newMockup


View a working sample here!!

Thursday, September 15, 2011

An alternative to the combo box

While developing the web application for tour operators @ syneity, we felt the need to move off from the combo box to something better. So here we will be designing the mockup for the same. We have identified the following states for this control.

Sl. State Details
1 Initial No data is selected
2 Typing Data is being entered into the control
3 Selected An item is selected from the search result
4 Add User needs to enter a new value, one that is not there in the search result

Saturday, September 3, 2011

Automating the build process

With the release of our Software for tour operators and the purchase of the same by a few operators, we felt the need to automate our release process. Our requirements in a nut shell:

“Take the latest version from our SVN repository, build it, run the scripts on the database and upload the build output to the website”

Nice, but then how do we do this??

That is what i am looking for….. will update with my findings..

Thursday, July 28, 2011

Sql Server 2008 Merge sample

Sql server Merge is a great tool as mentioned in my earlier blog. In this blog, i have a better example of using sql server 2008 merge.

If Not Exists(select * from sys.tables where name = 'TestTable')
Create Table TestTable(Id Int, SerialNo Int, Notes Varchar(50))

Declare @Tbl Table(SerialNo Int, Notes Varchar(50))
begin tran

Insert into TestTable(Id, SerialNo, Notes)
Values(1, 1, 'shouldnot be affected')
Insert into TestTable(Id, SerialNo, Notes)
Values(1, 2, 'shouldnot be affected')


Insert into TestTable(Id, SerialNo, Notes)
Values(2, 1, 'to-delete')
Insert into TestTable(Id, SerialNo, Notes)
Values(2, 2, 'to update')


Insert into @Tbl(SerialNo, Notes)
values(3, 'to insert')

Insert into @Tbl(SerialNo, Notes)
values(2, ' updated value')

select * from TestTable
Declare @Id Int = 2

Merge TestTable as Target
Using @Tbl as Source
On Target.Id = @Id And Target.SerialNo = Source.SerialNo
When Matched Then Update Set Target.Notes = Source.Notes
When Not Matched By Target Then Insert(Id, SerialNo, Notes)
Values(@Id, SerialNo, Notes)
When Not Matched By Source And Target.Id = @Id Then Delete
;

-- all items with id 1 must be present
select * from TestTable
rollback



Wednesday, July 20, 2011

My research articles.

This post consists of articles which I will have to research later. If any one has any interesting things you can mention in the comments.

Simulate windows service in asp.net
http://www.codeproject.com/Articles/12117/Simulate-a-Windows-Service-using-ASP-NET-to-run-sc

.net image resizing
http://www.hanselman.com/blog/NuGetPackageOfWeek11ImageResizerEnablesCleanClearImageResizingInASPNET.aspx
Sql server bulk loading
http://msdn.microsoft.com/en-us/library/dd425070(v=sql.100).aspx
Service broker
http://blogs.msdn.com/b/sql_service_broker/archive/2008/06/26/service-broker-periodic-tasks.aspx
SSRS
http://beyondrelational.com/blogs/viral/archive/2010/07/09/generating-ssrs-reports-programatically.aspx
Sql server optimisation
http://tonesdotnetblog.wordpress.com/2008/05/26/twelve-tips-for-optimising-sql-server-2005-queries/
Asp.net mvc
http://fzysqr.com/2010/04/26/asp-net-mvc2-plugin-architecture-tutorial/
http://www.sharparchitecture.net/
http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx
http://www.chrisvandesteeg.nl/2010/11/22/embedding-pre-compiled-razor-views-in-your-dll/
Visual Studio Modelling
http://www.olegsych.com/2010/01/uml-modeling-and-code-generation-in-visual-studio-2010/
Sql Server
CTE
http://msdn.microsoft.com/en-us/library/ms186243.aspx
Visual studio Guidance
http://mikehadlow.blogspot.com/2006/09/how-to-create-guidance-package.html
Todo:
Install ios on win 7
http://ipodtoucher55.blogspot.com/2010/12/installing-ios-sdk-and-xcode-on-windows.html
Javascript library
http://raphaeljs.com/ vector/diagramming javascript
Other:
tortuga.dll

http://oauth.net/code/
https://code.google.com/apis/
http://code.google.com/apis/blogger/docs/2.0/reference.html
http://code.google.com/apis/blogger/docs/2.0/developers_guide_dotnet.html#CreatingAccount

http://www.programmableweb.com/api/blogger/mashups

HARDWARE:
http://www.pikesoft.com/blog/index.php?itemid=124
Email:
http://www.diaryofaninja.com/blog/2011/09/27/what-all-good-web-developers-should-know-about-sending-email?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+DiaryOfANinja+%28Diary+of+a+Ninja%29
http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html
sql server
http://www.sqlteam.com/article/using-ddl-triggers-in-sql-server-2005-to-capture-schema-changes
API
http://developer.yahoo.com/travel/
http://developer.bookingmarkets.com/member/register
Use windows live writer to edit our site data
http://www.keyvan.ms/implement-metaweblog-api-in-asp-net
http://www.xml-rpc.net/
http://www.xmlrpc.com/metaWeblogApi
http://www.hanselman.com/blog/TheWeeklySourceCode22CAndVBNETLibrariesToDiggFlickrFacebookYouTubeTwitterLiveServicesGoogleAndOtherWeb20APIs.aspx
ACTS
http://business.ftc.gov/documents/bus61-can-spam-act-compliance-guide-business
Serial Port
http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx

Jquery–good articles

http://youhack.me/2010/04/22/live-character-count-with-progress-bar-using-jquery/

http://youhack.me/2011/07/15/google-plus-photo-stack-animation-using-jquery-and-css3/

Sunday, May 1, 2011

Website not working without www in parallel plesk.

Recently our website www.syneity.com came across a minor glitch. We could access our website with www but not without it.

image image
url : www.syneity.com url : syneity.com

To fix this i explored through the parallel plesk dashboard and got the solution.

  1. Visited the Domains link on the left navigation bar.
  2. Selected the checkbox against syneity.com and the clicked the modify button
  3. In the resulting page, scrolled down towards Preferences
  4. Then selected the check box against switch on for www prefix
  5. image

 

 

And bingo syneity could be accessed using both the links..

Friday, April 22, 2011

Pivot to Convert Rows into Columns

 

pivot-sql-server


I need to convert the table as show in the figure above to the one on the right hand side. Using Sql servers Pivot we can easily get this done. Please see the script below:

Thursday, April 7, 2011

Get all descendants of a parent using CTE

 

Declare @TblLocations Table(Id Int, Name Varchar(50), ParentId Int)
Insert into @TblLocations(Id, Name, ParentId)
Values(1, 'India', Null)
Insert into @TblLocations(Id, Name, ParentId)
Values(2, 'Kerala', 1)
Insert into @TblLocations(Id, Name, ParentId)
Values(3, 'Tamil Nadu', 1)
Insert into @TblLocations(Id, Name, ParentId)
Values(4, 'Kochi', 2)
Insert into @TblLocations(Id, Name, ParentId)
Values(5, 'Chennai', 3)


;With Locations As
(
Select * From @TblLocations
Where ParentId = 3
Union All

Select Child.* from @TblLocations Child Inner join Locations Parent on Child.ParentId = Parent.Id
)
Select * from Locations

Friday, March 25, 2011

Create a simple Restful WCF Service in Azure

Our target:

We will be creating a WCF Service in azure which will have rest based urls. The functionality of this wcf service along with rest based urls are:

Functionality Rest based URL HTTP Verb
View all Movies movies/now-playing GET

Coding the WCF Service:

Wednesday, March 23, 2011

Learning Windows Azure

I will be learning windows azure in the next few days and I will be documenting the same in this blog.

I will be learning Azure by building a sample application. The application requirement:

“The application will allow users to register / login using facebook /google/ live Ids. Registered users will be able to view movies, They will also be able to add movies, for each added movie they will get a credit. The users will be able to view the credit balance.”

Sunday, March 6, 2011

Configuring dotnetpanel for google apps email

I recently had to configure google apps email for dotnetpanel, the following link was helpful for me in that regard. Special thanks to Shai Ben-Naphtali

Link:

http://blog.arvixe.com/dnp-dotnetpanel-setup-google-apps-mx-cname-and-spf-records/

Sunday, February 20, 2011

Building dynamic html with Jquery

While reviewing the jquery code for a project developed at syneity. I came across the following javascript where dynamic html was handcoded and then applied to a table, we had encountered several such situations and it was a buggy experience. This blog details the refactoring i made to the same.

The problem:

image


 

Thursday, February 10, 2011

A MVC “Add View” like Visual Studio Wizard.

Any one who has used asp.net mvc will have be entranced by the “Add View” and “Add Controller” features. This is implemented using Visual Studio Wizards, today we will look into how we can implement such a wizard. We will be using this wizard at SyneITY for our development process.

What will this wizard do?

Wednesday, February 9, 2011

Executing a T4 Template from the command line

A T4 Template is normally added to a project and this gets executed whenever the user adds the template to the project / whenever a user saves the text template. Now i had a requirement when i needed to execute the T4 template programmatically. I had the following options:

Options to execute a T4 text template programmatically:

  • Implement the ITextTemplating interface.
  • Use the TextTransform command line utility.

Monday, February 7, 2011

Refactoring the code out of the T4 template

T4 templates have been a great way to generate code in visual studio, and at SyneITY we use code generation where developers find themselves repeating things. T4 has helped us achieve much better productivity. Also special thanks to Tangible for their Syntax Highlighting without which T4 wouldn’t have been a piece of cake.

The Reason for Refactoring:

Sunday, February 6, 2011

Implement paging with CTE and Row_Number in Sql Server.

We needed to implement paging and this is how we at SyneITY went about it. Since we were using Sql Server 2008 we decided to go for using the Row_Number() function along with CTE (Common Table Expression).

Procedure

Tuesday, January 11, 2011

Installing a dll in the global assembly cache - GAC


Where do we find the Global Assembly cache?
Your windows installation directory / Windows/Assembly  which can also be accessed through
%SystemRoot%/assembly
Steps to install an assembly into the GAC: