13
Apr

Visual Studio 2010 finally released

   Posted by: Rasik Jain   in Programming, Technology

The Visual Studio 2010 IDE has been redesigned which, according to Microsoft, clears the UI organization and “reduces clutter and complexity.” The new IDE better supports multiple document windows and floating tool windows,[70] while offering better multi-monitor support. The IDE shell has been rewritten using the Windows Presentation Foundation (WPF),[71] whereas the internals have been redesigned using Managed Extensibility Framework (MEF) that offers more extensibility points than previous versions of the IDE that enabled add-ins to modify the behavior of the IDE.

Visual Studio 2010 comes with .NET Framework 4 and includes F#, a functional programming language originally developed at Microsoft Research.

Please find more details at Microsoft Visual Studio 2010 page.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: , ,

6
Nov

Convert XML to CSV using LINQ to XML

   Posted by: Rasik Jain   in C# (C-Sharp), Programming, XML

This post will show you how to convert an XML file to CSV using Linq to XML and Anonymous types of C# 3.0. LINQ to XML is an lightweight in-memory XML programming API by which a user can manipulate the XML data such as

  • Reading from XML file
  • Writing to XML file
  • Add or Remove XML elements from XML tree.

Now lets dig into the code sample.

Following is the code snippet which helps in converting the XML file into CSV Format.

// Loading from a file, you can also load from a stream
XDocument loaded = XDocument.Load(@"C:\Contacts.xml");
 
// create a writer and open the file
TextWriter tw = new StreamWriter("c:\\XmltoCSV.txt");
 
// Query the data and write out a subset of contacts
var contacts = from c in loaded.Descendants("CONTACT")
		select new
		{
			FirstName = (string)c.Element("FIRSTNAME"),
			LastName = (string)c.Element("LASTNAME"),
			City = (string)c.Element("CITY"),
			State = (string)c.Element("STATE"),
			Country = (string)c.Element("COUNTRY")
		};
 
foreach (var contact in contacts)
{
	string s = contact.FirstName + "," +
				contact.LastName+ "," +
				contact.City+ "," +
				contact.State + "," +
				contact.Country;
 
	// write a line of text to the file
	tw.WriteLine(s);
}
 
// close the stream
tw.Close();

INPUT (XML File): We will use the XML file to read the data.

<?xml version='1.0' encoding='utf-8'?>
<CONTACTS>
	<CONTACT>
		<FIRSTNAME>John</FIRSTNAME>
		<LASTNAME>Doe</LASTNAME>	
		<CITY>Miami</CITY>
		<STATE>Florida</STATE>
		<COUNTRY>USA</COUNTRY>
	</CONTACT>
	<CONTACT>
		<FIRSTNAME>Shane</FIRSTNAME>
		<LASTNAME>Warne</LASTNAME>	
		<CITY>Sydney</CITY>
		<STATE>New South Wales</STATE>
		<COUNTRY>Australia</COUNTRY>
	</CONTACT>
	<CONTACT>
		<FIRSTNAME>Adam</FIRSTNAME>
		<LASTNAME>Smith</LASTNAME>	
		<CITY>London</CITY>
		<STATE>London</STATE>
		<COUNTRY>UK</COUNTRY>
	</CONTACT>
</CONTACTS>

OUTPUT (CSV file): Comma Separated File (CSV) will be generated as the output.

John,Doe,Miami,Florida,USA
Shane,Warne,Sydney,New South Wales,Australia
Adam,Smith,London,London,UK
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: , , ,

With every new version of SQL server, Microsoft is adding new and exciting features for database encryption. In SQL Server 2008, Microsoft has introduced a new encryption technique called Transparent Data Encryption (TDE). With TDE, Encryption is performed on the database with real time I/O operations. The performance of encryption and decryption is better when compared to SQL Server 2005.

Transparent Data Encryption (TDE) uses database encryption symmetric key (DEK) for the purpose of encryption and decryption. DEK is stored in master databased secured by certificate or asymmetric key. TDE provides the ability to encrypt the data at root levels meaning data and log files. This way users can encrypt the data without modifying the design of existing applications. TDE does not affect the size of the database. Size of the database remains same with or without TDE encryption. for TDE enabled database, backup files are also encrypted using DEK. So, during the restore process, certificate protecting database must be available. Care must be taken to backup server certificates on regular basis.

Following are the important steps in configuring the Transparent Data Encryption (TDE).

  1. Create a Master Key
  2. Generate a certificateprotected by master key.
  3. Create a database encryption key (DEK) protected by certificate.
  4. Enable the TDE encryption for selected database.

Here is an example for enabling the encryption on database Northwind using a certificate named MySQLCertificate.

USE Master;
GO
 
--Create Master Key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Password1';
GO
 
--Create Certificate
CREATE CERTIFICATE MySQLServerCertificate WITH SUBJECT = 'My SQL Server Certificate'
GO
 
USE Northwind
GO
 
--Create Database Encryption Key (DEK)
CREATE DATABASE ENCRYPTION KEY
WITH ALGORITHM = TRIPLE_DES
ENCRYPTION BY SERVER CERTIFICATE MySQLServerCertificate
GO
 
-- Enable the TDE Encryption for the database
ALTER DATABASE Northwind
SET ENCRYPTION ON
GO
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: , , ,

3
Jun

Securing Session Cookies or ID’s over Network

   Posted by: Rasik Jain   in Programming

Following are some of the security practices for secure transmission of session cookies between web server and client.

  • If its a commercial website, then install SSL for secure communication.
  • Generate unpredictable Random characters for the sessionID value.
  • Avoid incremental or time based session cookie values.
  • Issue or generate session cookie after successful authentication only.
  • Never generate cookies as Persistent cookies on the users hard disk.
  • Set the “SECURE” flag for the session cookie which means cookies will be transmitted over SSL only.
  • Set the Path and Domain of session cookies.
  • Never store or pass session information in URL and Hidden Fields.
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: , , ,

10
May

Secure Database against SQL Injection attacks

   Posted by: Rasik Jain   in Database

Following are some of the recommendations to protect the application against SQL injection attacks. These recommendations are very generic in nature and independent of database platform so they can be applied to any database such as SQL Server 2000/2005, Oracle, MySQL or DB2

Sanitization Input:Protecting SQL queries by implementing sanitization techniques for all input received from any ASP.NET request object. Check all the input sources such as Request.Cookies, Form Variables, Query String parameters, Request.ServerVariables etc. Sanitization routines will vary based on your DBMS.

Avoid disclosing database error information. In the event of database errors, make sure you do not disclose detailed error messages to the user. Never display debug or detailed information to the user containing SQL queries.

Check SQL meta-characters (single-quote(‘), semi-colon(;) or double-dash(–), or multi-line comments (/* */) etc) and command keywords (Select, Union, Delete, Drop, etc) from the input. Always check and filter these keywords in the input fields. Always perform these checks on server-side. Do not rely on client-side validation alone.

Escape/Quotesafe the input, such as by replacing all single quotes with two single quotes.

Constrain and sanitize input data. Check for known good data by validating for type, length, format, and range. Validation should be done on both server side and client side.

Remove unused extended stored procedures, like xp_cmdshell and xp_grantlogin, and other user-defined functions.

Limit the permissions granted to the database user account used by the Web application. Most of the cases, only “EXEC” permission is required for stored procs. Remove DBO privileges to the application account.

Avoid Dynamic Queries: Always use stored procedures to communicate with database. Avoid using dynamic queries or SQL statements embedded in the program code.

Use type-safe SQL parameters for data access. You can use these parameters with stored procedures or dynamically constructed SQL command strings. Parameter collections such as SqlParameterCollection provide type checking and length validation. If you use a parameters collection, input is treated as a literal value, and SQL Server does not treat it as executable code. An additional benefit of using a parameters collection is that you can enforce type and length checks. Values outside of the range trigger an exception.

Following is a sample VB.NET routine which will check for invalid characters in the data input.

 
Public Function TestForSQLInjection(ByVal psSQL As String) As String
 
	Dim rexSql As Regex = New Regex("/exec(\s|\+)+(s|x)p\w+/ix")
 
	Dim rexSql2 As Regex = New Regex("(\-\-)")
 
	If Not rexSql.Match(psSQL).Success And Not rexSql2.Match(psSQL).Success Then
 
		Return psSQL
 
	End If
 
Throw New Exception("SQL Injection attack possible with:" & psSQL)
 
End Function
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: ,

6
May

.NET (C# or VB.Net) libraries for Twitter API

   Posted by: Rasik Jain   in C# (C-Sharp)

I was looking for Twitter APIs or Wrapper classes which are built using .NET languages like C# or VB.NET. I have found some very good .NET libraries which are worth checking out them. If you are a .NET developer you can plugin these API libraries directly into your ASP.NET or Windows application without having to re-write everything from scratch in order to interact with twitter.

I have explored following APIs.

TweetSharp API

TweetSharp API is built using the .NET framework 3.0/3.5. It uses most of new features of C# like Linq, Implicit Variables, Extension Methods etc. TweetSharp can be used with silver light. Find more details about TweetSharp at Google Code – TweetSharp

You can interact with twitter as shown the below.

var twitter = FluentTwitter.CreateRequest()
    .AuthenticateAs("UserName", "Password")
    .Statuses().Update("Hello World")
    .AsJson();
 
var response = twitter.Request();

Twitterizer

Twitterizer is another .NET library which is promising. Already there are applications built using twitterizer. This Library provides simple to use functions and returns the user objects in the form of Collection Objects. Find more details at Google Code – Twitterizer

You can interact with twitter as shown the below.

Twitter tw = new Twitter("UserName", "Password");
 
tw.Status.Update("Hello World");

Yedda Lib

Yedda Lib is built using .NET 2.0 and C#. This is a simple and yet power library to use. When I checked this library last time there was no support for Direct Messages functionality. You can check more details at Yedda

Twitter tw = new Twitter();
 
//Using String object
String jsonFriends = tw.GetFriendsAsJSON("UserName", "Password");
 
//Using XML Object
XmlDocument xmlFriends = tw.GetFriendsAsXML("UserName", "Password");

TwitterVB

TwitterVB is a VB.NET library released as open source under Google Code. TwitterVB includes a working implementation of Twitter’s OAuth authentication system, as well as Basic Authentication. Find more details about TwitterVB at Google Code – TwitterVB

Dim tw As New TwitterVB.Twitter
tw = New TwitterVB.Twitter
tw.AuthenticateAs("UserName", "Password")
 
' Post the tweet to Twitter
tw.StatusMethods.Update(Me.txtPost.Text)
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: , , , ,

4
May

Check database size on SQL Server using Excel Macro

   Posted by: Rasik Jain   in Programming

Following is a script to check the size of each database in a server. It checks the Database size, DBFile size and Log file size. Below code loops through all the databases on the selected server and exports the information to the Excel sheet.

 
'Declare Variables for Server name, Database, DB File, Log File etc
Dim vServerName
Dim objServer
Dim objDatabase
Dim objDBFile
Dim objLogFile
Dim xlApp
Dim xlBook
Dim xlSheet
Dim Row
Dim Cell
 
' Messagebox for server name
vServerName = InputBox("Please Enter Server Name:","Server Name","(local)")
If vServerName = "" Then
vServerName = "(local)"
End If
 
'Create Excel Object
Set xlApp = CreateObject("Excel.Application")
 
'Add Workbook to Excel Obj
Set xlBook = xlApp.Workbooks.Add
 
'Add Sheet to WorkBook
Set xlSheet = xlBook.Worksheets.Add
 
'Make Visibility for Excel App
xlSheet.Application.Visible = True
 
' Set column headers
xlSheet.Cells(1, 1) = "Database Name"
xlSheet.Cells(1, 2) = "Space used (MB)"
xlSheet.Cells(1, 3) = "Space Available (MB)"
xlSheet.Cells(1, 4) = "DBFile (MB)"
xlSheet.Cells(1, 5) = "LogFile (MB)"
Row = 2
 
xlSheet.Rows("1:1").Font.Bold = True
xlSheet.Range("B:E").HorizontalAlignment = -4152
 
' Create the server object using SQL-DMO
Set objServer = CreateObject("SQLDMO.SQLServer2")
 
'Set Authentication for Server
' Login with current Windows account
objServer.LoginSecure = True
objServer.Connect vServerName
 
 
'Loop through all the databases and get the properties of databases
For each objDatabase in objServer.Databases
 
SET objDBFile = objDatabase.Filegroups("PRIMARY").DBFiles(1)
SET objLogFile = objDatabase.TransactionLog.LogFiles(1)
xlSheet.Cells(Row, 1).Value = objDatabase.Name
xlSheet.Cells(Row, 2).Value = objDatabase.Size
xlSheet.Cells(Row, 3).Value = Round(objDatabase.SpaceAvailableInMB,3)
xlSheet.Cells(Row, 4).Value = objDBFile.size
xlSheet.Cells(Row, 5).Value = objLogFile.size
 
Row = Row + 1
Set objDBFile = Nothing
Set objLogFile = Nothing
Next
 
xlSheet.Cells.EntireColumn.AutoFit
 
 
'Save our changes
xlBook.SaveAs ("C:\DBSpaceUsage.xls")
xlBook.Close
 
MsgBox "Check the file at C:\DBSpaceUsage.xls"
 
' Clean up memory
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
set objDatabase = Nothing
Set objServer = Nothing
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: , ,

4
May

Check File exists using .NET framework (VB.NET)

   Posted by: Rasik Jain   in VB.Net

Check If File Exists using VB.Net

FileInfo is a object derived from System.IO name space.

FileInfo has a property called “Exists”. This propery returns true if the file exists. False if file does not exists.

 
=========(VB.NET)===============
Imports System.IO
 
Declare Dim testfile As New FileInfo("c:\My Document\testfile.txt")
 
If testfile.Exists() Then
return true
Else
return false
End If
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Reddit
  • HackerNews
  • Slashdot
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • Tumblr
  • Share/Bookmark

Tags: