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

 

 

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