Posted on

c# and shadow copy – notes on library AlphaVSS

AlphaVSS

AlphaVSS is a .NET class library providing a managed API for the Volume Shadow Copy Service also known as VSS

Error loading library AlphaVSS.x64.dll

if you have error loading the library probabilly you need to install on the machine the Visual C++ 2017 Redist package.

You can find it at this link

Control shadow copy

To control shadow copy, created using alphavss library, you have to open a command prompt whith administrative priviliges and type

vssadmin

to list your shadow copy you have to type :

vssadmin list shadows

 

Posted on

Configure a Point-to-Site VPN connection via Openvpn on Azure

Create a virtual network

  1. Sign in to the Azure portal.
  2. In Search resources, service, and docs , type virtual network.
  3. On the Virtual Network page, select Create.
  4. On the IP Addresses tab, configure the values

Subnet: If you use the default address space, a default subnet is created automatically.

  • Subnet name: In this example, we named the subnet “FrontEnd”.
  • Subnet address range: The address range for this subnet.

On the Security tab, at this time, leave the default values:

  • DDos protection: Basic
  • Firewall: Disabled

So we will have this configuration (as example) :

  • Address space: 10.1.0.0/16
    Subnet name: FrontEnd
  • Subnet address range: 10.1.0.0/24

Create a virtual network gateway

  1. In the Search the Marketplace field, type ‘Virtual Network Gateway’

SKU: Select the gateway SKU from the dropdown. For Openvpn you need to select VpnGw1 because

Gateway subnet address range: This field only appears if your VNet doesn’t have a gateway subnet. If possible, make the range /27 or larger (/26,/25 etc.)

In this example :

GatewaySubnet: 10.1.1.0/27

Certificates

Certificates are used by Azure to authenticate clients connecting to a VNet over a Point-to-Site VPN connection. You have two options : use a root certificate that was generated with an enterprise solution (recommended), or generate a self-signed certificate.

Generate and export certificates for Point-to-Site using PowerShell

Two steps : generate root certificate; generate client certificate.

root certificate

From a computer running Windows 10 or Windows Server 2016, open a Windows PowerShell console in Admin mode.

Use the following example to create the self-signed root certificate. The following example creates a self-signed root certificate named ‘TestVPNRootCert’ that is automatically installed in ‘Certificates-Current User\Personal\Certificates’.

$cert = New-SelfSignedCertificate -Type Custom -KeySpec Signature -Subject "CN=TestVPNRootCert" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -KeyUsageProperty Sign -KeyUsage CertSign

You can view the certificate by opening certmgr.msc, or Manage User Certificates.

client certificate

Each client computer that connects to a VNet using Point-to-Site must have a client certificate installed. You generate a client certificate from the self-signed root certificate.

From a computer running Windows 10 or Windows Server 2016, open a Windows PowerShell console in Admin mode. Identify the self-signed root certificate that is installed on the computer. This cmdlet returns a list of certificates that are installed on your computer.

Get-ChildItem -Path "Cert:\CurrentUser\My"

As output you will see a string and a name for every certificate installed on your machine.

For example :

AED812AD883826FF76B4D1D5A77B3C08EFA79F3F CN=MyOldVPNRootCert

7181AA8C1B4D34EEDB2F3D3BEC5839F3FE52D655 CN=TestVPNRootCert

Declare a variable for the root certificate using the string from the previous step:

$cert = Get-ChildItem -Path “Cert:\CurrentUser\My\7181AA8C1B4D34EEDB2F3D3BEC5839F3FE52D655”

Modify and run the example to generate a client certificate. The result of the following example is a client certificate named ‘TestVPNClientCert’

New-SelfSignedCertificate -Type Custom -DnsName TestVPNClientCert -KeySpec Signature  -Subject "CN=TestVPNClientCert" -KeyExportPolicy Exportable  -HashAlgorithm sha256 -KeyLength 2048  -CertStoreLocation "Cert:\CurrentUser\My"  -Signer $cert -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2")

The client certificate that you generate is automatically installed in ‘Certificates – Current User\Personal\Certificates’ on your computer.

Export the root certificate public key (.cer)

To obtain a .cer file from the certificate, open Manage user certificates. Locate the self-signed root certificate, typically in ‘Certificates – Current User\Personal\Certificates’, and right-click. Click All Tasks, and then click Export. This opens the Certificate Export Wizard.

Select No, do not export the private key, and then click Next

On the Export File Format page, select Base-64 encoded X.509 (.CER)., and then click Next.

For File to ExportBrowse to the location to which you want to export the certificate. For File name, name the certificate file. Then, click Next.

Click Finish to export the certificate. You’ll find a file .cer in location selected.

Export the client certificate

To export a client certificate, open Manage user certificates. The client certificates that you generated are, by default, located in ‘Certificates – Current User\Personal\Certificates’. Right-click the client certificate that you want to export, click all tasks, and then click Export to open the Certificate Export Wizard.

Select Yes, export the private key, and then click Next. IMPORTANT!!!!

On the Export File Format page, leave the defaults selected. Make sure that Include all certificates in the certification path if possible is selected

On the Security page, you must protect the private key, using a password.

On the File to ExportBrowse to the location to which you want to export the certificate. For File name, name the certificate file. Then, click Next.Click Finish to export the certificate.

Add the client address pool

The client address pool is a range of private IP addresses that you specify. The clients that connect over a Point-to-Site VPN dynamically receive an IP address from this range. Use a private IP address range that does not overlap with the on-premises location that you connect from, or the VNet that you want to connect to.

Open virtual network gateway configuration page, navigate to the Settings section of the virtual network gateway page. In the Settings section, select Point-to-site configuration. Select Configure now to open the configuration page.

In the Address pool box, add the private IP address range that you want to use. VPN clients dynamically receive an IP address from the range that you specify.

For example : 172.16.0.0/24

Tunnel Type : OpenVpn

Authentication Type : Azure certificate

In root certificate section you have to put the root certificate name (in this example TestVPNRootCert).

Open the root certificate file (.cer) with a text editor, such as Notepad. Copy the text as in image and past it in “Public certificate data”

Save Point to Site Configuration.

Download vpn Client clicking on “Download vpn Client” 🙂

Install Openssl

https://slproweb.com/products/Win32OpenSSL.html

Extract the private key and the base64 thumbprint from the .pfx client certificate.

Using OpenSSL on your machine is one way. The profileinfo.txt file contains the private key and the thumbprint for the CA and the Client certificate

openssl pkcs12 -in “C:\myfolder\clientcert_vpn_test.pfx” -nodes -out “C:\myfolder\profileinfo.txt”

Configure openvpn client

Unzip the profile downloaded from virtual network point to site configuration. Next, open the vpnconfig.ovpn configuration file from the OpenVPN folder using Notepad. Open profileinfo.txt in Notepad and copy and paste in vpnconfig.ovpn the sections :

# P2S client certificate
# please fill this field with a PEM formatted cert
<cert>
$CLIENTCERTIFICATE
</cert>
# P2S client root certificate private key
# please fill this field with a PEM formatted key
<key>
$PRIVATEKEY
</key>

IMPORTANT :certificate and kay need to be insert in  openvpncon with  —- begin — and —-end —–

 


Posted on

Authentication Developing for Azure Media Service

After creation of your Azure Media Service (AMS) Account (Create a Media Services account using the Azure portal) you need to authenticate your application that your are developing , to manage your video and streaming channels.


Developing with .net

In this article we are using .net framework to develop an app, but the information should be valid for all languages.

To develop an application with .net frameeork, you need to install, via nuget , the package windowsazure.mediaservices.extensions with its derived packages.


You can authenticate in one of two ways :

User authentication

Authenticates a person who is using the app to interact with Azure Media Services resources. The interactive application should first prompt the user for credentials.

For this authentication your app needs two strings :

Azure AD tenant  (“tenant” in example) :  In Azure portal, select your AMS and  select, on the left menu, api page. In the table at the bottom of the page one of the fields is “Domain Tenant ADD”.

Endpoint API REST (“endpoint” in example) : you can read this information directly in main page of your AMS on the right at the top of the page. Should be something like this :

https://yourams.restv2.yourlocation.media.azure.net/api/

In your application you have to write this code :

var tokenCredentials = new AzureAdTokenCredentials(tenant, AzureEnvironments.AzureCloudEnvironment);
var tokenProvider = new AzureAdTokenProvider(tokenCredentials);
_context = new CloudMediaContext(new Uri(endpoint), tokenProvider);

Running the application you should automatically see the Microsoft user credentials form

 

Service principal authentication

Authenticates a service, a specific app, without user interaction. To use this authenticaton in your app, you need four strings :

Azure AD tenant  (“tenant” in example) : As above

Endpoint API REST (“endpoint” in example) : As above

Client ID (“clientid” in example) : Enter in azure portal and look for “applications”. Add new application. After creation, in properties, at the top of the page, you can find the “application ID”.

Client Secret (“secretid” in example): in your AMS select the API page. In the middle of page you can find a little form with two fields. In the first field you ha to select the application created before. Use the second field to create the client secret.

In your application you have to write this code :

AzureAdTokenCredentials tokenCredentials =
new AzureAdTokenCredentials(tenant,
new AzureAdClientSymmetricKey(_clientid, _secreteid),
AzureEnvironments.AzureCloudEnvironment);

var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

_context = new CloudMediaContext(new Uri(endpoint), tokenProvider);
Posted on

installing sqlserver 2008: Performance counter registry hive consistency check failed

if, during installation of Sql Server 2008 you have this error : Performance counter registry hive consistency check failed

Open a command prompt with administrator user rights (Run as Administrator)

cd c;/windows/system32
lodctr /R:PerfStringBackup.INI

Restart the system and try again to install sqlserver

Posted on

Token based authentication in ASP.NET Web API

Token based authentication

Nella “Token based authentication”, l’applicazione client invia prima una richiesta all’endpoint del server di autenticazione con le credenziali dell’utente; se il nome utente e la password sono corretti, il server di autenticazione invia un token al client come risposta. Questo token contiene dati sufficienti per identificare un determinato utente e un tempo di scadenza. L’applicazione client utilizza quindi il token per accedere alle risorse nelle richieste successive fino a quando il token risulta ancora valido (non scaduto).

Classe per validare le richieste del client

Aggiungete una classe come questa :

using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Owin;


namespace Mysite.Helpers
{
    public class MysiteAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated(); // 
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            var user = await userManager.FindAsync(context.UserName, context.Password);
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
            OAuthDefaults.AuthenticationType);

            context.Validated(oAuthIdentity);
        }
    }
}

Per attivare questa classe andate nel file App_Start/Startup.Auth.cs e aggiungete alla fine del metodo ConfigureAuth questo codice

var myProvider = new  MysiteAuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

In cui si definisce il link http://mysite/token che restituisce un token di durata 1 giorno.

Dovrete aggiungere nel file il riferimento

using Microsoft.Owin.Security.OAuth;

E’ necessario aggiungere un metodo all’autenticazione. Andate nel file IdentityModel.cs e aggiungete questo metodo :

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager,
            string authenticationType)
        {
           var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
           return userIdentity;
        }

TEST CON POSTMAN

Per testare il tutto facilmente potete usare Postman .

Dovrete creare con Postman una chiamata post sul vostro link http://mysite/token. Nell’headers inserite la dicitura che vedete in figura :

Nel Body inserite il tipo di autneticazione (password) il vostro username e la vostra password.

Spingete “Send”. Se tutto ha funzionato riceverete il token

Utilizzo del Token

Una volta che il client ha ricevuto il token lo può utilizzare per tutte le successive operazioni senza dover passare lo username e la password: va passato solo il token che contiene queste informazioni. Facciamo una prova, creando un metodo che richiede autenticazione all’interno di un controller :

using System;
using System.Web.Http;

namespace MySite.Controllers
{
    public class SampleController : ApiController
    {
       [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            var identity = (ClaimsIdentity)User.Identity;
            return Ok("Hello " + identity.Name);
        }
   }
}

Usando postman, fate una chiamata GET al link : http://MySite/api/Sample/GetForAuhenticate

Dovrete passare al link il token che avete ottenuto qualche istante prima (nel nostro esempio è valido per 1 giorno). Per farlo in postman aggiungete la chiave Authorization con valore la parola Bearer seguita dal token.

THE END

Posted on

add Web API to an asp.net mvc site

Install the Web API Client Libraries

Use NuGet Package Manager to install the Web API Client Libraries package :

  • Microsoft.AspNet.WebApi.Client
  • Microsoft.AspNet.WebApi.Core
  • Microsoft.AspNet.WebApi.WebHost

Define a Web API Routing Configuration

Add App_Start\WebApiConfig.cs

using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    }
}

Register the WebAPI Routing Configuration

If you added a new WebApiConfig.cs file, you need to register that on your Web Application’s main configuration class.

Import namespace System.Web.Http in Global.asax.cs.

Add this line before the registration of your classic routing

//api routing (before)
GlobalConfiguration.Configure(WebApiConfig.Register);
//existing normal route
RouteConfig.RegisterRoutes(RouteTable.Routes);

Create a sample Web API Controller

Create a new controller

using System;
using System.Web.Http;

namespace MySite.Controllers
{
    public class SampleController : ApiController
    {
       [HttpGet]
       public String Test()
       {
         return "Hello World!";
       }
   }
}

Based on the api routing you should call this method in your browser using

http://MySite/api/Sample/Test

with this result

<string xmlns=”http://schemas.microsoft.com/2003/10/Serialization/”>Hello World!</string>

Posted on

Android java app with notification from asp.net mvc using firebase cloud messaging – part 3

Notification service in Android

Now we need to create in Android the service able to manage the notification incoming from firebase and to show these to user. Follow this usefull article Working easily with FCM push notifications in Android. You’ll have a class like this.

package com.mycompany.myfirstapp;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import androidx.core.app.NotificationManagerCompat;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

//is the class that we can find in the manifest as a service

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "MsgFirebaseServ";

    @Override


    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        String title = "";
        String body = "";
        String objectId = "";
        String objectType = "";

        if (remoteMessage.getData() != null) {
            title = remoteMessage.getData().get("title");
            body = remoteMessage.getData().get("body");
            objectId = remoteMessage.getData().get("object_id");
            objectType = remoteMessage.getData().get("objectType");
        }

        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle(title)
                .setContentText(body)
                .build();
        NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
        manager.notify(/*notification id*/0, notification);
    }
}

Run your app on your device

Follow this instruction : https://developer.android.com/training/basics/firstapp/running-app

First test using your app in your device

  • Run the app on your device or emulator. The app should had created a new register id for the device and send it to asp.net mvc site. Now the device is registered.
  • Open Firebase console, go down in the menu on the left. Open Cloud Messaging session : you should find the possibility to send notification to your device starting from this page. So you can test correct developing of above class.

Send notification from asp.net mvc to firebase

For backend developers. You should create a class to manage notification to firebase. Follow the article Firebase push notifications using a .NET Backend to prepare a class to manage the notification to Firebase.

Then prepare your notification test task in a controller. Something like this :

        public Task<bool> NoteAsync()
        {
            var device = db.RegisteredDevices.Where(d => d.ENABLED == true);
            string[] da = new string[device.Count()];
            int i = 0;
            foreach (RegDevice r in device)
            {
                da[i] = r.ID;
                i++;     
            }
            string serverkey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
            return FCMPushNotification.SendPushNotification(da,serverkey,"Title","body");
        }

Firebase messaging, where to get Server Key?

Click the Settings (Cog wheel) icon next to your project name at the top of the new Firebase Console, as per screenshot below:

  1. Click Project settings.
  2. Click on the Cloud Messaging tab.


Final test

Call the asp.net mvc method created. You should see a notification in your device.


Android java app with notification from asp.net mvc using firebase cloud messaging – part 1

Android java app with notification from asp.net mvc using firebase cloud messaging – part 2

Links



Posted on

Android java app with notification from asp.net mvc using firebase cloud messaging – part 2

In this scenario we looking to send the device registration id to a server with user data to save it in our database.

Token based authentication in ASP.NET Web API

For backend developers. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients. Follow the following article in order to implement Token based authentication using ASP.NET Web API 2. (Part 1 : Token based authentication in ASP.NET Web API)

To register the device you need a method like this

       [HttpPost]
       public HttpResponseMessage Register(string key)
        {
            
            var identity = (ClaimsIdentity)User.Identity;
            string message = "";
            if (!string.IsNullOrEmpty(key))
            {
                var userid = identity.GetUserId();
                RegDevice device = db.RegisteredDevices.Where(d => d.ID == key &&
                        d.USER == userid).FirstOrDefault();
                        if (device == null)
                        {
                            device = new RegDevice();
                            device.ID = key;
                            device.USER = userid;
                            db.RegisteredDevices.Add(device);
                            if (db.SaveChanges() > 0)
                                {
                                    return Request.CreateResponse(HttpStatusCode.OK);
                                }
                                else
                                {
                                    message = Vocabolario.ErrorInTemporaryStorage;
                                    //System.Diagnostics.Debug.WriteLine("PostServerLog. erore" + 
                                    message);
                                }
                        }  
            }
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "value");
            response.Content = new StringContent(message, Encoding.Unicode);
            return response;
        }

Bearer authentication on Java

For frontend developers. To authenticated in a asp.net mvc site, first of all you have to generate the token using the username and the password. The token will conserve all the user’s data more the validation time. We will use this token to talk to our server.

Getting a token is not a goal per se. It’s a necessary step to call a protected API. The token needs to be used to access a Web API. The way to do it is by setting the Authorization header to be “Bearer”, followed by a space, followed by the access token.

To generate the token you should use something like this :

package com.mycompany.myfirstapp;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import javax.net.ssl.HttpsURLConnection;

import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import java.io.InputStream;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONObject;
import org.apache.wink.json4j.JSONException;

import java.nio.charset.StandardCharsets;

import java.security.cert.Certificate;
import javax.net.ssl.SSLPeerUnverifiedException;

public class MyServer {

    private final static String BASE_URL = "https://www.mysite.com";
    private final static String TOKEN_ENDPOINT = BASE_URL + "/token";
    private final static String REGDEVICE_ENDPOINT = BASE_URL + "/api/Account/Register";

//pass username and password in this example
    public static String getToken(String user, String pwd) throws IOException, JSONException {
        byte[] postData = getRequestBodyForAccessToken(user,pwd);
        int postDataLength = postData.length;

        URL url = new URL(TOKEN_ENDPOINT);
        HttpsURLConnection requestConn = (HttpsURLConnection) url.openConnection();
        requestConn.setRequestMethod("POST");
        requestConn.setDoOutput(true);
        requestConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        try (DataOutputStream dos = new DataOutputStream(requestConn.getOutputStream())) {
            dos.write(postData);
        }

        if (requestConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            if (requestConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
                String serverURL = requestConn.getHeaderField("Location");
                System.err.println("Set the value of the server path to: " + serverURL);
            }
            System.err.println("Error in obtaining an access token. " + 
            requestConn.getResponseMessage());
        }

        String accessToken;
        try (InputStream tokenStream = requestConn.getInputStream()) {
            JSONObject tokenRes = new JSONObject(tokenStream);
            accessToken = (String) tokenRes.get("access_token");
        }
        return accessToken;
    }

    public static void RegisterNewDevice(String deviceKey, String atoken)
    {
        StringBuilder urlBuilder = new StringBuilder(REGDEVICE_ENDPOINT);
        urlBuilder.append("&key=").append(deviceKey);
        String pathWithQueryParams = urlBuilder.toString();
        
        InputStream restRegApiStream = null;
        try {
            HttpsURLConnection restRegApiConn = getRestApiConnection(pathWithQueryParams);
            addAuthenticationHeader(restRegApiConnn, atoken);
            restRegApiConn.setRequestMethod("POST");
            
            if (restRegApiConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                if (restRegApiConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    if (restRegApiConn.getHeaderField("www-authenticate").contains("invalid_token")) {
                       
                    }
                } else if (restRegApiConn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
                    
                }
                
            } else {
                restRegApiStream = restRegApiConn.getInputStream();
            }
        }
        catch(Exception ex)
        {

        }
    }

    private static HttpsURLConnection getRestApiConnection(String apiCall) throws IOException {
        URL restApiUrl = new URL(apiCall);
        HttpsURLConnection restApiURLConnection = (HttpsURLConnection) restApiUrl.openConnection();
        return restApiURLConnection;
    }

    private static void addAuthenticationHeader(HttpsURLConnection restApiURLConnection, String t) 
    {
        restApiURLConnection.setRequestProperty("Authorization", "Bearer " + t);
    }

    /**
     * Get the request body to be used for the POST request when requesting an access token.
     */
    private static byte[] getRequestBodyForAccessToken(String user, String pwd) {
        StringBuilder sb = new StringBuilder("grant_type=password");
        sb.append("&username=")
                .append(user)
                .append("&password=")
                .append(pwd);
        return sb.toString().getBytes(StandardCharsets.UTF_8);
    }

    private static void print_https_cert(HttpsURLConnection con){

        if(con!=null){

            try {

                System.out.println("Response Code : " + con.getResponseCode());
                System.out.println("Cipher Suite : " + con.getCipherSuite());
                System.out.println("\n");

                Certificate[] certs = con.getServerCertificates();
                for(Certificate cert : certs){
                    System.out.println("Cert Type : " + cert.getType());
                    System.out.println("Cert Hash Code : " + cert.hashCode());
                    System.out.println("Cert Public Key Algorithm : "
                            + cert.getPublicKey().getAlgorithm());
                    System.out.println("Cert Public Key Format : "
                            + cert.getPublicKey().getFormat());
                    System.out.println("\n");
                }

            } catch (SSLPeerUnverifiedException e) {
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            }

        }

    }

    private static void print_content(HttpsURLConnection con){
        if(con!=null){

            try {

                System.out.println("****** Content of the URL ********");
                BufferedReader br =
                        new BufferedReader(
                                new InputStreamReader(con.getInputStream()));

                String input;

                while ((input = br.readLine()) != null){
                    System.out.println(input);
                }
                br.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}

So now you have registered the device on the server. It’s time to send notification to your device


Android java app with notification from asp.net mvc using firebase cloud messaging – part 1

Android java app with notification from asp.net mvc using firebase cloud messaging – part 3

Links