Exemplo n.º 1
0
        private void OnFormClosed(object sender, FormClosedEventArgs e)
        {
            Util.WriteCustomLog("Office365APIEditor Closing Log", "Exit. Code 20");

            if (!string.IsNullOrEmpty(Properties.Settings.Default.NewerInstallerPath) && File.Exists(Properties.Settings.Default.NewerInstallerPath))
            {
                // Newer installer is available

                if (MessageBox.Show("Do you want to install the latest version of Office365APIEditor?", "Office365APIEditor", MessageBoxButtons.YesNo, MessageBoxIcon.None) == DialogResult.Yes)
                {
                    try
                    {
                        System.Diagnostics.Process msi = System.Diagnostics.Process.Start(Properties.Settings.Default.NewerInstallerPath);

                        Properties.Settings.Default.NewerInstallerPath = "";
                        Properties.Settings.Default.Save();
                    }
                    catch
                    {
                    }
                }
            }

            Environment.Exit(0);
        }
Exemplo n.º 2
0
        private async void button_AcquireAccessToken_Click(object sender, EventArgs e)
        {
            if (textBox_ClientID.Text == "")
            {
                MessageBox.Show("Enter the Application ID.", "Office365APIEditor");
                return;
            }

            Cursor = Cursors.WaitCursor;

            string[] scopes = Office365APIEditorHelper.MailboxViewerScopes();

            _pca = new PublicClientApplication(textBox_ClientID.Text);

            StringBuilder stringBuilder = new StringBuilder();

            try
            {
                stringBuilder.AppendLine("MSAL - AcquireTokenAsync");
                stringBuilder.AppendLine("Application ID : " + textBox_ClientID.Text);
                stringBuilder.AppendLine("Scope : " + string.Join(",", scopes));

                _ar = await _pca.AcquireTokenAsync(scopes, "", UIBehavior.ForceLogin, "");

                stringBuilder.AppendLine("Result : Success");
                stringBuilder.AppendLine("AccessToken : " + ((_ar.AccessToken == null) ? "" : _ar.AccessToken));
                stringBuilder.AppendLine("ExpiresOn : " + _ar.ExpiresOn.ToString());
                stringBuilder.AppendLine("IdToken : " + ((_ar.IdToken == null) ? "" : _ar.IdToken));
                stringBuilder.AppendLine("Scope : " + string.Join(",", _ar.Scopes));
                stringBuilder.AppendLine("UniqueId : " + ((_ar.UniqueId == null) ? "" : _ar.UniqueId));
                stringBuilder.AppendLine("DisplayableId : " + ((_ar.User.DisplayableId == null) ? "" : _ar.User.DisplayableId));
                stringBuilder.AppendLine("Identifier : " + ((_ar.User.Identifier == null) ? "" : _ar.User.Identifier));
                stringBuilder.AppendLine("Name : " + ((_ar.User.Name == null) ? "" : _ar.User.Name));

                Properties.Settings.Default.Save();
                DialogResult = DialogResult.OK;
                Cursor       = Cursors.Default;
                Close();
            }
            catch (Exception ex)
            {
                stringBuilder.AppendLine("Result : Fail");
                stringBuilder.AppendLine("Message : " + ex.Message);
                Cursor = Cursors.Default;

                if (ex.Message != "User canceled authentication")
                {
                    MessageBox.Show(ex.Message, "Office365APIEditor");
                }
            }

            Util.WriteCustomLog("AcquireViewerTokenForm", stringBuilder.ToString());
        }
        private async System.Threading.Tasks.Task AcquireAccessTokenAsync(string ClientId)
        {
            Cursor  = Cursors.WaitCursor;
            Enabled = false;

            string[] scopes = Util.MailboxViewerScopes();

            _pca = new PublicClientApplication(ClientId);

            StringBuilder stringBuilder = new StringBuilder();

            try
            {
                stringBuilder.AppendLine("MSAL - AcquireTokenAsync");
                stringBuilder.AppendLine("Application ID : " + ClientId);
                stringBuilder.AppendLine("Scope : " + string.Join(",", scopes));

                _ar = await _pca.AcquireTokenAsync(scopes, "", UIBehavior.ForceLogin, "");

                stringBuilder.AppendLine("Result : Success");
                stringBuilder.AppendLine("AccessToken : " + (_ar.AccessToken ?? ""));
                stringBuilder.AppendLine("ExpiresOn : " + _ar.ExpiresOn.ToString());
                stringBuilder.AppendLine("IdToken : " + (_ar.IdToken ?? ""));
                stringBuilder.AppendLine("Scope : " + string.Join(",", _ar.Scopes));
                stringBuilder.AppendLine("UniqueId : " + (_ar.UniqueId ?? ""));
                stringBuilder.AppendLine("DisplayableId : " + (_ar.User.DisplayableId ?? ""));
                stringBuilder.AppendLine("Identifier : " + (_ar.User.Identifier ?? ""));
                stringBuilder.AppendLine("Name : " + (_ar.User.Name ?? ""));

                Properties.Settings.Default.Save();
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                stringBuilder.AppendLine("Result : Fail");
                stringBuilder.AppendLine("Message : " + ex.Message);

                if (ex.Message != "User canceled authentication")
                {
                    MessageBox.Show(ex.Message, "Office365APIEditor");
                }
            }
            finally
            {
                Cursor  = Cursors.Default;
                Enabled = true;
            }

            Util.WriteCustomLog("AcquireViewerTokenForm", stringBuilder.ToString());
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            // Save the contents of the log temporarily until the initialization of the setting is completed.
            StringBuilder startupLog = new StringBuilder();

            startupLog.AppendLine("Start.");

            // Load previous settings.
            if (Properties.Settings.Default.NeedUpgrade == true)
            {
                startupLog.AppendLine("Setting upgrade is required.");

                try
                {
                    Properties.Settings.Default.Upgrade();
                    startupLog.AppendLine("Setting was upgraded.");
                }
                catch
                {
                    startupLog.AppendLine("Setting was not upgraded.");
                }
                finally
                {
                    Properties.Settings.Default.NeedUpgrade = false;
                    Properties.Settings.Default.Save();
                    startupLog.AppendLine("Setting was saved.");
                }
            }

            // Check the command line switches.
            startupLog.AppendLine("CommandLine : " + Environment.CommandLine);
            string[] switches = Environment.GetCommandLineArgs();

            foreach (string command in switches)
            {
                if (command.ToLower() == ("/NoSetting").ToLower())
                {
                    // Reset all settings.
                    startupLog.AppendLine("Setting will be reset.");
                    Properties.Settings.Default.Reset();
                    Properties.Settings.Default.Save();
                    startupLog.AppendLine("Setting was saved.");
                }
                else if (command.ToLower() == ("/NoHistory").ToLower())
                {
                    // Remove Run History file.
                    startupLog.AppendLine("The history file will be delete.");
                    if (File.Exists(Path.Combine(Application.StartupPath, "RunHistory.xml")))
                    {
                        try
                        {
                            File.Delete(Path.Combine(Application.StartupPath, "RunHistory.xml"));
                            startupLog.AppendLine("The history file was deleted.");
                        }
                        catch (Exception ex)
                        {
                            startupLog.AppendLine("The history file was not deleted.");
                            MessageBox.Show(ex.Message.ToString(), "Office365APIEditor");
                        }
                    }
                    else
                    {
                        startupLog.AppendLine("The history file does not exist.");
                    }
                }
            }

            // Set default log folder path.
            startupLog.AppendLine("Current log folder : " + Properties.Settings.Default.LogFolderPath);
            if (!Directory.Exists(Properties.Settings.Default.LogFolderPath))
            {
                startupLog.AppendLine("The log folder does not exist and will be reset.");
                Properties.Settings.Default.LogFolderPath = Application.StartupPath;
                Properties.Settings.Default.Save();
                startupLog.AppendLine("New log folder : " + Properties.Settings.Default.LogFolderPath);
                startupLog.AppendLine("Setting was saved.");
            }

            // Write startup log.
            Util.WriteCustomLog("Office365APIEditor startup log", startupLog.ToString());

            // Create the MyApplicationContext, that derives from ApplicationContext,
            // that manages when the application should exit.

            MyApplicationContext context = new MyApplicationContext();

            // Run the application with the specific context. It will exit when
            // all forms are closed.
            try
            {
                Application.Run(context);
            }
            catch (Exception ex)
            {
                // Write error log.
                try
                {
                    string filePath = Path.Combine(Application.StartupPath, "Error.txt");

                    using (StreamWriter writer = new StreamWriter(filePath, true))
                    {
                        writer.WriteLine(
                            "Date :" + DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + Environment.NewLine +
                            "Message :" + ex.Message + Environment.NewLine +
                            "StackTrace :" + ex.StackTrace + Environment.NewLine +
                            "-----------------------------------------------------------------------------" + Environment.NewLine
                            );
                    }
                }
                catch
                {
                }

                if (ex.InnerException == null)
                {
                    MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    MessageBox.Show(ex.InnerException.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            finally
            {
                Util.WriteCustomLog("Office365APIEditor Closing Log", "Exit. Code 10");
            }
        }
Exemplo n.º 5
0
 private void OnFormClosed(object sender, FormClosedEventArgs e)
 {
     Util.WriteCustomLog("Office365APIEditor Closing Log", "Exit. Code 20");
     Environment.Exit(0);
 }
Exemplo n.º 6
0
        private async void button_RefreshToken_Click(object sender, EventArgs e)
        {
            // Request another access token with refresh token.

            originalJsonResponse           = "";
            indentedJsonResponse           = "";
            decodedJsonResponse            = "";
            indentedAndDecodedJsonResponse = "";

            string endPoint = "https://login.microsoftonline.com/common/oauth2/";

            // Build a POST body.
            string    postBody  = "";
            Hashtable tempTable = new Hashtable();

            tempTable["grant_type"]    = "refresh_token";
            tempTable["refresh_token"] = clientInfo.Token.refresh_token;

            if (clientInfo.AuthType == AuthEndpoints.OAuthV1)
            {
                //string resourceURL = StartForm.GetResourceURL(clientInfo.ResourceUri);
                tempTable["resource"] = System.Web.HttpUtility.UrlEncode(clientInfo.ResourceUri);

                if (clientInfo.ClientID != "")
                {
                    // If _clientID has value, we're working with web app.
                    // So we have to add Client ID and Client Secret.
                    tempTable["client_id"]     = clientInfo.ClientID;
                    tempTable["client_secret"] = System.Web.HttpUtility.UrlEncode(clientInfo.ClientSecret);
                }
            }
            else
            {
                endPoint                 += "v2.0/";
                tempTable["scope"]        = clientInfo.Scopes;
                tempTable["client_id"]    = clientInfo.ClientID;
                tempTable["redirect_uri"] = System.Web.HttpUtility.UrlEncode(clientInfo.RedirectUri);

                if (clientInfo.ClientID != "")
                {
                    // If _clientID has value, we're working with web app.
                    // So we have to add Client Secret.
                    tempTable["client_secret"] = clientInfo.ClientSecret;
                }
            }

            foreach (string key in tempTable.Keys)
            {
                postBody += String.Format("{0}={1}&", key, tempTable[key]);
            }
            byte[] postDataBytes = Encoding.ASCII.GetBytes(postBody);

            WebRequest request = WebRequest.Create(endPoint + "token/");

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = postDataBytes.Length;

            try
            {
                // Change a cursor.
                Application.UseWaitCursor = true;

                // Get a RequestStream to POST a data.
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(postDataBytes, 0, postDataBytes.Length);
                }

                // Logging
                if (checkBox_Logging.Checked)
                {
                    WriteRequestLog(request, postBody);
                }

                string jsonResponse = "";

                var response = (HttpWebResponse)await request.GetResponseAsync();

                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.Default);
                    jsonResponse = reader.ReadToEnd();
                }

                // Logging
                if (checkBox_Logging.Checked)
                {
                    WriteResponseLog(response, jsonResponse);
                }

                // Display the results.
                DisplayResponse(CreateStatusCodeString(response), response.Headers, jsonResponse);

                // Deserialize and get Access Token.
                clientInfo.ReplaceToken(AccessTokenWizard.Deserialize <TokenResponse>(jsonResponse));
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                {
                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        Util.WriteCustomLog("Response", ex.Message);
                    }

                    DisplayResponse("Error", null, ex.Message);
                }
                else
                {
                    string jsonResponse = "";
                    using (Stream responseStream = ex.Response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.Default);
                        jsonResponse = reader.ReadToEnd();
                    }

                    HttpWebResponse response = (HttpWebResponse)ex.Response;

                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        WriteResponseLog((HttpWebResponse)ex.Response, jsonResponse);
                    }

                    DisplayResponse(CreateStatusCodeString(response), ex.Response.Headers, jsonResponse);
                }
            }
            catch (Exception ex)
            {
                // Logging
                if (checkBox_Logging.Checked)
                {
                    Util.WriteCustomLog("Response", ex.Message);
                }

                DisplayResponse("Error", null, ex.Message);
            }
            finally
            {
                // Change cursor.
                Application.UseWaitCursor = false;
            }
        }
Exemplo n.º 7
0
        private async void button_Run_Click(object sender, EventArgs e)
        {
            Uri requestUri;

            originalJsonResponse           = "";
            indentedJsonResponse           = "";
            decodedJsonResponse            = "";
            indentedAndDecodedJsonResponse = "";

            string originalRequestBody = "";

            try
            {
                requestUri = new Uri(textBox_Request.Text);
            }
            catch
            {
                requestUri = null;
            }

            if (requestUri == null)
            {
                MessageBox.Show("The supplied URI could not be correctly parsed.", "Office365APIEditor");
                return;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox_Request.Text);

            request.AllowAutoRedirect = Properties.Settings.Default.AllowAutoRedirect;
            request.ContentType       = "application/json";
            // ((HttpWebRequest)request).Accept = "application/json;odata.metadata=full;odata.streaming=true";
            // TODO: implement "Accept Header Editor"

            if (clientInfo.AuthType == AuthEndpoints.Basic)
            {
                // Basic authentication

                if (textBox_BasicAuthSMTPAddress.Text == "")
                {
                    MessageBox.Show("Enter your SMTP address", "Office365APIEditor");
                    textBox_BasicAuthSMTPAddress.Focus();
                    return;
                }

                if (textBox_BasicAuthPassword.Text == "")
                {
                    MessageBox.Show("Enter your password", "Office365APIEditor");
                    textBox_BasicAuthPassword.Focus();
                    return;
                }

                string credential = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(textBox_BasicAuthSMTPAddress.Text + ":" + textBox_BasicAuthPassword.Text));
                request.Headers.Add("Authorization:Basic " + credential);
            }
            else
            {
                // OAuth authentication
                request.Headers.Add("Authorization:Bearer " + clientInfo.Token.access_token);
            }

            if (radioButton_GET.Checked)
            {
                // Request is GET.
                request.Method = "GET";
            }
            else if (radioButton_POST.Checked)
            {
                // Request is POST.
                request.Method = "POST";

                // Build a body.
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    originalRequestBody = textBox_RequestBody.Text;

                    streamWriter.Write(originalRequestBody);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            else if (radioButton_PATCH.Checked)
            {
                // Request if PATCH
                request.Method = "PATCH";

                // Build a body.
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    originalRequestBody = textBox_RequestBody.Text;

                    streamWriter.Write(originalRequestBody);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            else
            {
                // Request is DELETE.
                request.Method = "DELETE";
            }

            // Add headers

            string originalRequestHeaders = "";

            foreach (DataGridViewRow item in dataGridView_RequestHeader.Rows)
            {
                string headerName  = "";
                string headerValue = "";

                if (item.Cells[0].Value != null)
                {
                    headerName = item.Cells[0].Value.ToString();
                }

                if (item.Cells[1].Value != null)
                {
                    headerValue = item.Cells[1].Value.ToString();
                }

                if (headerName == "")
                {
                    if (headerValue == "")
                    {
                        continue;
                    }
                    else
                    {
                        MessageBox.Show("Invalid header name.", "Office365APIEditor");
                        return;
                    }
                }

                string header = headerName + ": " + headerValue;
                originalRequestHeaders += header + Environment.NewLine;

                try
                {
                    request.Headers.Add(header);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Office365APIEditor");
                    return;
                }
            }

            try
            {
                // Change cursor.
                Application.UseWaitCursor = true;

                // Logging
                if (checkBox_Logging.Checked)
                {
                    WriteRequestLog(request, originalRequestBody);
                }

                // Get a response and response stream.
                var response = (HttpWebResponse)await request.GetResponseAsync();

                string jsonResponse = "";
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    jsonResponse = reader.ReadToEnd();
                }

                // Logging
                if (checkBox_Logging.Checked)
                {
                    WriteResponseLog(response, jsonResponse);
                }

                // Display the results.
                DisplayResponse(CreateStatusCodeString(response), response.Headers, jsonResponse);

                // Add Run History
                AddRunHistory(request, originalRequestHeaders, originalRequestBody, response, jsonResponse);

                // Save application setting.
                Properties.Settings.Default.Save();
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                {
                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        Util.WriteCustomLog("Response", ex.Message);
                    }

                    DisplayResponse("Error", null, ex.Message);

                    // Add Run History
                    AddRunHistory(request, originalRequestHeaders, originalRequestBody, null, ex.Message);
                }
                else
                {
                    string jsonResponse = "";
                    using (Stream responseStream = ex.Response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.Default);
                        jsonResponse = reader.ReadToEnd();
                    }

                    HttpWebResponse response = (HttpWebResponse)ex.Response;

                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        WriteResponseLog(response, jsonResponse);
                    }

                    DisplayResponse(CreateStatusCodeString(response), ex.Response.Headers, jsonResponse);

                    // Add Run History
                    AddRunHistory(request, originalRequestHeaders, originalRequestBody, (HttpWebResponse)ex.Response, jsonResponse);
                }
            }
            catch (Exception ex)
            {
                // Logging
                if (checkBox_Logging.Checked)
                {
                    Util.WriteCustomLog("Response", ex.Message);
                }

                DisplayResponse("Error", null, ex.Message);

                // Add Run History
                AddRunHistory(request, originalRequestHeaders, originalRequestBody, null, ex.Message);
            }
            finally
            {
                // Change cursor.
                Application.UseWaitCursor = false;
            }
        }
Exemplo n.º 8
0
        private async void button_Run_Click(object sender, EventArgs e)
        {
            Uri requestUri;

            originalJsonResponse           = "";
            indentedJsonResponse           = "";
            decodedJsonResponse            = "";
            indentedAndDecodedJsonResponse = "";

            string originalRequestBody = "";

            try
            {
                requestUri = new Uri(textBox_Request.Text);
            }
            catch
            {
                requestUri = null;
            }

            if (requestUri == null)
            {
                MessageBox.Show("The supplied URI could not be correctly parsed.", "Office365APIEditor");
                return;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox_Request.Text);

            request.AllowAutoRedirect = Properties.Settings.Default.AllowAutoRedirect;
            request.UserAgent         = Util.CustomUserAgent;
            request.ContentType       = "application/json";
            // ((HttpWebRequest)request).Accept = "application/json;odata.metadata=full;odata.streaming=true";
            // TODO: implement "Accept Header Editor"

            if (clientInfo.AuthType == AuthEndpoints.Basic)
            {
                // Basic authentication

                if (textBox_BasicAuthSMTPAddress.Text == "")
                {
                    MessageBox.Show("Enter your SMTP address", "Office365APIEditor");
                    textBox_BasicAuthSMTPAddress.Focus();
                    return;
                }

                if (textBox_BasicAuthPassword.Text == "")
                {
                    MessageBox.Show("Enter your password", "Office365APIEditor");
                    textBox_BasicAuthPassword.Focus();
                    return;
                }

                string credential = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(textBox_BasicAuthSMTPAddress.Text + ":" + textBox_BasicAuthPassword.Text));
                request.Headers.Add("Authorization:Basic " + credential);
            }
            else
            {
                // OAuth authentication
                request.Headers.Add("Authorization:Bearer " + clientInfo.Token.access_token);
            }

            if (radioButton_GET.Checked)
            {
                // Request is GET.
                request.Method = "GET";
            }
            else if (radioButton_POST.Checked)
            {
                // Request is POST.
                request.Method = "POST";

                // Build a body.
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    originalRequestBody = textBox_RequestBody.Text;

                    streamWriter.Write(originalRequestBody);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            else if (radioButton_PATCH.Checked)
            {
                // Request if PATCH
                request.Method = "PATCH";

                // Build a body.
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    originalRequestBody = textBox_RequestBody.Text;

                    streamWriter.Write(originalRequestBody);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            else
            {
                // Request is DELETE.
                request.Method = "DELETE";
            }

            // Add headers

            string originalRequestHeaders = "";

            foreach (DataGridViewRow item in dataGridView_RequestHeader.Rows)
            {
                string headerName  = "";
                string headerValue = "";

                if (item.Cells[0].Value != null)
                {
                    headerName = item.Cells[0].Value.ToString();
                }

                if (item.Cells[1].Value != null)
                {
                    headerValue = item.Cells[1].Value.ToString();
                }

                if (headerName == "")
                {
                    if (headerValue == "")
                    {
                        continue;
                    }
                    else
                    {
                        MessageBox.Show("Invalid header name.", "Office365APIEditor");
                        return;
                    }
                }

                string header = headerName + ": " + headerValue;
                originalRequestHeaders += header + Environment.NewLine;

                try
                {
                    request.Headers.Add(header);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Office365APIEditor");
                    return;
                }
            }

            try
            {
                // Change cursor.
                Application.UseWaitCursor = true;

                // Logging
                if (checkBox_Logging.Checked)
                {
                    WriteRequestLog(request, originalRequestBody);
                }

                // Get a response and response stream.
                var response = (HttpWebResponse)await request.GetResponseAsync();

                bool   isImageResponse    = response.ContentType.Contains("image/jpeg");
                string contentDisposition = response.Headers.Get("content-disposition");
                bool   isCsvResponse      = (contentDisposition != null && Regex.IsMatch(contentDisposition, "^attachment; filename=\".*\\.csv\"$"));

                if (isImageResponse)
                {
                    // Response data is photo.

                    List <byte> byteList = new List <byte>();

                    using (Stream responseStream = response.GetResponseStream())
                    {
                        for (; ;)
                        {
                            // read 1 byte from the stream
                            int data = responseStream.ReadByte();

                            if (data == -1)
                            {
                                // there is no data to read
                                break;
                            }

                            byteList.Add((byte)data);
                        }
                    }

                    byte[] binaryResponse = byteList.ToArray();
                    string base64Response = Convert.ToBase64String(binaryResponse);

                    // Create new bitmap object to display the response
                    MemoryStream memoryStream = new MemoryStream();
                    byte[]       pictureData  = binaryResponse;
                    memoryStream.Write(pictureData, 0, Convert.ToInt32(pictureData.Length));
                    Bitmap bitmapResponse = new Bitmap(memoryStream, false);
                    memoryStream.Dispose();

                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        WriteResponseLog(response, base64Response);
                    }

                    // Display the results.
                    DisplayResponse(CreateStatusCodeString(response), response.Headers, base64Response);
                    pictureBox_Photo.Image = bitmapResponse;

                    // Add Run History
                    AddRunHistory(request, originalRequestHeaders, originalRequestBody, response, base64Response);
                }
                else if (isCsvResponse)
                {
                    // Response data is CSV.

                    string csvResponse = "";
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        csvResponse = reader.ReadToEnd();
                    }

                    // Create DataTable

                    StringReader stringReader = new StringReader(csvResponse);
                    string       line         = stringReader.ReadLine();

                    DataTable dataTable = new DataTable();
                    DataRow   dataRow;

                    if (line != "")
                    {
                        // Create headers.
                        foreach (var column in line.Split(','))
                        {
                            dataTable.Columns.Add(column);
                        }

                        // Add rows.
                        while ((line = stringReader.ReadLine()) != null)
                        {
                            dataRow           = dataTable.NewRow();
                            dataRow.ItemArray = line.Split(',');
                            dataTable.Rows.Add(dataRow);
                        }
                    }

                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        WriteResponseLog(response, csvResponse);
                    }

                    // Display the results.
                    DisplayResponse(CreateStatusCodeString(response), response.Headers, csvResponse);
                    dataGridView_CSV.DataSource = dataTable;

                    // Add Run History
                    AddRunHistory(request, originalRequestHeaders, originalRequestBody, response, csvResponse);
                }
                else
                {
                    // Response data is json.

                    string jsonResponse = "";
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        jsonResponse = reader.ReadToEnd();
                    }

                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        WriteResponseLog(response, jsonResponse);
                    }

                    // Display the results.
                    DisplayResponse(CreateStatusCodeString(response), response.Headers, jsonResponse);

                    // Add Run History
                    AddRunHistory(request, originalRequestHeaders, originalRequestBody, response, jsonResponse);
                }

                // Save application setting.
                Properties.Settings.Default.Save();
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                {
                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        Util.WriteCustomLog("Response", ex.Message);
                    }

                    DisplayResponse("Error", null, ex.Message);

                    // Add Run History
                    AddRunHistory(request, originalRequestHeaders, originalRequestBody, null, ex.Message);
                }
                else
                {
                    string jsonResponse = "";
                    using (Stream responseStream = ex.Response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.Default);
                        jsonResponse = reader.ReadToEnd();
                    }

                    HttpWebResponse response = (HttpWebResponse)ex.Response;

                    // Logging
                    if (checkBox_Logging.Checked)
                    {
                        WriteResponseLog(response, jsonResponse);
                    }

                    DisplayResponse(CreateStatusCodeString(response), ex.Response.Headers, jsonResponse);

                    // Add Run History
                    AddRunHistory(request, originalRequestHeaders, originalRequestBody, (HttpWebResponse)ex.Response, jsonResponse);
                }
            }
            catch (Exception ex)
            {
                // Logging
                if (checkBox_Logging.Checked)
                {
                    Util.WriteCustomLog("Response", ex.Message);
                }

                DisplayResponse("Error", null, ex.Message);

                // Add Run History
                AddRunHistory(request, originalRequestHeaders, originalRequestBody, null, ex.Message);
            }
            finally
            {
                // Change cursor.
                Application.UseWaitCursor = false;
            }
        }