Showing posts with label C# PDF file. Show all posts
Showing posts with label C# PDF file. Show all posts

Wednesday, 12 March 2014

Multi-Threading Concept in c#(Questions and answers)

Multi-Threading Concept in c# (Questions and answers)
Multithreading is the ability of an operating system to concurrently run programs that have been divided into threads.
Multithreading offers better utilization of processors and other system resources.
Example:
A program can spell check and save the data to disk while sending data to be printed. 
Advantages and disadvantages of using multithreading
Advantages:
Simultaneous access to multiple applications
Reduced number of required servers
Improved performance and concurrency
Simplified coding of remote procedure calls and conversations
Disadvantages:
Code writing, debugging, managing concurrency, testing, porting existing code is difficult in multithreading and multicontexting.
Programmers need to remove static variables and replace any code that is not thread-safe to introduce threading into a previously non threaded application. 
Benefits of using the Thread Pool.
The benefits of using a Thread Pool are:
Thread creation and destruction overhead is negated,
Better performance and better system stability.
It is better to use a thread pool in cases where the number of threads is very large. 


Explain how to create and manage threads using Thread class in the System.Threading namespace in .NET.
using System.Threading;
private void ThreadTask()
{
         int x;
         int val;
         Random r=new Random();

         while(true)
         {
             x=this.progressBar1.Step*r.Next(-1,2);
            val = this.progressBar1.Value + x;
            if (val > this.progressBar1.Maximum)
                  val = this.progressBar1.Maximum;
            else if (val < this.progressBar1.Minimum)
                  val = this.progressBar1.Minimum;
            this.progressBar1.Value = val;
            Thread.Sleep(100);
         }
}
You need to write these lines first:
    Thread t1 = new Thread(new ThreadStart(this.ThreadTask));
    t1.IsBackground = true;
    t1.Start(); 
Explain the purpose of Mutex class in .NET.
System uses synchronization mechanism to make sure that a resource is used by only one thread at a time when more than one thread needs to access a shared resource at the same time.
Mutex grants exclusive access to the shared resource to a single thread.
A second thread that needs to acquire a particular mutex is suspended until the first thread releases the mutex. 
Describe the concepts of Monitor class, the interlocked class and the ReaderWriterLock class.
Access to objects by is controlled by the Monitor class. It grants a lock for an object to a single thread.
Critical sections can be access restricted by using object locks.
While a thread owns the lock for an object, no other thread can acquire that lock.
Interlocked class provides atomic operations for variables that are shared by multiple threads.
When two threads are executing concurrently on separate processors error protection is done.
The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads.
ReaderWriterLock synchronizes access to a resource. It allows either concurrent read access for multiple threads, or write access for a single thread.
A ReaderWriterLock provides better throughput than a simple one lock a time like Monitor.
Explain about Serialization in .NET. Explain binary serialization and XML serialization
System.Runtime.Serialization namespace provides Serialization in .NET.
The IFormatter interface in the namespace contains Serialize and De-serialize methods that save and load data of a stream.
So we need stream as a container for the serialized object(s) and a formatter that serializes these objects onto the stream to implement serialization in .net.
Binary serialization is a mechanism that creates exact binary copy of the object onto the storage media by writing the data to the output stream such that it can be used to re-construct the object automatically.
XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format for storage or transport. This XML stream conforms to a specific XML Schema definition language (XSD) document.
Explain why Serialization.
An object is stored in a file, a database or even in the memory. However, data to be transferred over a network needs to be in a linear form for which serialization and deserialization are used.
Advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object later by de-serializing the object.
Remoting and Web Services depend heavily on Serialization and De-serialization.
Explain the components that comprise the binary serialization architecture.
To binary serialize an object we need a FileStream object,
Constructor: FileStream(file_name, FileMode.Create);
And
BinaryFormatter

Constructor: binaryFormatter.Serialize(fileStreamObject, object1);

What is Formatters? Explain the binary formatter and the SOAP formatter.
A formatter determines the serialization format for objects.
.NET framework provides Binary formatter and SOAP formatter which inherit from the IFormatter interface
The Binary Formatter
It provides binary encoding for compact serialization for storage or socket-based network streams.
It is not appropriate for data to be passed through a firewall.
The SOAP Formatter
It provides formatting that can be used to enable objects to be serialized using the SOAP protocol.
The class is used for serialization through firewalls or diverse systems. 
What are the main advantages of binary serialization?
An object is stored in a file, a database or even in the memory. However, data to be transferred over a network needs to be in a linear form for which serialization and deserialization are used.
Advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object later by de-serializing the object.
Also Binary Serialization is faster, supports complex objects too with read only properties and even circular references. 
How do you encapsulate the binary serialization?
public static void SerializeBinary( object o, string file_name)
{
   using (FileStream fs = new FileStream(file_name, FileMode.Create)) {
  BinaryFormatter fmt = new BinaryFormatter ();
  fmt.Serialize(fs, o);
  }
} 
How do you implement a custom serialization?
CUSTOM SERIALIZATION implementation
public class A: ISerializable
{
           private int a;
           protected A(SerializationInfo si, StreamingContext sc)
           {
                   this.a = serializationInfo.GetInt32("a");
           }
           public void ISerializable.GetObjectData(SerializationInfo si, StreamingContext sc)
           {
                     si.AddValue("a", this.a);
            }
} 
What is the difference between the SoapFormatter and the XmlSerializer?
SoapFormatter
SOAP formatter will actually take the field values of an object and store all of that information in the stream passed.
SoapFormatter is better to serialize arbitrary data
XmlSerializer
XML Serialization would just serialize the public properties of an object.
The XML Serializer is used typically for serializing simple types across web services
xmlserializer is better, more flexible and faster 
How can I optimize the serialization process?
The first call to a Web Service takes long because XmlSerializer generate an assembly optimized for each type in memory.
To optimize the serialization process pregeneration of serialization assembly with Visual Studio or sgen.exe is needed.
Implementing serialization separately can also increase the performance. 
Apartments
COM objects in the process as divided into groups called apartments. A COM object lives in exactly one apartment, in the sense that its methods can legally be directly called only by a thread that belongs to that apartment. Any other thread that wants to call the object must go through a proxy.
There are two types of apartments: single-threaded apartments, and multithreaded apartments.
1.Single-threaded Apartments—Single-threaded apartments consist of exactly one thread, so all COM objects that live in a single-threaded apartment can receive method calls only from the one thread that belongs to that apartment. All method calls to a COM object in a single-threaded apartment are synchronized with the windows message queue for the single-threaded apartment's thread. A process with a single thread of execution is simply a special case of this model.
2. Multithreaded Apartments—Multithreaded apartments consist of one or more threads, so all COM objects that live in an multithreaded apartment can receive method calls directly from any of the threads that belong to the multithreaded apartment. Threads in a multithreaded apartment use a model called free-threading. Calls to COM objects in a multithreaded apartment are synchronized by the objects themselves.
Synchronizing objects
Lock
Locks are useful when only one thread at a time can be allowed to modify data or some other controlled resource.
Monitors
Monitors are Like the lock keyword, monitors prevent blocks of code from simultaneous execution by multiple threads. The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit. This is just like using the lock keyword. In fact, the lock keyword is implemented with the Monitor class.
Mutex
A mutex is similar to a monitor; it prevents the simultaneous execution of a block of code by more than one thread at a time. In fact, the name "mutex" is a shortened form of the term "mutually exclusive." Unlike monitors, however, a mutex can be used to synchronize threads across processes.
Semaphore is same as Mutex but it ensures not more than a specified number of threads can access a resource, or section of code. 

Monday, 10 March 2014

Threading Overview and Concepts in C#

How Threading Works
Multithreading is managed internally by a thread scheduler, a
function the CLR typically delegates to the operating system. A
thread scheduler ensures all active threads are allocated
appropriate execution time, and that threads that are waiting or
blocked – for instance – on an exclusive lock, or on user input –
do not consume CPU time.
On a single-processor computer, a thread scheduler performs
time-slicing – rapidly switching execution between each of the
active threads. This results in "choppy" behavior, such as in the
very first example, where each block of a repeating X or Y
character corresponds to a time-slice allocated to the thread.
Under Windows XP, a time-slice is typically in the tens-ofmilliseconds
region – chosen such as to be much larger than the
CPU overhead in actually switching context between one thread
and another (which is typically in the few-microseconds region).
On a multi-processor computer, multithreading is implemented
with a mixture of time-slicing and genuine concurrency – where
different threads run code simultaneously on different CPUs. It's
almost certain there will still be some time-slicing, because of the
operating system's need to service its own threads – as well as
those of other applications.
A thread is said to be preempted when its execution is interrupted
due to an external factor such as time-slicing. In most situations,
a thread has no control over when and where it's preempted.
Threads vs. Processes
All threads within a single application are logically contained within a process – the operating
system unit in which an application runs.
Threads have certain similarities to processes – for instance, processes are typically time-sliced
with other processes running on the computer in much the same way as threads within a single
C# application. The key difference is that processes are fully isolated from each other; threads
share (heap) memory with other threads running in the same application. This is what makes
threads useful: one thread can be fetching data in the background, while another thread is
displaying the data as it arrives.
7
When to Use Threads
A common application for multithreading is performing time-consuming tasks in the background.
The main thread keeps running, while the worker thread does its background job. With Windows
Forms or WPF applications, if the main thread is tied up performing a lengthy operation,
keyboard and mouse messages cannot be processed, and the application becomes unresponsive.
For this reason, it’s worth running time-consuming tasks on worker threads even if the main
thread has the user stuck on a “Processing… please wait” modal dialog in cases where the
program can’t proceed until a particular task is complete. This ensures the application doesn’t get
tagged as “Not Responding” by the operating system, enticing the user to forcibly end the process
in frustration! The modal dialog approach also allows for implementing a "Cancel" button, since
the modal form will continue to receive events while the actual task is performed on the worker
thread. The BackgroundWorker class assists in just this pattern of use.
In the case of non-UI applications, such as a Windows Service, multithreading makes particular
sense when a task is potentially time-consuming because it’s awaiting a response from another
computer (such as an application server, database server, or client). Having a worker thread
perform the task means the instigating thread is immediately free to do other things.
Another use for multithreading is in methods that perform intensive calculations. Such methods
can execute faster on a multi-processor computer if the workload is divided amongst multiple
threads. (One can test for the number of processors via the Environment.ProcessorCount
property).
A C# application can become multi-threaded in two ways: either by explicitly creating and
running additional threads, or using a feature of the .NET framework that implicitly creates
threads – such as BackgroundWorker, thread pooling, a threading timer, a Remoting server, or a
Web Services or ASP.NET application. In these latter cases, one has no choice but to embrace
multithreading. A single-threaded ASP.NET web server would not be cool – even if such a thing
were possible! Fortunately, with stateless application servers, multithreading is usually fairly
simple; one's only concern perhaps being in providing appropriate locking mechanisms around
data cached in static variables.
When Not to Use Threads
Multithreading also comes with disadvantages. The biggest is that it can lead to vastly more
complex programs. Having multiple threads does not in itself create complexity; it's the
interaction between the threads that creates complexity. This applies whether or not the
interaction is intentional, and can result long development cycles, as well as an ongoing
susceptibility to intermittent and non-reproducable bugs. For this reason, it pays to keep such
interaction in a multi-threaded design simple – or not use multithreading at all – unless you have
a peculiar penchant for re-writing and debugging!
Multithreading also comes with a resource and CPU cost in allocating and switching threads if
used excessively. In particular, when heavy disk I/O is involved, it can be faster to have just one
or two workers thread performing tasks in sequence, rather than having a multitude of threads
each executing a task at the same time. Later we describe how to implement a
Producer/Consumer queue, which provides just this functionality.
8
Creating and Starting Threads
Threads are created using the Thread class’s constructor, passing in a ThreadStart delegate –
indicating the method where execution should begin. Here’s how the ThreadStart delegate is
defined:
public delegate void ThreadStart();
Calling Start on the thread then sets it running. The thread continues until its method returns, at
which point the thread ends. Here’s an example, using the expanded C# syntax for creating a
TheadStart delegate:
class ThreadTest {
static void Main() {
Thread t = new Thread (new ThreadStart (Go));
t.Start(); // Run Go() on the new thread.
Go(); // Simultaneously run Go() in the main thread.
}
static void Go() { Console.WriteLine ("hello!"); }
In this example, thread t executes Go() – at (much) the same time the main thread calls Go(). The
result is two near-instant hellos:
hello!
hello!
A thread can be created more conveniently using C#'s shortcut syntax for instantiating delegates:
static void Main() {
Thread t = new Thread (Go); // No need to explicitly use ThreadStart
t.Start();
...
}
static void Go() { ... }
In this case, a ThreadStart delegate is inferred automatically by the compiler. Another shortcut
is to use an anonymous method to start the thread:
static void Main() {
Thread t = new Thread (delegate() { Console.WriteLine ("Hello!"); });
t.Start();
}
A thread has an IsAlive property that returns true after its Start() method has been called, up
until the thread ends.
A thread, once ended, cannot be re-started.

Monday, 24 February 2014

Here you'll learn how to create a PDF File using C#

 learn how to create a PDF File using C#




steps are as below:



void CreatePDF()
    {
        try
        {


            string path = Server.MapPath("Attatchment PDF");
        /*Logo Path*/
            string Invoiceid = ;
        string strLogoPath = Server.MapPath("Image") + "\\jayendra.jpg";
        Document doc = new Document(PageSize.LETTER, 25F, 25F, 50F, 25F);
        PdfWriter.GetInstance(doc, new FileStream(path + "/Font.pdf", FileMode.Create));
        doc.Open();
      iTextSharp.text.Rectangle page = doc.PageSize;
        iTextSharp.text.Font Verdana = FontFactory.GetFont("Verdana", 10F, iTextSharp.text.Font.NORMAL,iTextSharp.text.Color.BLACK);
        PdfPTable table = new PdfPTable(2);
        table.TotalWidth = page.Width;
        PdfPCell cell = new PdfPCell();
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(strLogoPath);
        AddImageInCell(cell, image, 200f, 200f, 1);
        cell.Border = 0;
        AddtextCell(table, cell, 0, 0, 0);
        PdfPCell cell2 = new PdfPCell();
        PdfPTable table2 = new PdfPTable(1);
        PdfPCell line_2 = new PdfPCell(new Phrase("Name: Gohil Jayendrasinh F", Verdana));
        AddtextCell(table2, line_2);
        PdfPCell line_3 = new PdfPCell(new Phrase("Email: jayendrasinhgohil@gmail.com", Verdana));
        AddtextCell(table2, line_3);
        PdfPCell line_4 = new PdfPCell(new Phrase("Compny Name: SIGMASOLVE LLC", Verdana));
        AddtextCell(table2, line_4);
        cell2.AddElement(table2);
        cell2.Border = 0;
        AddtextCell(table, cell2, 0, 0, 0);
        doc.Add(table);
        doc.Close();
        }
        catch (Exception)
        {

            throw;
        }
    }


     private static void AddImageInCell(PdfPCell cell, iTextSharp.text.Image image,float fitWidth,float fitHight,int Alignment)
    {
        image.ScaleToFit(fitWidth, fitHight);
        image.Alignment = Alignment;
        cell.AddElement(image);
    }
    private void AddtextCell(PdfPTable table, PdfPCell cell)
    {
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
        cell.Border = 0;
        table.AddCell(cell);
    }
    private void AddtextCell(PdfPTable table, PdfPCell cell, float paddingLeft,float paddingRight)
    {
        cell.Colspan = 3;
        cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
        cell.PaddingLeft = paddingLeft;
        cell.PaddingRight = paddingRight;
        cell.Border = 0;
        table.AddCell(cell);
    }
    private void AddtextCell(PdfPTable table, PdfPCell cell, float paddingLeft, float paddingRight,int hAlign)
    {
        cell.Colspan = 3;
        cell.HorizontalAlignment = hAlign; //0=Left, 1=Centre, 2=Right
        cell.PaddingLeft = paddingLeft;
        cell.PaddingRight = paddingRight;
        cell.Border = 0;
        table.AddCell(cell);
    }
    private static void AddtextCell(PdfPTable table, PdfPCell cell, int Colspan, int HorizontalAlignment, int Border)
    {
        cell.Colspan = Colspan;
        cell.HorizontalAlignment = HorizontalAlignment; //0=Left, 1=Centre, 2=Right
        cell.Border = Border;
        table.AddCell(cell);
    }


After write these methods and events call these where you want to create PDF file.


Check out my other Blogs Here:click on this link:


http://integratedskillsofdotnet.blogspot.in/
http://computerknowledgehacking.blogspot.in/