private void MainForm_Load(object sender, EventArgs e)
        {
            bool exists = ConfigurationManagerHelper.CheckConfigFileIsPresent();

            if (exists == false)
            {
                button1.Enabled = false;
                button2.Enabled = false;

                DisplayMessage.Error(this, "Configuration file not found. The application may not work.");
            }
            else
            {
                urlTemplate = ConfigurationManager.AppSettings["UrlTemplate"];

                if (urlTemplate != null)
                {
                    textBox6.Text = urlTemplate;
                }
                else
                {
                    button1.Enabled = false;
                    button2.Enabled = false;

                    DisplayMessage.Error(this, "Configuration file does not contain AppSettings key \"UrlTemplate\". The application may not work.");
                }
            }
        }
        private bool ValidateInput()
        {
            // INPUT DATA READING

            hubName      = textBox1.Text.Trim();
            hubNamespace = textBox2.Text.Trim();

            string str = textBox3.Text.Trim();

            ttl = TimeSpan.Zero;

            if (str != string.Empty && IsNumber(str))
            {
                switch (((ComboBoxItem <int>)comboBox1.SelectedItem).Value)
                {
                case 1:
                    ttl = TimeSpan.FromDays(int.Parse(str));
                    break;

                case 2:
                    ttl = TimeSpan.FromHours(int.Parse(str));
                    break;

                case 3:
                    ttl = TimeSpan.FromMilliseconds(int.Parse(str));
                    break;
                }
            }

            connStr = textBox4.Text.Trim();


            // INPUT DATA VALIDATION

            if (hubName == string.Empty)
            {
                DisplayMessage.Error(this, "Provide the Azure Notification Hub name");
                return(false);
            }

            if (hubNamespace == string.Empty)
            {
                DisplayMessage.Error(this, "Provide the Azure Notification Hub namespace");
                return(false);
            }

            if (ttl == TimeSpan.Zero)
            {
                DisplayMessage.Error(this, "Token TTL must be an integer");
                return(false);
            }

            if (connStr == string.Empty)
            {
                DisplayMessage.Error(this, "Provide the Azure Notification Hub connection string");
                return(false);
            }

            return(true);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (ValidateInput())
            {
                string[] parts = connStr.Split(';');

                Dictionary <string, string> dictionary = new Dictionary <string, string>();

                foreach (string part in parts)
                {
                    if (part.Contains("Endpoint="))
                    {
                        dictionary.Add("Endpoint", part.Replace("Endpoint=", null));
                    }
                    else if (part.Contains("SharedAccessKeyName="))
                    {
                        dictionary.Add("SharedAccessKeyName", part.Replace("SharedAccessKeyName=", null));
                    }
                    else if (part.Contains("SharedAccessKey="))
                    {
                        dictionary.Add("SharedAccessKey", part.Replace("SharedAccessKey=", null));
                    }
                }


                if (dictionary.Count == 3)
                {
                    // URL format obtained by tracing a call made by the client returned by NotificationHubClient.CreateClientFromConnectionString() when calling SendTemplateNotificationAsync()

                    string url = urlTemplate;

                    url = url.Replace("{NOTIF_HUB_NS}", hubNamespace);
                    url = url.Replace("{NOTIF_HUB_NAME}", hubName);

                    // Microsoft.Azure.NotificationHubs.dll
                    //string sas = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(dictionary["SharedAccessKeyName"], dictionary["SharedAccessKey"], url, ttl);

                    string sas = SharedAccessSignatureBuilder.GetSharedAccessSignature(dictionary["SharedAccessKeyName"], dictionary["SharedAccessKey"], url, ttl);

                    textBox5.Text = sas;
                }
                else
                {
                    DisplayMessage.Error(this, "An Azure Notification Hub connection string should have the \"Endpoint=...;SharedAccessKeyName=...;SharedAccessKey=...\" format.");
                }
            }
        }
        private async void button2_Click(object sender, EventArgs e)
        {
            if (textBox4.Text == string.Empty)
            {
                DisplayMessage.Error(this, "You need to generated a SAS before");
                return;
            }

            textBox8.Text = null;

            string url = urlTemplate;

            if (urlTemplate.Contains(HUB_NAME))
            {
                url = url.Replace(HUB_NAME, hubName);
            }
            else
            {
                DisplayMessage.Error(this, $"Placeholder {hubName} not found in \"UrlTemplate\" configuration item");
                return;
            }

            if (urlTemplate.Contains(HUB_NAMESPACE))
            {
                url = url.Replace(HUB_NAMESPACE, hubNamespace);
            }
            else
            {
                DisplayMessage.Error(this, $"Placeholder {hubNamespace} not found in \"UrlTemplate\" configuration item");
                return;
            }

            // SharedAccessSignature sr={URI}&sig={HMAC_SHA256_SIGNATURE}&se={EXPIRATION_TIME}&skn={KEY_NAME}

            //SharedAccessSignature sr=https%3a%2f%2fstefama-eh.servicebus.windows.net%2fstefamaeventhub%2fpublishers%2fabc&sig=4AI5vU5LmKk0V%2f71Swt4jmJkEU1uYajBKI6p3aSAUPg%3d&se=1531839083&skn=RootManageSharedAccessKey

            HttpHelper http = new HttpHelper(this);

            textBox8.Text = await http.DoPost(url, textBox5.Text, textBox7.Text);
        }
Exemplo n.º 5
0
        public async Task <string> DoPost(string url, string authHeader, string body)
        {
            string responseBody = null;

            Uri requestUri = new Uri(url);

            HttpWebRequest req = HttpWebRequest.Create(requestUri) as HttpWebRequest;

            req.Method = HTTP_POST;


            req.Headers["Authorization"] = authHeader;
            req.ContentType = "application/json";

            byte[] byteArray = Encoding.UTF8.GetBytes(body);
            req.ContentLength = byteArray.Length;

            Exception exc = null;

            try
            {
                // Get the request stream.
                using (Stream dataStream = await req.GetRequestStreamAsync())
                {
                    // Write the data to the request stream.
                    await dataStream.WriteAsync(byteArray, 0, byteArray.Length);

                    dataStream.Close();
                }
            }
            catch (Exception ex)
            {
                exc = ex;

                string msg = ex.Message;

                if (ex is WebException)
                {
                    WebException wex = ex as WebException;

                    if (wex.Response != null)
                    {
                        msg += Environment.NewLine + Environment.NewLine + GetResponseBody(wex);
                    }
                }

                DisplayMessage.Error(_parent, msg);
            }

            if (exc == null)
            {
                try
                {
                    // WEB RESPONSE

                    Task <WebResponse> task = req.GetResponseAsync();

                    //using (HttpWebResponse res = req.GetResponse() as HttpWebResponse)
                    using (HttpWebResponse res = await task as HttpWebResponse)
                    {
                        HttpStatusCode statusCode        = res.StatusCode;
                        string         statusDescription = res.StatusDescription;

                        string characterSet    = res.CharacterSet;
                        string contentEncoding = res.ContentEncoding;
                        long   contentLength   = res.ContentLength;
                        string contentType     = res.ContentType;

                        DateTime lastModified = res.LastModified;

                        string cerverResponse = null;
                        using (Stream dataStream = res.GetResponseStream())
                        {
                            // Reading the server response.
                            cerverResponse = await ReadToEndAsync(characterSet, dataStream);

                            dataStream.Close();
                        }

                        StringBuilder sb = new StringBuilder();

                        sb.AppendLine($"POST {url}");
                        sb.AppendLine($"HTTP status: {(int)statusCode} {statusCode}");
                        sb.Append(Environment.NewLine);

                        foreach (string key in req.Headers.Keys)
                        {
                            sb.AppendLine($"{key}: {req.Headers[key]}");
                        }

                        sb.Append(Environment.NewLine);
                        sb.AppendLine($"Response: {cerverResponse}");

                        responseBody = sb.ToString();

                        res.Close();
                    }
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;

                    if (ex is WebException)
                    {
                        WebException wex = ex as WebException;

                        if (wex.Response != null)
                        {
                            msg += Environment.NewLine + Environment.NewLine + GetResponseBody(wex);
                        }
                    }

                    DisplayMessage.Error(_parent, msg);
                }
            }

            return(responseBody);
        }