window.print not working in firefox

Recently I was implementing a functionality where we upload a file to server, retrieve its data then show summary based on it. I was showing this summary in a panel with a print button. This print button uses JavaScript function window.print () to print the summary report from the contents of the panel. Here is the function that I was using –

function CallPrint() {
    var prtContent = document.getElementById('<%= pnlSummary.ClientID %>');
    var winPrint = window.open('', '', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
    winPrint.document.write("<h3>Summary</h3>" + prtContent.innerHTML);
    winPrint.document.close();
    winPrint.focus();
    winPrint.print();
    winPrint.close();
}

Everything was working fine until it came to Firefox. In Firefox the print dialog was not getting opened in the new window. To resolve this I changed the calling mechanism of the print function, I added a new page to project solution Print.aspx. Instead of opening a new window without any URL, I opened this page in the window and accessed the contents of the pnlSummary from the opened window via window.opener object –

function CallPrint() {
    var winPrint = window.open('Print.aspx', '', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
}

On Print.aspx page I used this function –

function Print() {
    var prtContent = "<h3>Summary</h3>" + window.opener.document.getElementById('ctl00_cphContent_pnlSummary').innerHTML;
    document.getElementById("printDiv").innerHTML = prtContent;
    window.print();
    window.opener.focus();
    window.close();
}

and called it on body onload.

<body onload="Print();">
    <form id="form1" runat="server">
    <div id="printDiv">
    </div>
    </form>
</body>
Posted in Technology | Tagged , , | 5 Comments

Podcasts to follow for .NET developers

These are some of the podcasts that a .NET developer should follow –

  • Stackoverflow – A programming community exploit
  • HerdingCode – A Weekly podcast with K. Scott Allen, Kevin Dente, Scott Koon, and Jon Galloway.
  • Hanselminutes – Weekly audio show with web developer and technologist Scott Hanselman and hosted by Carl Franklin
  • CodeCast – The late night show for .NET developers
  • .NET Rocks! – The internet audio talk show for .NET developers
  • The ASP.NET Podcast – A Podcast by Wallace B. McClure, David Penton, and Paul Glavich
  • .Net Preacher Show – The Dot Net Preacher is about preaching the good word of .NET to the uneducated heathen masses and bringing them into the light of .NET to save their souls from the mortal dangers of PHP, J2EE, Ruby, Python and other false idols.
  • Channel9 – Channel9 podcast
  • Microsoft Podcasts – Microsoft Podcasts for Developers
  • Polymorphic Podcast – Craig Shoemaker’s periodic exploration of software and best practices for .NET developers
Posted in Technology | Tagged , | Leave a comment

“is not a valid name” error while retrieving data from csv file using oledb

is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.”

I encountered this error about two days back when I was retrieving data from a file with long name, I was not sure what was the cause of the problem so posted this as a question on stackoverflow. As the response was low, I tried to search the solution on my own but I didn’t exactly found what the problem was but it was clear that long file name was creating problem so here is what I did

ConnString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " & System.IO.Path.GetDirectoryName(strFileName) & "; Extended Properties = ""Text;HDR=YES;FMT=Delimited"""

'==========OleDB Supports fixed length file name.===========
Dim OldFileName As String = System.IO.Path.GetFileName(strFileName)
Dim NewFileName As String = Guid.NewGuid().ToString().Substring(0, 10) + System.IO.Path.GetExtension(OldFileName)
Dim rootPath As String = System.IO.Path.GetDirectoryName(strFileName) + "/"

'Rename file name
My.Computer.FileSystem.RenameFile(rootPath + OldFileName, NewFileName)
strFileName = rootPath + NewFileName
'===========================================================

Dim strQuery As String
strQuery = "SELECT * FROM [" & System.IO.Path.GetFileName(strFileName) & "]"

'Revert rename file name
'===========================================================
My.Computer.FileSystem.RenameFile(rootPath + NewFileName, OldFileName)
strFileName = rootPath + OldFileName
'===========================================================

I just renamed the file with a new Guid while I am retrieving the data after renamed it back to original file name. This is not exactly what I wanted. Please comment if a better solution is there.

Posted in Technology | Tagged , , , | Leave a comment

Generating pivot table dynamically

--Create Subjects table
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Subjects]') AND type in (N'U'))
DROP TABLE [dbo].[Subjects]
GO
CREATE TABLE [dbo].[Subjects](
	[pkey] [int] IDENTITY(1,1) NOT NULL,
	[Subject] [varchar](50) NULL,
	[Day] [int] NULL,
 CONSTRAINT [PK_Subjects] PRIMARY KEY CLUSTERED
(
	[pkey] 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

--Create Days table
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Days]') AND type in (N'U'))
DROP TABLE [dbo].[Days]
GO
CREATE TABLE [dbo].[Days](
	[pkey] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NULL,
 CONSTRAINT [PK_Days] PRIMARY KEY CLUSTERED
(
	[pkey] 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

--Insert values into Subjects table
INSERT INTO Subjects(Subject,Day) VALUES('Litrature',1)
GO
INSERT INTO Subjects(Subject,Day) VALUES('History',3)
GO
INSERT INTO Subjects(Subject,Day) VALUES('Geography',5)
GO
INSERT INTO Subjects(Subject,Day) VALUES('Mathematics',2)
GO

--Insert values into Days table
INSERT INTO Days(Name) VALUES('Monday')
GO
INSERT INTO Days(Name) VALUES('Tuesday')
GO
INSERT INTO Days(Name) VALUES('Wednesday')
GO
INSERT INTO Days(Name) VALUES('Thursday')
GO
INSERT INTO Days(Name) VALUES('Friday')
GO
INSERT INTO Days(Name) VALUES('Saturday')
GO
INSERT INTO Days(Name) VALUES('Sunday')
GO

--Dynamically generate Pivot table
DECLARE @cols NVARCHAR(2000)
 SELECT  @cols = STUFF((  SELECT  TOP 100 PERCENT
         ', ' + cast(t1.subject AS NVARCHAR)
       FROM    Subjects AS t1
       FOR XML PATH('')
        ), 1, 2, '') + ''

 DECLARE @query NVARCHAR(4000)
 SET @query = N'SELECT Name,pkey, '+
 @cols +'
 FROM
 (SELECT t2.Name, t1.Subject,t2.pkey, 1 AS [access] FROM Days AS t2 LEFT JOIN Subjects AS t1 ON t2.PKey = t1.Day) p
 PIVOT
 (
 Sum([access])
 FOR subject IN
 ( '+
 @cols +' )
 ) AS pvt;'

EXEC(@query)

In the above query there are two tables Subjects and Days, one contains entries for subjects and other for holding days of week

The generated pivot tables is like a time table which contains value 1 for the day where lecture of subjects is there otherwise NULL. This is rather a simple query more complex pivot table are constructed as per requirements. Pivot tables are quite useful in showing data in more user-friendly way.

Posted in Technology | Tagged , , | Leave a comment

Drop all the constraints on a table

Following sql snippet illustrates an example of dropping all the constraints on a table. This stored procedure takes table name as parameter and dynamically creates a drop script for all the constraints of given table and executes it. Earliar today I was searching scripts concerning the same but I mostly found scripts related to information schema of the database. As a small developer I thought it was risky to put a hand on that. I was able to create this simple script which just involves a cursor on sysobjects table.

CREATE PROCEDURE DeleteConstraints
@tableName VARCHAR(100)
AS
BEGIN

DECLARE @sql VARCHAR(max)
DECLARE @conName VARCHAR(100)
DECLARE @con CURSOR

SET @con = CURSOR FOR SELECT name FROM sysobjects WHERE parent_obj=(SELECT id FROM sysobjects WHERE name=@tableName) AND type IN ('C','D','F','K')

OPEN @con
FETCH NEXT
FROM @con INTO @conName
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @sql = 'IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N''[' + @conName + ']'') AND type IN (''C'',''D'',''F'',''K'')
BEGIN
	ALTER TABLE [dbo].[' + @tableName  + '] DROP CONSTRAINT [' + @conName + ']
END'
	EXEC(@sql)

FETCH NEXT
FROM @con INTO @conName
END
CLOSE @con
DEALLOCATE @con

END
GO
Posted in Technology | Tagged , , , , | Leave a comment

Get DataTable from CSV without OleDb

I have been pretty busy for last 4 months. It has been months since I blogged last time but now as time is easing I’ll try my hands on various thing that have came out of Microsoft garage recently and try to blog about that.

Speaking of Microsoft, recently I got to know a limitation with Microsoft’s oledb Jet engine. In last few days I was engaged with some import utilities for my project, it basically consisted of saving values of a CSV file in various tables. Everything I did was working fine until it reached on production servers, the file contents were not getting imported to the tables, I was not clear about what the problem was, as I hadn’t logged any exception that may come in, at first I thought there is some permission issue in folder to which I am uploading the files; After some time when problem was not getting rectified I started logging the exceptions.

The exception I was getting on production was “The ‘Microsoft.Jet.OleDb.4.0’ provider is not registered on the local machine“, the problem was I used to Jet.OleDb to parse CSV file to get DataTable from which my import method was going to work. The production environment was 64-bit Windows Server 2008 and there is no 64-bit version of Jet is available at the moment. That meant I had to write my own method of parsing a CSV, one way was to use string.split but that’s a problem when you have your delimiter in your values. To avoid writing my own method I searched on the internet for quite some time but I didn’t get what I wanted.

I got some help through Jouni Heikniemi’s CsvReader but that used to give values of CSV for line I modified that to write my own class. As it took my lot time search for the solution and still not getting exactly what I wanted, I am sharing this class (CSVHandler.vb). It converts values of a CSV file into a DataTable preserving values having commas in between.

Download CSVHandler.vb

Download CSVHandler.cs

Posted in Technology | Tagged , , , , , | 2 Comments

Shirdi Visit

Trip to Shirdi A trip to remember with friends. We went to Shirdi, place of Sai Baba; The journey was fun, we enjoyed it thoroughly also with this visit I’hv spiritually revived my self.

View Shirdi Album

Posted in Personal | Tagged | Leave a comment