Monday, March 22, 2010

Convert PDF to JPEG

GhostScript GPL/AFPL

From command line it will go like this:

gswin32c.exe -q -dBATCH -dMaxBitmap=300000000 -dNOPAUSE -dSAFER -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dFirstPage=1 -dLastPage=1 -sOutputFile="C:\test.jpg" "C:\test.pdf" -c quit

Tuesday, March 16, 2010

Transform xml with xsl

using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;

namespace Microsoft.Samples.Xml
{
public class TransformXMLSample
{
private const string document1 = @"..\..\books.xml";
private const string document2 = @"..\..\ProcessParametersA.xml";
private const string document3 = @"..\..\ProcessParametersB.xml";
private const string styleSheet1 = @"..\..\books.xsl";
private const string styleSheet2 = @"..\..\StyleSheetGenerator.xsl";
private const string output1 = @"..\..\table.html";
private const string output2 = @"..\..\transform2.xsl"; //linked by books-t2.xml
private const string output3 = @"..\..\transform3.xsl"; //linked by books-t3.xml
/**
add to books.xml to view transform using transform2.xsl
add to books.xml to view transform using transform3.xsl
**/

public static void Main()
{
TransformXMLSample transformXMLSample = new TransformXMLSample();
Console.WriteLine("\n\n*********Output from the first transform:*********\n\n");
String[] args1 = {document1, styleSheet1,output1};
transformXMLSample.Run(args1);

Console.WriteLine("\n\n*********Output from the second transform:*********\n\n");
String[] args2 = {document2, styleSheet2,output2};
transformXMLSample.Run(args2);

Console.WriteLine("\n\n*********Output from the third transform:*********\n\n");
String[] args3 = {document3, styleSheet2,output3};
transformXMLSample.Run(args3);
Console.Write("Press Enter to Exit");
Console.ReadLine();
}

public void Run(String[] args)
{
Console.WriteLine();
Console.WriteLine("Read XML data file, transform and format display ...");
Console.WriteLine();

ReadTransform(args);

Console.WriteLine();
Console.WriteLine("Read XML data file, transform and write ...");
Console.WriteLine();

ReadTransformWrite(args);
Console.WriteLine();
}

public void ReadTransform(String[] args)
{
XslCompiledTransform processor = new XslCompiledTransform();
processor.Load(args[1]);
//Transform the file.
processor.Transform(args[0], null, Console.Out);
}

public void ReadTransformWrite(String[] args)

{
using (FileStream stream = File.Open(args[2], FileMode.Create))
{
//Create XsltCommand and compile stylesheet.
XslCompiledTransform processor = new XslCompiledTransform();
processor.Load(args[1]);
//Transform the file.
processor.Transform(args[0], null, stream);
}
}
}
}

Validate xml with xml Schema

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Microsoft.Samples.Xml
{
class XmlSchemaValidatorSample
{
static string document = @"..\..\books.xml";
static string xsdDocument = @"..\..\books.xsd";

public static void Main(){
XmlSchemaInfo schemaInfo = new XmlSchemaInfo();
XmlSerializer serializer = null;
Books myBooks = null;

using (TextReader reader = new StreamReader(document))
{
serializer = new XmlSerializer(typeof(Books));
myBooks = (Books)serializer.Deserialize(reader);
}

XmlSchemaValidator xsv = CreateValidator();
xsv.Initialize();

xsv.ValidateElement("books", "http://www.example.com/my-bookshelf",
schemaInfo);

xsv.ValidateEndOfAttributes(schemaInfo);

foreach (BookType book in myBooks.book)
{
xsv.ValidateElement("book", "http://www.example.com/my-bookshelf",
schemaInfo);

if (book.publisher != null)
{
xsv.ValidateAttribute("publisher", string.Empty, book.publisher, schemaInfo);
}

if (book.onloan != null)
{
xsv.ValidateAttribute("on-loan", string.Empty, book.onloan, schemaInfo);
}

xsv.ValidateEndOfAttributes(schemaInfo);
xsv.ValidateElement("title", "http://www.example.com/my-bookshelf", schemaInfo);
xsv.ValidateEndElement(null, book.title);
xsv.ValidateElement("author", "http://www.example.com/my-bookshelf", schemaInfo);
xsv.ValidateEndElement(null, book.author);
xsv.ValidateElement("publication-date", "http://www.example.com/my-bookshelf", schemaInfo);
xsv.ValidateEndElement(null, book.publicationdate);
xsv.ValidateEndElement(schemaInfo);
}

xsv.ValidateEndElement(schemaInfo);
xsv.EndValidation();
Console.WriteLine("Schema validated.");
Console.WriteLine();
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}

static XmlSchemaValidator CreateValidator()
{
NameTable nt = new NameTable();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("http://www.example.com/my-bookshelf", xsdDocument);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
XmlSchemaValidationFlags flags = XmlSchemaValidationFlags.None;
return new XmlSchemaValidator(nt, schemaSet, nsmgr, flags);
}

}

Convert String to XML - .NET/C#

If you have a valid string in "str", you can use XmlDocument to load the string and then save string to an XML file using Save method of XmlDocument. Don't forget to import System.Xml namespace before using XmlDocument.

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
doc.Save("SSML.xml");

Reading and writing XML with c#

In this article, you will see how to read and write XML documents in Microsoft .NET using C# language.

First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa.

Introduction to Microsoft .NET XML Namespaces and Classes

Before start working with XML document in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library.
.NET provides five namespace
- System.Xml,
- System.Xml.Schema-
- System.Xml.Serialization
- System.Xml.XPath
- System.Xml.Xsl
to support XML classes.

The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes.

The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example.

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas.

The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example.

The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects.

In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList.

Next namespace in Xml series is System.Xml.Schema. It classes to work with XML schemas such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType.

The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams.

The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation though XML documents. This class contains many Move methods to move through a document.

The System.Xml.Xsl namespace contains classes to work with XSL/T transformations.

Reading XML Documents

In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line:

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

Or you can use any XML file.

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor.

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber an so on.

List 1 reads a document and displays a node information using these properties.

About Sample Example 1

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output.

Sample Example 1.


using System;
using System.Xml;
namespace ReadXml1
{
class Class1

static void Main(string[] args)
{
//Create an instance of XmlTextReader and call Read method to read the file

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
textReader.Read();
// If the node has value
while (textReader.Read())
{
// Move to fist element
textReader.MoveToElement();
Console.WriteLine("XmlTextReader Properties Test");
Console.WriteLine("===================");
Console.WriteLine("Name:" + textReader.Name);
Console.WriteLine("Base URI:" + textReader.BaseURI);
Console.WriteLine("Local Name:" + textReader.LocalName);
Console.WriteLine("Attribute Count:" +
textReader.AttributeCount.ToString());
Console.WriteLine("Depth:" + textReader.Depth.ToString());
Console.WriteLine("Line Number:" +
textReader.LineNumber.ToString());
Console.WriteLine("Node Type:" +
textReader.NodeType.ToString());
Console.WriteLine("Attribute Count:" +
textReader.Value.ToString());

}

}

}

}




The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on.

List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has.

About Sample Example 2

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document.

Sample Example 2.


using System;
using System.Xml;
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
int ws = 0;
int pi = 0;
int dc = 0;
int cc = 0;
int ac = 0;
int et = 0;
int el = 0;
int xd = 0;
// Read a document
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
// Read until end of file
while (textReader.Read())
{
XmlNodeType nType = textReader.NodeType;
// If node type us a declaration
if (nType == XmlNodeType.XmlDeclaration)
{

Console.WriteLine("Declaration:" + textReader.Name.ToString());
xd = xd + 1;
}
// if node type is a comment
if (nType == XmlNodeType.Comment)
{
Console.WriteLine("Comment:" + textReader.Name.ToString());
cc = cc + 1;
}
// if node type us an attribute
if (nType == XmlNodeType.Attribute)
{
Console.WriteLine("Attribute:" + textReader.Name.ToString());
ac = ac + 1;
}
// if node type is an element
if (nType == XmlNodeType.Element)
{
Console.WriteLine("Element:" + textReader.Name.ToString());
el = el + 1;
}
// if node type is an entity\
if (nType == XmlNodeType.Entity)
{
Console.WriteLine("Entity:" + textReader.Name.ToString());
et = et + 1;
}
// if node type is a Process Instruction
if (nType == XmlNodeType.Entity)
{
Console.WriteLine("Entity:" + textReader.Name.ToString());
pi = pi + 1;
}

// if node type a document
if (nType == XmlNodeType.DocumentType)
{
Console.WriteLine("Document:"+textReader.Name.ToString());
dc = dc + 1;
}
// if node type is white space
if (nType == XmlNodeType.Whitespace)
{
Console.WriteLine("WhiteSpace"+textReader.Name.ToString());
ws = ws + 1;
}

}

// Write the summary
Console.WriteLine("Total Comments:" + cc.ToString());
Console.WriteLine("Total Attributes:" + ac.ToString());
Console.WriteLine("Total Elements:" + el.ToString());
Console.WriteLine("Total Entity:" + et.ToString());
Console.WriteLine("Total Process Instructions:"+pi.ToString());
Console.WriteLine("Total Declaration:" + xd.ToString());
Console.WriteLine("Total DocumentType:" + dc.ToString());
Console.WriteLine("Total WhiteSpaces:" + ws.ToString());

}

}

}

Writing XML Documents

XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents. This class has several Writexxx method to write every type of item of an XML document. For example, WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndElement are some of them. Some of these methods are used in a start and end pair. For example, to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.

Besides many methods, this class has three properties. WriteState, XmlLang, and XmlSpace. The WriteState gets and sets the state of the XmlWriter class.

Although, it's not possible to describe all the Writexxx methods here, let's see some of them.

First thing we need to do is create an instance of XmlTextWriter using its constructor. XmlTextWriter has three overloaded constructors, which can take a string, stream, or a TextWriter as an argument. We'll pass a string (file name) as an argument, which we're going to create in C:\ root.

In my sample example, I create a file myXmlFile.xml in C:\\ root directory.

// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null) ;

After creating an instance, first thing you call us WriterStartDocument. When you're done writing, you call WriteEndDocument and TextWriter's Close method.


textWriter.WriteStartDocument();
textWriter.WriteEndDocument();
textWriter.Close();

The WriteStartDocument and WriteEndDocument methods open and close a document for writing. You must have to open a document before start writing to it. WriteComment method writes comment to a document. It takes only one string type of argument. WriteString method writes a string to a document. With the help of WriteString, WriteStartElement and WriteEndElement methods pair can be used to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute.

WriteNode is more write method, which writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write a ProcessingInstruction and DocType items of a document.

//Write the ProcessingInstruction node
string PI= "type='text/xsl' href='book.xsl'"
textWriter.WriteProcessingInstruction("xml-stylesheet", PI);
//'Write the DocumentType node
textWriter.WriteDocType("book", Nothing, Nothing, "");

The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 5-14. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter:

After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter.

About Sample Example 3

In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items.

Sample Example 3.

using System;
using System.Xml;
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);
// Opens the document
textWriter.WriteStartDocument();
// Write comments
textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
textWriter.WriteComment("myXmlFile.xml in root dir");
// Write first element
textWriter.WriteStartElement("Student");
textWriter.WriteStartElement("r", "RECORD", "urn:record");
// Write next element
textWriter.WriteStartElement("Name", "");
textWriter.WriteString("Student");
textWriter.WriteEndElement();
// Write one more element
textWriter.WriteStartElement("Address", "");
textWriter.WriteString("Colony");
textWriter.WriteEndElement();
// WriteChars
char[] ch = new char[3];
ch[0] = 'a';
ch[1] = 'r';
ch[2] = 'c';
textWriter.WriteStartElement("Char");
textWriter.WriteChars(ch, 0, ch.Length);
textWriter.WriteEndElement();
// Ends the document.
textWriter.WriteEndDocument();
// close writer
textWriter.Close();

}

}

}




Using XmlDocument

The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article.

Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter.

About Sample Example 4

This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file.

Sample Example 4.

//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(("Tommy
ex
"));
//Save the document to a file.
doc.Save("C:\\std.xml");
You can also use Save method to display contents on console if you pass Console.Out as a
arameter. For example:
doc.Save(Console.Out);

About Sample Example 5

Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method argument displays data on the console

Sample Example 5.

XmlDocument doc = new XmlDocument();
//Load the the document with the last book node.
XmlTextReader reader = new XmlTextReader("c:\\books.xml");
reader.Read();
// load reader
doc.Load(reader);
// Display contents on the console
doc.Save(Console.Out);

Writing Data from a database to an XML Document

Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document.

The DataSet class provides method to read a relational database table and write this table to an XML file. You use WriteXml method to write a dataset data to an XML file.

In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query.

About Sample Example 6

In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter.

In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir.

Sample Example 6.

using System;
using System.Xml;
using System.Data;
using System.Data.OleDb;
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
// create a connection
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";
// create a data adapter
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);
// create a new dataset
DataSet ds = new DataSet();
// fill dataset
da.Fill(ds, "Customers");
ds.WriteXml("C:\\OutputXML.xml");

}

}

}

Random numbers with c#

Pseudo-Random NumbersWhether you're planning on building a game, looking to pick a lucky winner from an array of contest participants or simply want to display a random picture in your ASP.NET website, random numbers are something that you should know how to obtain, especially since in modern programming language it's so easy to. The dark truth behind computer generated random numbers however, is that they are not truly random, they are pseudo-random, generated by complex algorithms. But then again, for a long time scientists couldn't find anything random in the universe, and the current subjects that appear to be random are still debatable.

Without further ado, I present you what is needed in order to generate a random number in C#:

Random randNum = new Random();
randNum.Next();


That's all it takes. The creation of a Random object (of the System.Random class) and calling its Next() method, which is going to return a non-negative random number as an integer.


Random Numbers Within a RangeAs soon as you test the code above, you realize it returns a quite large number. However, most of the time you'll want to generate a number between a desired range. For instance if in your contest 108 people participated, you'll want to generate a random no larger than 108:


Random randNum = new Random();
randNum.Next(108); // No larger than 108


This will generate you a positive number of up to 108, including 108. However in certain situations (such as picking the contest winner), you'll want the number to be 1 to 108, while the code above returns a number that is 0 to 108. Since people would probably not take kindly to you announcing that the winner is participant number 0, thanks to another overload of the Next() function, you will be able to specify a minimum value, as such:

Random randNum = new Random();
randNum.Next(1, 108); // No larger than 108, no smaller than 1


Using SeedsC++ programmers and others may wonder what happened to the seed. Who's seeding this random number because you sure aren't? Well, in the default constructor of the Random() object that we've seen above, where no parameter was specified, a seed will be automatically generated for you based on the current system time (which should always be unique.) Not having to specify the system time yourself as a parameter is very convinient, since the great majority of programmers would do that when generating random numbers.

However, there are advantages to specifying your own seed. One important thing to note is that for as long as you specify the same seed, you will get the same random number. Let's look at an example:

Random randNum = new Random(1986);
randNum.Next(); // This will always generate 564610494


Here we specify a seed, more exactly the number 1986, in order to generate a random number based on that seed. However, what is the point of using this, when it always generates the same number? Check this out:

Random randNum = new Random(1986);
randNum.Next(); // This will always generate 564610494
randNum.Next(); // This will always generate 1174029081
randNum.Next(); // This will always generate 2057658224


The interesting concept behind this is that each time you apply the Next() method, it will come up with a different number, so more exactly you will get a sequence of random numbers, but since they're based on the same seed, whenever you use that seed again, you are guaranteed to get the same random numbers. Thus if we create a new Random object and pass the 1986 value, get some random values, then create another Random object and pass the same 1986 value as the seed, the same random numbers will be retrieved in the exact same sequence . I'm not going to get very deep into explaining this, but it's not hard to imagine where you would need this, and when you will need this (if ever), you'll know it.

Double-Precision Numbers Sometimes you may want to generate double-precision numbers, and C# has a method for that. Instead of using Next(), the NextDouble() method will return a number between 0 and 1:

Random randNum = new Random();
randNum.NextDouble();
randNum.NextDouble();
randNum.NextDouble();


This will generate numbers such as 0.12820489450164194, 0.81203657295197121 and 0.0582018419231087554.

Now if you picked into IntelliSense, you've probably noticed a new method:

Array of Random BytesThe NextBytes() method will fill an array of bytes with random bytes. Thus, each element of the array will be a byte with a value of 0 to 255:

byte[] randBytes = new byte[108];
Random randNum = new Random();
randNum.NextBytes(randBytes);


This code would produce an array with values as such: 196 231 77 225 52 144 146 72 3 90 18 233 161 205 147 196 35 152 30 220 41 114 156 25 184 185 30 64 140 138 215 62 178 90 158 94 0 47 101 234 151 44 71 189 146 113 111 90 3 93 59 104 91 143 81 82 75 51 40 123 113 81 188 121 130 212 55 71 47 52 195 243 50 52 68 252 42 222 135 70 74 196 61 46 79 111 227 34 8 75 19 205 6 234 120 70 112 206 58 190 58 39 42 206 153 71 53 38. But of course, since we don't specify a seed and the current system time is being used, you'll get a different set of values.

That's all for random numbers using C#.

Arrays in c#

There are 2 methods commonly used for declaring arrays. While both have their place and usage, most programmers prefer the dynamic array that is declared at run-time to provide the most flexibility. The static array is great if you have a set structure that will never change. For instance, an array that holds the days of the week, months in the year, or even the colors in a rainbow. These won't change and they won't be data driven so in this case, a static array will be best.
Static Arrays
Arrays can be declared in many ways. These first examples demonstrate arrays that are created at "design time" – (programmer sets the value(s) and length). This array is "hard coded". Hard coded means that the values and length of the array are established at the time the array is declared and isn't based on user input or stored data. It won't vary while the program is running. Notice that there is more than one way to declare this type of arrays.

string[] strFruitArray = {"apple", "banana", "orange", "grape", "pineapple"};
string[] strFruitArray = new string[]{"apple", "banana", "orange", "grape", "pineapple"};
string[]strFruitArray;
strFruitArray = new string [5] {"apple", "banana", "orange", "grape", "pineapple"};


Regardless of which method is used to declare the array, referencing the individual values is done the same way

strFruitArray[0] = "apple"
strFruitArray[1] = "banana"
strFruitArray[2] = "orange"
strFruitArray[3] = "grape"
strFruitArray[4] = "pineapple"


Dynamic Arrays
Most of the time, we need to have arrays that we won't know the values or how many items. The next example is an example of a completely dynamic array. The only information set at design time is the data type (int), the variable name (intArray), and that it is an array ([]). The values and the number of values will be based on user input or data retrieved from at runtime. The following is an example of how this type of array is declared.

No length or values set at the time of declaration. Set this at the class level (see full example download) in order for it to be visible to the entire form class.
int[] intArray;

Fixed length at the time of declaration but not the values
intArray = new int[5];
Practical Example of a Dynamic Array
In the example below, there is a list box with some values. When the user clicks the "Create Array" button, the array size is set to the number of items in the list box and a for loop is used to add the values to the dynamic array.

private void btnCreateArray_Click(object sender, EventArgs e)
{
//the number of items in the list box is the size of our array.
int intNumItems = lstBoxValues.Items.Count;
//get the number of items
strListItems = new string[intNumItems];
//use a for iteration to add the items.
//List boxes are also 0 based. The first item in the list will be referred
//to as lstBoxValues[0].
for (int intX = 0; intX < lstBoxValues.Items.Count; intX++) strListItems[intX] = lstBoxValues.Items[intX].ToString(); //Show array properties in a rich text box named rtbArrayValues rtbArrayValues.Text = "Total number of elements = " + strListItems.LongLength + "\n" ;//the \n is a return rtbArrayValues.Text += "The LowerBound() value = " + strListItems.GetLowerBound(0).ToString() + "\n"; rtbArrayValues.Text += "The UpperBound() value = " + strListItems.GetUpperBound(0).ToString() + "\n" ; //show all of the values using the for iteration for (int intX = 0; intX <= strListItems.GetUpperBound(0); intX++) rtbArrayValues.Text += "value " + intX + " is " + strListItems[intX] "\n"; }

CLASSIC ASP types

Date/Time Functions

Function Description
CDate Converts a valid date and time expression to
the variant of subtype Date
Date Returns the current system date
DateAdd Returns a date to which a specified time
interval has been added
DateDiff Returns the number of intervals between two
dates
DatePart Returns the specified part of a given
date
DateSerial Returns the date for a specified year, month,
and day
DateValue Returns a date
Day Returns a number that represents the day of the
month (between 1 and 31, inclusive)
FormatDateTime Returns an expression formatted as a date or
time
Hour Returns a number that represents the hour of
the day (between 0 and 23, inclusive)
IsDate Returns a Boolean value that indicates if the
evaluated expression can be converted to a date
Minute Returns a number that represents the minute of
the hour (between 0 and 59, inclusive)
Month Returns a number that represents the month of
the year (between 1 and 12, inclusive)
MonthName Returns the name of a specified month
Now Returns the current system date and time
Second Returns a number that represents the second of
the minute (between 0 and 59, inclusive)
Time Returns the current system time
Timer Returns the number of seconds since 12:00
AM
TimeSerial Returns the time for a specific hour, minute,
and second
TimeValue Returns a time
Weekday Returns a number that represents the day of the
week (between 1 and 7, inclusive)
WeekdayName Returns the weekday name of a specified day of
the week
Year Returns a number that represents the
year



Conversion Functions

Top
Function Description
Asc Converts the first letter in a string to ANSI
code
CBool Converts an expression to a variant of subtype
Boolean
CByte Converts an expression to a variant of subtype
Byte
CCur Converts an expression to a variant of subtype
Currency
CDate Converts a valid date and time expression to
the variant of subtype Date
CDbl Converts an expression to a variant of subtype
Double
Chr Converts the specified ANSI code to a
character
CInt Converts an expression to a variant of subtype
Integer
CLng Converts an expression to a variant of subtype
Long
CSng Converts an expression to a variant of subtype
Single
CStr Converts an expression to a variant of subtype
String
Hex Returns the hexadecimal value of a specified
number
Oct Returns the octal value of a specified
number



Format Functions

Top
Function Description
FormatCurrency Returns an expression formatted as a currency
value
FormatDateTime Returns an expression formatted as a date or
time
FormatNumber Returns an expression formatted as a
number
FormatPercent Returns an expression formatted as a
percentage



Math Functions

Top
Function Description
Abs Returns the absolute value of a specified
number
Atn Returns the arctangent of a specified
number
Cos Returns the cosine of a specified number
(angle)
Exp Returns e raised to a power
Hex Returns the hexadecimal value of a specified
number
Int Returns the integer part of a specified
number
Fix Returns the integer part of a specified
number
Log Returns the natural logarithm of a specified
number
Oct Returns the octal value of a specified
number
Rnd Returns a random number less than 1 but greater
or equal to 0
Sgn Returns an integer that indicates the sign of a
specified number
Sin Returns the sine of a specified number
(angle)
Sqr Returns the square root of a specified
number
Tan Returns the tangent of a specified number
(angle)



Array Functions

Top
Function Description
Array Returns a variant containing an array
Filter Returns a zero-based array that contains a
subset of a string array based on a filter criteria
IsArray Returns a Boolean value that indicates whether
a specified variable is an array
Join Returns a string that consists of a number of
substrings in an array
LBound Returns the smallest subscript for the
indicated dimension of an array
Split Returns a zero-based, one-dimensional array
that contains a specified number of substrings
UBound Returns the largest subscript for the indicated
dimension of an array



String Functions

Top
Function Description
InStr Returns the position of the first occurrence of
one string within another. The search begins at the first
character of the string
InStrRev Returns the position of the first occurrence of
one string within another. The search begins at the last
character of the string
LCase Converts a specified string to lowercase
Left Returns a specified number of characters from
the left side of a string
Len Returns the number of characters in a
string
LTrim Removes spaces on the left side of a
string
RTrim Removes spaces on the right side of a
string
Trim Removes spaces on both the left and the right
side of a string
Mid Returns a specified number of characters from a
string
Replace Replaces a specified part of a string with
another string a specified number of times
Right Returns a specified number of characters from
the right side of a string
Space Returns a string that consists of a specified
number of spaces
StrComp Compares two strings and returns a value that
represents the result of the comparison
String Returns a string that contains a repeating
character of a specified length
StrReverse Reverses a string
UCase Converts a specified string to
uppercase



Other Functions

Top
Function Description
CreateObject Creates an object of a specified type
Eval Evaluates an expression and returns the
result
GetLocale Returns the current locale ID
GetObject Returns a reference to an automation object
from a file
GetRef Allows you to connect a VBScript procedure to a
DHTML event on your pages
InputBox Displays a dialog box, where the user can write
some input and/or click on a button, and returns the
contents
IsEmpty Returns a Boolean value that indicates whether
a specified variable has been initialized or not
IsNull Returns a Boolean value that indicates whether
a specified expression contains no valid data (Null)
IsNumeric Returns a Boolean value that indicates whether
a specified expression can be evaluated as a number
IsObject Returns a Boolean value that indicates whether
the specified expression is an automation object
LoadPicture Returns a picture object. Available only on
32-bit platforms
MsgBox Displays a message box, waits for the user to
click a button, and returns a value that indicates which
button the user clicked
RGB Returns a number that represents an RGB color
value
Round Rounds a number
ScriptEngine Returns the scripting language in use
ScriptEngineBuildVersion Returns the build version number of the
scripting engine in use
ScriptEngineMajorVersion Returns the major version number of the
scripting engine in use
ScriptEngineMinorVersion Returns the minor version number of the
scripting engine in use
SetLocale Sets the locale ID and returns the previous
locale ID
TypeName Returns the subtype of a specified
variable
VarType Returns a value that indicates the subtype of a
specified variable

Classic ASP - read/write files

The following VBScript example demonstrates how to open a file, write to it, and then read from it:

Sub ReadFiles
Dim fso, f1, ts, s
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line.
Response.Write "Writing file
"
f1.WriteLine "Hello World"
f1.WriteBlankLines(1)
f1.Close
' Read the contents of the file.
Response.Write "Reading file
"
Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
s = ts.ReadLine
Response.Write "File contents = '" & s & "'"
ts.Close
End Sub



This code demonstrates the same in JScript:

function ReadFiles()
{
var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line.
Response.Write("Writing file
");
f1.WriteLine("Hello World");
f1.WriteBlankLines(1);
f1.Close();
// Read the contents of the file.
Response.Write("Reading file
");
ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
s = ts.ReadLine();
Response.Write("File contents = '" + s + "'");
ts.Close();
}



The following VBScript example creates a text file in the root directory of drive C, writes some information to it, moves it to a directory called \tmp, makes a copy of it in a directory called \temp, then deletes the copies from both directories.

To run the following example, create directories named \tmp and \temp in the root directory of drive C:

Sub ManipFiles
Dim fso, f1, f2, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
Response.Write "Writing file
"
' Write a line.
f1.Write ("This is a test.")
' Close the file to writing.
f1.Close
Response.Write "Moving file to c:\tmp
"
' Get a handle to the file in root of C:\.
Set f2 = fso.GetFile("c:\testfile.txt")
' Move the file to \tmp directory.
f2.Move ("c:\tmp\testfile.txt")
Response.Write "Copying file to c:\temp
"
' Copy the file to \temp.
f2.Copy ("c:\temp\testfile.txt")
Response.Write "Deleting files
"
' Get handles to files' current location.
Set f2 = fso.GetFile("c:\tmp\testfile.txt")
Set f3 = fso.GetFile("c:\temp\testfile.txt")
' Delete the files.
f2.Delete
f3.Delete
Response.Write "All done!"
End Sub


This code shows the same in JScript:

function ManipFiles()
{
var fso, f1, f2, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
Response.Write("Writing file
");
// Write a line.
f1.Write("This is a test.");
// Close the file to writing.
f1.Close();
Response.Write("Moving file to c:\\tmp
");
// Get a handle to the file in root of C:\.
f2 = fso.GetFile("c:\\testfile.txt");
// Move the file to \tmp directory.
f2.Move ("c:\\tmp\\testfile.txt");
Response.Write("Copying file to c:\\temp
");
// Copy the file to \temp.
f2.Copy ("c:\\temp\\testfile.txt");
Response.Write("Deleting files
");
// Get handles to files' current location.
f2 = fso.GetFile("c:\\tmp\\testfile.txt");
f3 = fso.GetFile("c:\\temp\\testfile.txt");
// Delete the files.
f2.Delete();
f3.Delete();
Response.Write("All done!");
}

Monday, March 15, 2010

Upload csv file in sql server using bcp

If you want to upload text files into sql database you must create an fmt file with file configuration. "fmt" file must have the same configuration with table you upload in.

create fmt file

exec master.dbo.xp_cmdshell 'bcp "DATABASE.dbo.TABLE" format null -f C:\FOLDER\FILE.fmt -c -T -U username -S ip
-e C:\FOLDER\err.txt'

where FILE.fmt reprezents the fmt file that you create
ERR.txt - error log file

The upload code is different int sql 2000 and 2005

--2005

select *
FROM OPENROWSET(BULK 'C:\FOLDER\FILE.csv',
FORMATFILE = 'c:\FOLDER\FILE.fmt') as tmp1


--2000

BULK INSERT ABR_FRAMEWORK.dbo.ABR_CRB_ERR_TRANSMISIE FROM 'c:\FILE\FILE.csv'
WITH (FORMATFILE = 'c:\FOLDER\FILE.fmt')

create sql users from a table

If you want to create Sql Server database users from an table (TABLE_USERS) you can use this code:

DECLARE @name VARCHAR(100)
DECLARE @cnp VARCHAR(100)
DECLARE @userName VARCHAR(100)
DECLARE @sql NVARCHAR(300)
DECLARE @id int
DECLARE @Name varchar(100)

DECLARE db_cursor CURSOR FOR
select   a.DomainName, c.Code,c.Name from TABLE_USERS

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name,@cnp ,@Name
WHILE @@FETCH_STATUS = 0
BEGIN

SET @userName = ltrim(rtrim(@name))
IF not EXISTS (SELECT * FROM sys.server_principals WHERE name = @userName)
begin
     select @sql = 'CREATE LOGIN ['+@userName+'] FROM WINDOWS  
           WITH  DEFAULT_DATABASE = [DATABASE],  DEFAULT_LANGUAGE=[us_english]'

     EXEC sp_executesql @sql
 
    select @sql = 'CREATE USER ['+@userName+'] FOR LOGIN ['+@userName+'] WITH  
          DEFAULT_SCHEMA=[dbo]'
    EXEC sp_executesql @sql
end

select @sqlRollMember = 'execute sp_addrolemember '+@DBRole2+' , '''+@userName + ''''
EXEC sp_executesql @sqlRollMember
END
CLOSE db_cursor
DEALLOCATE db_cursor

Installing IIS After .NET Framework

If you install IIS after .NET framework or if you removed and reinstalled IIS on a server that has .NET framework, then your ASP.NET pages will not work.


This is because you are missing the IIS mappings associating the ASP.NET file extensions.

To fix IIS mappings for ASP.NET, follow these steps:

1. Click Start -> run -> cmd - ENTER

2. At the command prompt, type the following, and then press ENTER:

"%windir%\Microsoft.NET\Framework\version\aspnet_regiis.exe" -i

In this path, version represents the version number of the .NET Framework that you installed on your server. You need to replace with the actual version number when you type the command.

3. Register the Aspnet_isapi.dll by clicking start -> run

4. In the Open text box, type "regsvr32 %windir%\Microsoft.NET\Framework\version\aspnet_isapi.dll" and then press ENTER

Create Charts in c# using OWC

Charts and graphs are considered to be very useful form of data representation. Graphs can add significant impact and visualization to your applications, especially in Web applications. Creating dynamic graphs in your web applications generally requires third party tools that have the ability to create graphs dynamically. A simple and inexpensive way to do this is using the Office Web Components (OWC). Apart from other third party tools, OWC charts are completely customizable, can have detailed charting and also have a professional look.

This article gives you the answers for the following questions.
How can you display your data as graphs in your web pages?
What is OWC?
How to implement OWC Charts in ASP .Net using C#?
Introduction
The Office Web Component (OWC) is a set of controls included in the Microsoft Office 2000. Using these components, we can build many useful data analysis and reporting solutions in web browsers or in traditional programming environments. The office Web Components are a set of COM controls designed to bring interactive spreadsheet modeling, database reporting, and data visualization. OWC library contains four principal components:
  • Spreadsheet
  • Chart
  • PivotTable
  • Data Source
The controls are standard COM controls and can be used in many control containers such as Microsoft Internet Explorer, Microsoft Visual Basic, Microsoft Visual C++, Microsoft Visual FoxPro, or Microsoft Office UserForms. However, the controls have a few behaviors that make them especially suited to the unique environment of Internet Explorer.
OWC Charts
To display a chart in your web page you have to do the following steps.
Read the data to plot the chart from a database
Create an OWC Chart
Add required number of chart series in it.
Give the values for each chart series.
Customize your chart to display it in the format you wish
Create a GIF image from the chart
Display the image in your web page using the tag.
The data required for plotting the chart is bound to the chart component as its datasource. The Chart Component supports different types of datasource. They are A data source that implements the IDataSource interface
An ADO Recordset object.
XML stream (if the data is persisted to the stream in the XML persistence format.)
Literal data in the form of a delimited string or array (a chart that uses literal data is not considered to be bound.)
Data Source In ASP

ASP can use the ADO Recordset object as the datasource for the chart and so the implementation is much more easy and straightforward.
Data Source In ASP .Net

The DataSet class in ADO.NET does not implement IDataSource, and the .NET Framework does not support a direct means to convert an ADO.NET DataSet object to an ADO Recordset object. If you have a DataSet from which you want to create a chart, you can either transform the DataSet into a stream that uses the XML persistence format for ADO, or you can generate literal data from the DataSet.
Terms and Definitions

ChartSpace: Represents the chart workspace. The chart workspace is the top-level chart container; it can contain more than one chart, with each chart represented by a WCChart object. When a chart workspace is first created, it is empty (it does not contain any charts). Use the Add method of the WCCharts object to create a new chart.
WCCharts: Represents a single chart in the chart workspace. The chart workspace can contain up to 16 charts.
WCSeriesCollection: Represents a collection of all the WCSeries objects on a chart. A chart can contain up to 255 series.
WCSeries: Represents a series on a chart. (Example: A line in a line graph, a bar in a bar graph etc.)
Implementing Charts in ASP .Net using C#

To Start with, the OWC component has to be included in our project. For this, in the Visual Studio .Net, right click �References� in the Solution Explorer. Select The Add references option. In the Add references Dialog, Select The COM tab. Select The Microsoft Office Component from the list and click OK. Add the using directive to add the control in your C# page.

using OWC;
A placeholder must be added in the ASPX page to hold the graph image. For this, simply add the following code in the web page where you want to show the graph.

In the C# code behind we can write the code to create the chart image and add the image into the placeholder. Here is the code for creating a column wise bar graph.
//First create a ChartSpace object to hold the chart

OWC.ChartSpace objCSpace = new OWC.ChartSpaceClass ();
//Add a chart in the ChartSpace. The Add method returns a chart object.
OWC.WCChart objChart = objCSpace.Charts.Add (0);
/*Specify the type of the graph to be displayed. The type of the graph is specified by the enumerated values in OWC.ChartChartTypeEnum. */
objChart.Type = OWC.ChartChartTypeEnum.chChartTypeColumnClustered;
//Specify if the chart needs to have legend.
objChart.HasLegend = true;
//Give title to graph.
objChart.HasTitle = true;
objChart.Title.Caption= "Title Of The Chart";
//Give the caption for the X axis and Y axis of the graph
objChart.Axes[0].HasTitle = true;
objChart.Axes[0].Title.Caption = "Y Axis Caption";
objChart.Axes[1].HasTitle = true;
objChart.Axes[1].Title.Caption = "X Axis Caption";
//Populate the Literal Strings For the data
/*The categories and values can be given as literal string with values separated by tabs. With these three values we can draw a single line.*/
string strSeriesName = "Line 1";
string strCategory = "1" + '\t' + "2" + '\t' + "3" + '\t';
string strValue = "9" + '\t' + "8" + '\t' + "4" + '\t';
//Add a series to the chart�s series collection
objChart.SeriesCollection.Add(0);
//Give the name of the series
objChart.SeriesCollection[0].SetData (OWC.ChartDimensionsEnum.chDimSeriesNames, (int)OWC.ChartSpecialDataSourcesEnum.chDataLiteral, strSeriesName);
//Give the Categories
objChart.SeriesCollection[0].SetData (OWC.ChartDimensionsEnum.chDimCategories, (int)OWC.ChartSpecialDataSourcesEnum.chDataLiteral, strCategory);
//Give The values
objChart.SeriesCollection[0].SetData
(OWC.ChartDimensionsEnum.chDimValues,
(int)OWC.ChartSpecialDataSourcesEnum.chDataLiteral, strValue);

//Now a chart is ready to export to a GIF.
string strAbsolutePath = (Server.MapPath(".")) + "\TempFiles\somefilename.gif";
objCSpace.ExportPicture(strAbsolutePath, "GIF", 600, 350);
//Create a relative path to the GIF file.

/*If an absolute path is used instead of a relative path, the file will not be displayed in the client machines as the file is created in the server, not in the client. */

string strRelativePath = "./TempFiles/somefilename.gif";
//Add the image into the placeholder.
string strImageTag = "";
ChartHolder.Controls.Add(new LiteralControl(strImageTag));

Create SSIS Package - SQL Server

To create a new SSIS package, follow these steps:
1. Launch Business Intelligence Development Studio

2. Select File -> New -> Project.
3. Select the Business Intelligence Projects project type.

4. Select the Integration Services Project template.

5. Select a convenient location.

6. Name the new project ISProject1 and click OK.


Working with Connection Managers


SSIS uses connection managers to integrate different data sources into packages.
SSIS includes a wide variety of different connection managers that allow you to move data around from place to place. Table 16-1 lists the available connection managers.

ADO Connection Manager Connecting to ADO objects such as a Recordset
ADO.NET Connection Manager  - Connecting to data sources through an ADO.NET provider.
Analysis Services Connection Manager  - Connecting to an Analysis Services database or cube.
Excel Connection Manager  - Connecting to an Excel worksheet.
File Connection Manager - Connecting to a file or folder.
Flat File Connection Manager  - Connecting to delimited or fixed width flat files.
FTP Connection Manager - Connecting to an FTP data source.
HTTP Connection Manager Connecting to an HTTP data source.

MSMQ Connection Manager Connecting to a Microsoft Message Queue.
Multiple Files Connection Manager Connecting to a set of files, such as all text files on a particular hard drive.
Multiple Flat Files Connection Manager Connecting to a set of flat files.
ODBC Connection Manager Connecting to an ODBC data source.
OLE DB Connection Manager Connecting to an OLE DB data source.
SMO Connection Manager Connecting to a server via SMO.
SMTP Connection Manager Connecting to a Simple Mail Transfer Protocol server.
SQL Server Mobile Connection Manager Connecting to a SQL Server Mobile database.
WMI Connection Manager Connecting to Windows Management

To create a Connection Manager, you right-click anywhere in the Connection Managers area of a package in BIDS and choose the appropriate shortcut from the shortcut menu. Each Connection Manager has its own custom configuration dialog  box with specific options that you need to fill out.

Try It!


To add some connection managers to your package, follow these steps:
1. Right-click in the Connection Managers area of your new package and select New OLE DB Connection.
2. Note that the configuration dialog box will show the data connections that you created in Chapter 15; data connections are shared across Analysis Services and Integration Services projects. Click New to create a new data connection.
3. In the Connection Manager dialog box, select the SQL Native Client provider.
4. Select your test server and provide login information.
5. Select the Chapter16 database.
6. Click OK.
7. In the Configure OLE DB Connection Manager dialog box, click OK.
8. Right-click in the Connection Managers area of your new package and select New Flat File Connection.
9. Enter DepartmentList as the Connection Manager Name.
10. Enter C:\Departments.txt as the File Name (this file will be supplied by your instructor).
11. Check the Column Names in the First Data Row checkbox. Figure 16-4 shows the completed General page of the dialog box.



 
12. Click the Advanced icon to move to the Advanced page of the dialog box.
13. Click the New button.
14. Change the Name of the new column to DepartmentName.
15. Click OK.
16. Right-click the DepartmentList Connection Manager and select Copy.
17. Right-click in the Connection Managers area and select Paste.
18. Click on the new DepartmentList 1 connection to select it.


Use the Properties Window to change properties of the new connection.
Change the Name property to DepartmentListBackup. Change the ConnectionString property to C:\DepartmentsBackup.txt.


The Control Flow tab of the Package Designer is where you tell SSIS what them package will do. You create your control flow by dragging and dropping items from the toolbox to the surface, and then dragging and dropping connections between the objects. The objects you can drop here break up into four different groups:
• Tasks are things that SSIS can do, such as execute SQL statements or transfer objects from one SQL Server to another. Table 16-2 lists the available tasks.
• Maintenance Plan tasks are a special group of tasks that handle jobs such as checking database integrity and rebuilding indexes. Table 16-3 lists the maintenance plan tasks.
The Data Flow Task is a general purpose task for ETL (extract, transform, and load) operations on data. There’s a separate design tab for building the details of a Data Flow Task.
• Containers are objects that can hold a group of tasks. Table 16-4 lists the available containers.


To add control flows to the package you’ve been building, follow these steps:


1. If the Toolbox isn’t visible already, hover your mouse over the Toolbox tab until it slides out from the side of the BIDS window. Use the pushpin button in the Toolbox title bar to keep the Toolbox visible.
2. Make sure the Control Flow tab is selected in the Package Designer.
3. Drag a File System Task from the Toolbox and drop it on the Package Designer.
4. Drag a Data Flow Task from the Toolbox and drop it on the Package Designer, somewhere below the File System task.
5. Click on the File System Task on the Package Designer to select it.
6. Drag the green arrow from the bottom of the File System Task and drop it on top of the Data Flow Task. This tells SSIS the order of tasks when the File System Task succeeds.
7. Double-click the connection between the two tasks to open the Precedence Constraint Editor.
8. Change the Value from Success to Completion, because you want the Data Flow Task to execute whether the File System Task succeeds or not.
9. Click OK.
10. Select the File System task in the designer. Use the Properties Window to set properties of the File System Task. Set the Source property to DepartmentList. Set the Destination property to DepartmentListBackup.Set the OverwriteDestinationFile property to True.



Building Data Flows


The Data Flow tab of the Package Designer is where you specify the details of any Data Flow tasks that you’ve added on the Control Flow tab. Data Flows are made up of various objects that you drag and drop from the Toolbox:
• Data Flow Sources are ways that data gets into the system. Table 16-5 lists the available data flow sources.
• Data Flow Transformations let you alter and manipulate the data in various ways. Table 16-6 lists the available data flow transformations.
• Data Flow Destinations are the places that you can send the transformed data.

Try It!


To customize the data flow task in the package you’re building, follow these steps:

1. Select the Data Flow tab in the Package Designer. The single Data Flow Task in the package will automatically be selected in the combo box.
2. Drag an OLE DB Source from the Toolbox and drop it on the Package Designer.
3. Drag a Character Map Transformation from the Toolbox and drop it on the Package Designer.
4. Drag a Flat File Destination from the Toolbox and drop it on the Package Designer.
5. Click on the OLE DB Source on the Package Designer to select it.
6. Drag the green arrow from the bottom of the OLE DB Source and drop it on top of the Character Map Transformation.
7. Click on the Character Map Transformation on the Package Designer to select it.
8. Drag the green arrow from the bottom of the Character Map Transformation and drop it on top of the Flat File Destination.
9. Double-click the OLE DB Source to open the OLE DB Source Editor.
10. Select the HumanResources.Department view. Figure 16-7 shows the completed OLE DB Source Editor.

11. Click OK.

12. Double-click the Character Map Transformation.
13. Check the Name column.
14. Select In-Place Change in the Destination column.
15. Select the Uppercase operation. Figure 16-8 shows the completed Character Map Transformation Editor.


16. Click OK.

17. Double-click the Flat File Destination.
18. Select the DepartmentList Flat File Connection Manager.
19. Select the Mappings page of the dialog box.
20. Drag the Name column from the Available Input Columns list and drop it on top of the DepartmentName column in the Available Destination Columns list.




The data flows in this package take a table from the Chapter16 database, transform one of the columns in that table to all uppercase characters, and then write that transformed column out to a flat file.

Sunday, March 14, 2010

Add image to pdf


using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class AddImage{

public static void Main() {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileStream("Example.pdf", FileMode.Create));
document.Open();

Image wmf = Image.getInstance(new Uri("http://itextsharp.sourceforge.net/examples/harbour.wmf"));
Image gif = Image.getInstance(new Uri("http://itextsharp.sourceforge.net/examples/vonnegut.gif"));
Image jpeg = Image.getInstance(new Uri("http://itextsharp.sourceforge.net/examples/myKids.jpg"));
Image png = Image.getInstance(new Uri("http://itextsharp.sourceforge.net/examples/hitchcock.png"));

document.Add(wmf);
document.Add(gif);
document.Add(jpeg);
document.Add(png);
}

catch(DocumentException de) {
Console.Error.WriteLine(de.Message);
}
catch(IOException ioe) {
Console.Error.WriteLine(ioe.Message);
}
document.Close();
}
}