How to install a SSL certificate on IIS 10

SSL installation in IIS 10 requires one certificate file with the .p7b (or .cer) file extension. You may either download the issued certificate in the email delivered by Comodo or download it in your SSLs.com account following these instructions.

In order to install the certificate, please follow the steps below.

  1. Press Win + R and type “inetmgr” in the appeared window to run the Internet Information Services (IIS) Manager.
  2. On the IIS Manager home page, locate the “Server Certificates” icon and double-click it:
  3. Locate the “Actions” panel on the right side and click “Complete Certificate Request”:

4. In the “Specify Certificate Authority Response” window, perform the actions below.

a) In the “File name containing the certification authority’s response” field, browse the file system to select your .p7b (or .cer) certificate.
b) In the “Friendly name” field, specify any name that will help you to identify the certificate among other files. It is best to submit the actual domain name of the certificate.
c) In the “Select a certificate store for the new certificate” field, leave the default value “Personal”.

5. Click “OK” to import the certificate to the server storage.

6. Once the import is completed, in the “Server Certificates” window, you will see a new entry associated with the imported certificate:

7. Assign the certificate to your website by expanding the “Sites” subsection in the “Connections” menu on the left and select the corresponding site. Then, in the “Actions” panel on the right side, locate the “Edit Site” menu and select the “Bindings” option:

8. On the right side of the “Site Bindings” window, click “Add”:

9. In the “Add Site Binding” window, modify the fields as below:

a) In the “Type” field, select “https”.

b) In the “IP address” field, select your website’s IP address or “All Unassigned”.

c) In the “Port” field, specify “443” (default).

d) In the “SSL certificate” field, select the previously imported certificate, which can be identified by the friendly name:

NOTE: The “Require Server Name Indication” box needs to be checked if there are multiple SSL certificates on the server.

10. Click “OK” in order for the new “https” entry to appear in the “Site Bindings” window:

That’s all – the certificate should now be installed and the website should be accessible via HTTPS.

The SSL installation status can be checked online via the SSL checker at https://decoder.link/sslchecker.

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