How-to-send-IOS-Iphone-push-notification-from-server-side-using-push-sharp-in-asp.net-csharp

using Newtonsoft.Json.Linq; using PushSharp.Apple; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;

namespace IOSPUshNotificationDemo12 { public partial class Demo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {

}

protected void btnSendNotification_Click(object sender, EventArgs e)
{
if(txtDeviceToken.Text!=”” && txtMessage.Text!=””)
{
SendPushNotification(txtDeviceToken.Text, txtMessage.Text);
}
}

private void SendPushNotification(string deviceToken,string message)
{
try
{

//Get Certificate
var appleCert = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(“~/Files/Certificate/IOS/Production_Certificate.p12”));

// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, “1234567890”);

// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);

// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{

aggregateEx.Handle(ex =>
{

// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;

// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
string desc = $”Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}”;
Console.WriteLine(desc);
lblStatus.Text = desc;
}
else
{
string desc = $”Apple Notification Failed for some unknown reason : {ex.InnerException}”;
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine(desc);
lblStatus.Text = desc;
}

// Mark it as handled
return true;
});
};

apnsBroker.OnNotificationSucceeded += (notification) =>
{
lblStatus.Text = “Apple Notification Sent successfully!”;
};

var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
{
// Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
};

// Start Proccess
apnsBroker.Start();

if (deviceToken != “”)
{
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse((“{\”aps\”:{\”badge\”:1,\”sound\”:\”oven.caf\”,\”alert\”:\”” + (message + “\”}}”)))
});
}

apnsBroker.Stop();

}
catch (Exception)
{

throw;
}
}
}

Here is youtube link

 

 

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);
                    }
                }
            }
        }
    }
}