Create and extract a .zip file

How to: Compress and extract files

The System.IO.Compression namespace contains the following types for compressing and decompressing files and streams. You can also use these types to read and modify the contents of a compressed file:

The following examples show some of the functions you can perform when working with compressed files.

Example 1 – Create and extract a .zip file

The following example shows how to create and extract a compressed file that has a .zip file name extension by using the ZipFile class. It compresses the contents of a folder into a new .zip file and then extracts that content to a new folder. To use the ZipFile class, you must reference the System.IO.Compression.FileSystem assembly in your project.

C#
using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string startPath = @"c:\example\start";
            string zipPath = @"c:\example\result.zip";
            string extractPath = @"c:\example\extract";

            ZipFile.CreateFromDirectory(startPath, zipPath);

            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}

Example 2 – Extract specific file extensions

The next example shows how to iterate through the contents of an existing .zip file and extract files that have a .txt extension. It uses the ZipArchiveclass to access an existing .zip file, and the ZipArchiveEntry class to inspect the individual entries in the compressed file. It uses an extension method (ExtractToFile) for the ZipArchiveEntry object. The extension method is available in the System.IO.Compression.ZipFileExtensions class. To use the ZipFileExtensions class, you must reference the System.IO.Compression.FileSystem assembly in your project.

Important

When unzipping files, you must look for malicious file paths which can escape out of the directory where you want to unzip into. This is known as a path traversal attack.

The following example demonstrates how to check for malicious file paths and provides a safe way to unzip:

C#
using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string zipPath = @"c:\example\start.zip";

            Console.WriteLine("Provide path where to extract the zip file:");
            string extractPath = Console.ReadLine();
            
            // Normalizes the path.
            extractPath = Path.GetFullPath(extractPath);

            // Ensures that the last character on the extraction path
            // is the directory separator char. 
            // Without this, a malicious zip file could try to traverse outside of the expected
            // extraction path.
            if (!extractPath.EndsWith(Path.DirectorySeparatorChar))
                extractPath += Path.DirectorySeparatorChar;

            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                    {
                        // Gets the full path to ensure that relative segments are removed.
                        string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName));
 
                        // Ordinal match is safest, case-sensitive volumes can be mounted within volumes that
                        // are case-insensitive.
                        if (destinationPath.StartsWith(extractPath, StringComparison.Ordinal))
                            entry.ExtractToFile(destinationPath);                        
                    }
                }
            }
        }
    }
}

Example 3 – Add a new file to an existing .zip file

The following example uses the ZipArchive class to access an existing .zip file, and adds a new file to the compressed file. The new file gets compressed when you add it to the existing .zip file.

C#
using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}

Example 4 – Compress and decompress a directory of .gz files

You can also use the GZipStream and DeflateStream classes to compress and decompress data. They use the same compression algorithm. Compressed GZipStream objects that are written to a file that has an extension of .gz can be decompressed by using many common tools in addition to the methods provided by GZipStream. The following example shows how to compress and decompress a directory of files by using the GZipStreamclass:

C#
using System;
using System.IO;
using System.IO.Compression;

namespace zip
{
    public class Program
    {
        private static string directoryPath = @"c:\temp";
        public static void Main()
        {
            DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
            Compress(directorySelected);

            foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
            {
                Decompress(fileToDecompress);
            }
        }

        public static void Compress(DirectoryInfo directorySelected)
        {
            foreach (FileInfo fileToCompress in directorySelected.GetFiles())
            {
                using (FileStream originalFileStream = fileToCompress.OpenRead())
                {
                    if ((File.GetAttributes(fileToCompress.FullName) & 
                       FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                    {
                        using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
                        {
                            using (GZipStream compressionStream = new GZipStream(compressedFileStream, 
                               CompressionMode.Compress))
                            {
                                originalFileStream.CopyTo(compressionStream);

                            }
                        }
                        FileInfo info = new FileInfo(directoryPath + "\\" + fileToCompress.Name + ".gz");
                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                        fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
                    }

                }
            }
        }

        public static void Decompress(FileInfo fileToDecompress)
        {
            using (FileStream originalFileStream = fileToDecompress.OpenRead())
            {
                string currentFileName = fileToDecompress.FullName;
                string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

                using (FileStream decompressedFileStream = File.Create(newFileName))
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(decompressedFileStream);
                        Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
                    }
                }
            }
        }
    }
}

WCF Streaming Issue

Problem Statement

I have a WCF service hosted on IIS that gets called from a web application. The WCF service is used for uploading/downloading files to and from a server.

For files, less than 50 KB upload/download works. However – when the file size exceeds 50 KB, it fails. No error message is displayed on the client application.

 

Troubleshooting

Step 1: Collect and review WCF traces

We started with configuring the WCF verbose level tracing for the service and client (web app).

For more information on configuring WCF tracing please see the link – https://msdn.microsoft.com/en-us/library/ms733025%28v=vs.110%29.aspx

After the issue was reproduced, we found that no traces were generated for the Service, but we had a set of trace for the client application.

In the traces we could find the following.

 

<Exception>

<ExceptionType>System.ServiceModel.ProtocolException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>

<Message>The remote server returned an unexpected response: (413) Request Entity Too Large.</Message>

Since we did not have any WCF trace come up for the service, it seems that the request from client never made it to the WCF layer of the service and must have gotten blocked in the IIS itself.

 

Step 2: Check IIS Request filtering

The first thing I checked was “IIS Request Filtering” features setting for the WCF application.

To do this, open IIS Manager. Select your application.

In the Features view you will see “Request Filtering”.

Open this feature and on the right hand panel you will find “Edit Feature Settings”

 

Maximum Allowed Content Length is an Optional U-Int attribute.

It specifies the maximum length of content in a request, in bytes.  The default value is 30000000, which is approximately 28.6MB.

 

This value was already set to 28.6 MB for the customer, so we could be sure that this feature was not responsible for blocking the incoming upload/download requests.

 

Step 3: Check “UploadReadAheadSize” in IIS

 

After some research I found out there is a setting present in the IIS – “UploadReadAheadSize” that prevents upload and download of data greater than 49KB. The value present by default is 49152 bytes and can be increased up to 4 GB.

 

The UploadReadAheadSize property establishes the number of bytes a Web server will read into a buffer and pass to an ISAPI extension. This occurs once per client request. The ISAPI extension receives any additional data directly from the client. The range is from 0 to &HFFFFFFFF (4 GB).

For more details on this property please check the URL – https://msdn.microsoft.com/en-us/library/ms525310%28v=vs.90%29.aspx

 

To navigate to this setting, use the following steps:

  • Launch “Internet Information Services (IIS) Manager”
  • Expand the Server field
  • Expand Sites
  • Select the site your application is in.
  • In the Features section, double click “Configuration Editor”
  • Under “Section” select: system.webServer>serverRuntime

 

For my case, customer had maximum file size less than 50 MB, so we set it to 52428800 i.e. 50 MB.

Please note that the value is in Bytes.

 

This resolved the issue for us and file uploads and downloads worked fine.

 

How to get address from latitude and longitude

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());

addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

 

Reference :

https://stackoverflow.com/questions/9409195/how-to-get-complete-address-from-latitude-and-longitude

Validate credit card number with Mod 10 algorithm in C#

Introduction

All you know what information contains in your NIC number. But do you know what information contains in the Credit Card Number? Following article provides brief details about what information contain in your credit card and demonstrates to how to validate credit card number using mod 10 (Luhn) algorithms with C#.

Background

Card Length

Typically, credit card numbers are all numeric and the length of the credit card number is between 12 digits to 19 digits.
14, 15, 16 digits – Diners Club
15 digits – American Express
13, 16 digits – Visa
16 digits – MasterCard
For more information please refer http://en.wikipedia.org/wiki/Bank_card_number.

Hidden information

Major Industry Identifier (MII)

The first digit of the credit card number is the Major Industry Identifier (MII). It designates the category of the entry which issued the card.
1 and 2 – Airlines
3 – Travel
4 and 5 – Banking and Financial
6 – Merchandising and Banking/Financial
7 – Petroleum
8 – Healthcare, Telecommunications
9 – National Assignment

Issuer Identification Number

The first 6 digits are the Issuer Identification Number. It will identify the institution that issued the card. Following are some of the major IINs.
Amex – 34xxxx, 37xxxx
Visa – 4xxxxxx
MasterCard – 51xxxx – 55xxxx
Discover – 6011xx, 644xxx, 65xxxx

Account Number

Taking away the 6 identifier digits and the last digits, remaining digits are the person’s account number (7th and following excluding last digits)

Check digits

Last digit is known as check digits or checksum. It is used to validate the credit card number using Luhn algorithm (Mod 10 algorithm).
For more information refer: http://en.wikipedia.org/wiki/Bank_card_number andhttp://en.wikipedia.org/wiki/List_of_Issuer_Identification_Numbers.

Luhn algorithm (Mod 10)

The Luhn algorithm or Luhn formula, also known as the “modulus 10″ or “mod 10″ algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in US and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn. (http://en.wikipedia.org/wiki/Luhn_algorithm)
When you implementing eCommerce application, It is a best practice validating credit card number before send it to the bank validation.
Here are the Luhn steps which can used to validate the credit card number.

4 0 1 2 8 8 8 8 8 8 8 8 1 8 8 1

Step 1 – Starting with the check digit double the value of every other digit (right to left every 2nd digit)

Step 2 – If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.
Step 2
Step 3 – Now add the un-doubled digits to the odd places

Step 4 – Add up all the digits in this number

If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.
Using the code
Following code sample validates your credit card number against Mod 10.
Hide Copy Code
public static bool Mod10Check(string creditCardNumber)
{
//// check whether input string is null or empty
if (string.IsNullOrEmpty(creditCardNumber))
{
return false;
}

//// 1. Starting with the check digit double the value of every other digit
//// 2. If doubling of a number results in a two digits number, add up
/// the digits to get a single digit number. This will results in eight single digit numbers
//// 3. Get the sum of the digits
int sumOfDigits = creditCardNumber.Where((e) => e >= ‘0’ && e <= '9') .Reverse() .Select((e, i) => ((int)e – 48) * (i % 2 == 0 ? 1 : 2))
.Sum((e) => e / 10 + e % 10);

//// If the final sum is divisible by 10, then the credit card number
// is valid. If it is not divisible by 10, the number is invalid.
return sumOfDigits % 10 == 0;
}

————————————————————————————–

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ValidateCreditCard
{
class Program
{
static void Main(string[] args)
{
string[] cards = new string[] {
////http://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
//”378282246310005″, // American Express
//”4012888888881881″, // Visa
//”6011111111111117″, // Discover
//”4222222222222″, // Visa
//”76009244561″, // Dankort (PBS)
//”5019717010103742″, // Dakort (PBS)
//”6331101999990016″, // Switch/Solo (Paymentech)
//”30569309025904″, // Diners Club
////http://www.getcreditcardnumbers.com/
//”5147004213414803″, // Mastercard
//”6011491706918120″, // Discover
//”379616680189541″, // American Express
//”4916111026621797″, // Visa

“340931724562876”,//American Express
“30387628228509”,//Diners Club
“6011076572567331”,//Discover
“214997288618159”,//enRoute
“3088498025303152”,//JCB
“210054331070006”,//JCB 15 digit
“5131157941313628”,//MasterCard
“4532133451218182”,//Visa
“4716102585525”,//Visa 13 digit
“869945432670749”,//Voyager
};

foreach (string card in cards)
{
Console.WriteLine(IsValid(card));
}

Console.ReadLine();

Console.WriteLine(“******************************* Second Method ***********************************”);
Console.WriteLine(“Please enter your credit card number here:”);
var ccnumber = Console.ReadLine();
var results = Mod10Check(ccnumber);
if (results)
{
Console.WriteLine(“This Credit Card Number is valid!”);
}
else
{
Console.WriteLine(“Invalid Credit Card Number”);
}
Console.ReadLine();
}

public static bool IsValid(object value)
{
if (value == null)
{
return true;
}

string ccValue = value as string;
if (ccValue == null)
{
return false;
}
ccValue = ccValue.Replace(“-“, “”);
ccValue = ccValue.Replace(” “, “”);

int checksum = 0;
bool evenDigit = false;

// http://www.beachnet.com/~hstiles/cardtype.html
foreach (char digit in ccValue.Reverse())
{
if (digit < '0' || digit > ‘9’)
{
return false;
}

int digitValue = (digit – ‘0’) * (evenDigit ? 2 : 1);
evenDigit = !evenDigit;

while (digitValue > 0)
{
checksum += digitValue % 10;
digitValue /= 10;
}
}

return (checksum % 10) == 0;
}

public static bool Mod10Check(string creditCardNumber)
{
//http://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm

//// check whether input string is null or empty
if (string.IsNullOrEmpty(creditCardNumber))
{
return false;
}

//// 1. Starting with the check digit double the value of every other digit
//// 2. If doubling of a number results in a two digits number, add up
/// the digits to get a single digit number. This will results in eight single digit numbers
//// 3. Get the sum of the digits
int sumOfDigits = creditCardNumber.Where((e) => e >= ‘0’ && e <= '9') .Reverse() .Select((e, i) => ((int)e – 48) * (i % 2 == 0 ? 1 : 2))
.Sum((e) => e / 10 + e % 10);

//// If the final sum is divisible by 10, then the credit card number
// is valid. If it is not divisible by 10, the number is invalid.
return sumOfDigits % 10 == 0;
}

}
}

Regular Expression Password Validation

^ The password string will start this way
(?=.*[a-z]) The string must contain at least 1 lowercase alphabetical character
(?=.*[A-Z]) The string must contain at least 1 uppercase alphabetical character
(?=.*[0-9]) The string must contain at least 1 numeric character
(?=.*[!@#\$%\^&\*]) The string must contain at least one special character, but we are escaping reserved RegEx characters to avoid conflict
(?=.{8,}) The string must be eight characters or longer

WPF Enforce Single Instance Application

protected override void OnStartup(StartupEventArgs e)
{
// Single instance application logic

// Get Reference to the current Process
Process thisProc = Process.GetCurrentProcess();
// Check how many total processes have the same name as the current one
if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
{
// If ther is more than one, than it is already running.
MessageBox.Show(“Application is already running.”, “Error”, MessageBoxButton.OK, MessageBoxImage.Stop);
Application.Current.Shutdown();
return;
}

// End single instance application logic

base.OnStartup(e);

//////DXSplashScreen.Show<SplashScreenView>();
//Thread.Sleep(5000);
DevExpress.Xpf.Core.ApplicationThemeHelper.UpdateApplicationThemeName();

Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException1;

InitModules();
}