Sunday, 11 December 2011

SharpZipLib

SharpZipLib is a .NET compression library that supports Zip files using both stored and deflate compression methods, PKZIP 2.0 style and AES encryption, tar with GNU long filename extensions, gzip, zlib and raw deflate, as well as BZip2.

#ziplib (SharpZipLib, formerly NZipLib) is a Zip, GZip, Tar and BZip2 library written entirely in C# for the .NET platform. It is implemented as an assembly (installable in the GAC), and thus can easily be incorporated into other projects (in any .NET language). The creator of #ziplib put it this way: "I've ported the zip library over to C# because I needed gzip/zip compression and I didn't want to use libzip.dll or something like this. I want all in pure C#."

How to create a Zip File

FastZip fastZip = new FastZip();

 bool recurse = true;  // Include all files by recursing through the directory structure
 string filter = null; // Dont filter any files at all
 fastZip.CreateZip("fileName.zip", @"C:\SourceDirectory", recurse, filter);

 Using the fileFilter parameter

If the file filter is not a null string, it is interpreted as a regular expression which is tested against each file name.

For example, a fileFilter value of 'txt' would match with 'Test.txt' but would also match with 'SometxtFile.doc'. To match with '.txt' you would need to add a a dot, but even then a filter of ".txt" would be interpreted as [any-character]txt. You need to add an escape character "\" before the dot to specify it as a literal match. However, in my tests doing a single \ didn't seem to work, I needed to add a second \.

Note that "\.txt" would still match a file such as "file.txtold" or "file.txt.old", so you can append the $ specifier which matches with the end of the string: e.g "\.txt$" to ensure you only match files with the last extension as .txt

FastZip fastZip = new FastZip();

 bool recurse = true;  // Include all files by recursing through the directory structure
 string filter = @"\\.txt$"; // Only files ending in ".txt"
 fastZip.CreateZip("fileName.zip", @"C:\SourceDirectory", recurse, filter);

Create a zip with FastZip using progress events

You can set events which will fire on each file. This gives you the opportunity to display a progress notification, and to decide whether to include each file.

using System;
using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

private int _uptoFileCount;
private int _totalFileCount;

public void TestFastZipCreate(string backupFolderPath) {

 _totalFileCount = FolderContentsCount(backupFolderPath);

 FastZipEvents events = new FastZipEvents();
 events.ProcessFile = ProcessFileMethod;
 FastZip fastZip = new FastZip(events);

 fastZip.CreateEmptyDirectories = true;

 string zipFileName = Directory.GetParent(backupFolderPath).FullName + "\\ZipTest.zip";

 fastZip.CreateZip(zipFileName, backupFolderPath, true, "");
}

private void ProcessFileMethod(object sender, ScanEventArgs args) {
 _uptoFileCount ++;
 int percentCompleted = _uptoFileCount * 100 / _totalFileCount;
 // do something here with a progress bar
 // file counts are easier as sizes take more work to calculate, and compression levels vary by file type

 string fileName = args.Name;
 // To skip this file, set args.ContinueRunning = false
 // Only include files ending in ".txt"
 if (!fileName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
  args.ContinueRunning = false;
}

// Returns the number of files in this and all subdirectories
private int FolderContentsCount(string path) {
 int result = Directory.GetFiles(path).Length;
 string[ ] subFolders = Directory.GetDirectories(path);
 foreach (string subFolder in subFolders) {
  result += FolderContentsCount(subFolder);
 }
 return result;
}

How to extract a Zip File using FastZip

C#
using System;
using ICSharpCode.SharpZipLib.Zip;

public void TestFastZipUnpack(string zipFileName, string targetDir) {

 FastZip fastZip = new FastZip();
 string fileFilter = null;

 // Will always overwrite if target filenames already exist
 fastZip.ExtractZip(zipFileName, targetDir, fileFilter);
}

VB
Imports ICSharpCode.SharpZipLib.Zip

Public Sub TestFastZipUnpack(ByVal zipFileName As String, ByVal targetDir As String)

 Dim fastZip As FastZip = New FastZip()
 Dim fileFilter As String = Nothing

 fastZip.ExtractZip(zipFileName, targetDir, fileFilter)
End Sub

How to extract a Zip File using FastZip with Name Filter and Confirm Overwrite

C#
using System;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

private bool _stop;

public void TestFastZipUnpack(string zipFileName, string targetDir) {

 // Set the method that will be called on each file before extraction but after the OverwritePrompt (if applicable)
 FastZipEvents events = new FastZipEvents();
 events.ProcessFile = ProcessFileMethod;
 FastZip fastZip = new FastZip(events);

 // To conditionally extract files in FastZip, use the fileFilter and directoryFilter arguments.
 // The filter is a list of regex values separated with semi-colon. An entry starting with - is an exclusion.
 // See the NameFilter class for more details.
 // The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'
 string fileFilter = @"+\.dat$;-^dummy\.dat$";
 string directoryFilter = null;
 bool restoreDateTime = true;

 // Will prompt to overwrite if target filenames already exist
 fastZip.ExtractZip(zipFileName, targetDir, FastZip.Overwrite.Prompt, OverwritePrompt,
    fileFilter, directoryFilter, restoreDateTime);
}

private bool OverwritePrompt(string fileName) {

 // In this method you can choose whether to overwrite a file.
 DialogResult dr = MessageBox.Show("Overwrite " + fileName, "Overwrite?", MessageBoxButtons.YesNoCancel);
 if (dr == DialogResult.Cancel) {
  _stop = true;
  // Must return true if we want to abort processing, so that the ProcessFileMethod will be called.
  // When the ProcessFileMethod sets ContinueRunning false, processing will immediately stop.
  return true;
 }
 return dr == DialogResult.Yes;
}

private void ProcessFileMethod(object sender, ScanEventArgs args) {

 string fileName = args.Name;
 // To stop all further processing, set args.ContinueRunning = false
 if (_stop) {
  args.ContinueRunning = false;
 }
}

VB
Imports ICSharpCode.SharpZipLib.Zip
Imports ICSharpCode.SharpZipLib.Core
Imports System.Windows.Forms

Dim _stop As Boolean

Public Sub TestFastZipUnpack(ByVal zipFileName As String, ByVal targetDir As String)

 Dim events As FastZipEvents = New FastZipEvents()
 events.ProcessFile = AddressOf ProcessFileMethod
 Dim fastZip As FastZip = New FastZip(events)

 ' The only way to conditionally extraxt files in FastZip is to use the fileFilter and directoryFilter arguments.
 ' The filter is a list of regex values separated with semi-colon. An entry starting with - is an exclusion.
 ' See the NameFilter class for more examples.
 ' The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'
 Dim fileFilter As String = "+\.dat$;-^dummy\.dat$"
 Dim directoryFilter As String = Nothing
 Dim restoreDateTime As Boolean = True

 ' Will prompt to overwrite if target filenames already exist
 fastZip.ExtractZip(zipFileName, targetDir, fastZip.Overwrite.Prompt, AddressOf OverwritePrompt, _
       fileFilter, directoryFilter, restoreDateTime)
End Sub

Private Function OverwritePrompt(ByVal fileName As String) As Boolean

 ' In this method you can choose whether to overwrite a file.
 Dim dr As DialogResult = MessageBox.Show("Overwrite " + fileName, "Overwrite?", MessageBoxButtons.YesNoCancel)
 If (dr = DialogResult.Cancel) Then
  _stop = True
  ' Must return true if we want to abort processing, so that the ProcessFileMethod will be called.
  ' When the ProcessFileMethod sets ContinueRunning false, processing will immediately stop.
  Return True
 End If
 Return dr = DialogResult.Yes
End Function

Private Sub ProcessFileMethod(ByVal sender As Object, ByVal args As ScanEventArgs)

 Dim fileName As String = args.Name
 ' To stop all further processing, set args.ContinueRunning = false
 If (_stop) Then
  args.ContinueRunning = False
 End If

End Sub 

Download

Saturday, 10 December 2011

Json.NET

Json.NET is a popular high-performance JSON framework for .NET

Features

-Flexible JSON serializer to convert .NET objects to JSON and back again
-LINQ to JSON for manually reading and writing JSON
-High performance, faster than .NET's built-in JSON serializers
-Writes indented, easy to read JSON
-Convert JSON to and from XML
-Supports Silverlight and Windows Phone

The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class. The serializer automatically reads and writes JSON for the class.

LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects. LINQ to JSON allows you to easily read, create and modify JSON in .NET.

NuGet

Download Json.NET from CodePlex or install using NuGet

for more information please visit click me

DotNetZip - Zip and Unzip in C#, VB, any .NET language

DotNetZip is an easy-to-use, FAST, FREE class library and toolset for manipulating zip files or folders. Zip and Unzip is easy: with DotNetZip, .NET applications written in VB, C# - any .NET language - can easily create, read, extract, or update zip files. For Mono or MS .NET.

DotNetZip is the best ZIP library for .NET



DotNetZip is a 100% managed code library that can be used in any .NET application - Console, Winforms, WPF, ASP.NET, Sharepoint, Web services apps, and so on. New for v1.9.1.6: Silverlight. It can also be used from scripting environments or COM-capable environments like Powershell scripts, VBScript, VBA, VB6, PHP, Perl, Javascript, and more. Whatever environment it is used from, DotNetZip produces zip files that are fully interoperable with Windows Explorer, as well as Java applications, apps running on Linux.

It is designed to be simple and easy to use. DotNetZip is packaged as a single DLL, about 400k in size. It has no third-party dependencies. It is Medium Trust, so can be used on most hosters. Get zipping just by referencing the DLL. The library supports zip passwords, Unicode, ZIP64, stream input and output, AES encryption, multiple compression levels, self-extracting archives, spanned archives, and more.

DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment. DotNetZip supports these scenarios:
- a Silverlight app that dynamically creates zip files.
- an ASP.NET app that dynamically creates ZIP files and allows a browser to download them
- a Windows Service that periodically zips up a directory for backup and archival purposes
- a WPF program that modifies existing archives - renaming entries, removing entries from an archive, or adding new entries to an archive
- a Windows Forms app that creates AES-encrypted zip archives for privacy of archived content.
- a SSIS script that unzips or zips
- An administrative script in PowerShell or VBScript that performs backup and archival.
- a WCF service that receives a zip file as an attachment, and dynamically unpacks the zip to a stream for analysis
- an old-school ASP (VBScript) application that produces a ZIP file via the COM interface for DotNetZIp
- a Windows Forms app that reads or updates ODS files
- creating zip files from stream content, saving to a stream, extracting to a stream, reading from a stream
- creation of self-extracting archives.

If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952).

And the price for all this: totally FREE.


Example Usage
Here's some C# code that creates a zip file.
using (ZipFile zip = new ZipFile())
 {
     // add this map file into the "images" directory in the zip archive
     zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
     // add the report into a different directory in the archive
     zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
     zip.AddFile("ReadMe.txt");
     zip.Save("MyZipFile.zip");
 } 
 
Here is some VB code that unpacks a zip file (extracts all the entries):
  Dim ZipToUnpack As String = "C1P3SML.zip"  
   Dim TargetDir As String = "C1P3SML"  
   Console.WriteLine("Extracting file {0} to {1}", ZipToUnpack, TargetDir)   
   Using zip1 As ZipFile = ZipFile.Read(ZipToUnpack)   
       AddHandler zip1.ExtractProgress, AddressOf MyExtractProgress   
       Dim e As ZipEntry   
       ' here, we extract every entry, but we could extract    
       ' based on entry name, size, date, etc.   
       For Each e In zip1   
           e.Extract(TargetDir, ExtractExistingFileAction.OverwriteSilently)   
       Next  
   End Using 
 
For more infomation click here
 

Wednesday, 7 December 2011

jZebra

Free browser applet for sending raw commands to your printer
 
Usage 
 
<input type=button onClick="print()" value="Print">
<applet name="jZebra" code="jzebra.PrintApplet.class" archive="./jzebra.jar" 
 width="100" height="100">
      <param name="printer" value="zebra">
</applet>
<script>
      function print() {
         document.jZebra.append("A37,503,0,1,2,3,N,ABC WIDGET CO\n");
         document.jZebra.print();
      }
</script>
 
 

Features

  • Prints barcodes, receipts and more from a web page.
  • Supports thermal printers, label printers, magnetic cards.
  • 100% free and open source
  • Free to use in commercial applications (check license for details)
  • Seamlessly sends commands to your EPL2, ZPLII, CHR, ASCII, RAW, ESC/P printer (and more).
  • Compatible with Windows, Mac OS X, Ubuntu, Solaris (and more).
  • Tested with Firefox, Safari, Internet Explorer, Opera.
  • Supports COM, parallel, serial, USB, socket, lpr, LPT communication.
  • AJAX compatible by using JavaScript to control print jobs 

 

How It Works

  1. First, jZebra loads in your web browser as a Java applet (similar to a Flash or SilverLight object).
  2. Second, jZebra interfaces with browser interactively via JavaScript.
  3. Third, jZebra gains permission to use locally installed printers via digital signature prompt.
  4. Finally, jZebra spools directly to locally installed printers, allowing hundreds of print jobs to transfer seamlessly from web code to printer.