1

I created an application for the Pharmacy management system using mysql and c#. They have the databases on Local and Remote server also. Basically all records are stored on local database. Then after the newly created records should be uploaded to the remote server using JSon file. I also have the code to execute the Json file data to remote server using php. I have the newly records on Desktop using json file.

JSon file export coding :

    private void btnExportToJson_Click(object sender, EventArgs e)
    {
        string contents = (DataTableToJSONWithStringBuilder(_dt));
        //MessageBox.Show(afd);
        System.IO.File.WriteAllText(@"C:\Users\NICK-PC\Desktop\path.json", contents);
        Application.Exit();
    }

JSon file create coding :

    public string DataTableToJSONWithStringBuilder(DataTable table)
    {
        var jsonString = new StringBuilder();
        if (table.Rows.Count > 0)
        {
            jsonString.Append("[\n");
            for (int i = 0; i < table.Rows.Count; i++)
            {
                jsonString.Append("{\n");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (j < table.Columns.Count - 1)
                    {
                        jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
                                          table.Rows[i][j].ToString() + "\",\n");
                    }
                    else if (j == table.Columns.Count - 1)
                    {
                        jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
                                          table.Rows[i][j].ToString() + "\"");
                    }
                }

                if (i == table.Rows.Count - 1)
                {
                    jsonString.Append("}");
                }
                else
                {
                    jsonString.Append("\n},");
                    jsonString.Append("\n");
                }
            }

            jsonString.Append("\n]");
        }

        return jsonString.ToString();
    }

I used the following code but does not work

public void jsonOps()
    {
        // Preparing Json object to send to the remote server
        jsonLogin li = new jsonLogin();
        li.username = "myadmin";
        li.password = "log@678*";
        string jLoginString = JsonConvert.SerializeObject(li);

        // Create HTTP POST request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.youraddress.com");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        httpWebRequest.Accept = "application/json";
        httpWebRequest.Method = "POST";

        string output = "";

        // Connecting to the server. Sending request and receiving response
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(jLoginString);
            streamWriter.Flush();
            streamWriter.Close();

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                output = streamReader.ReadToEnd();
            }
        }

        // Reading JSON response
        JsonTextReader reader = new JsonTextReader(new StringReader(output));
        while (reader.Read())
        {
            if (reader.Value != null)
            {
                textBox1.Text = reader.Value;
            }
            else
            {
                // No value exception block
            }
        }
S.Sakthybaalan
  • 499
  • 6
  • 20
  • What exactly is your question? How to convert a `DataTable` to JSON? If so see [How to convert datatable to json string using json.net?](https://stackoverflow.com/a/2979938/3744182) which shows it can be done in one line using [tag:json.net]. Or is your question, How to upload an arbitrary file to a server? If this is your question then the code to build the JSON is irrelevant; we would need to know what kind of server it is - a web server, a file server, or what? – dbc May 17 '18 at 05:56
  • That is a web server. I already converted the `DataTable` to `Json`. And that file is in the desktop. I want to upload it to the web server. – S.Sakthybaalan May 17 '18 at 05:58
  • Try referring this. https://msdn.microsoft.com/en-us/library/sx0a40c2(v=vs.110).aspx – Akbar Badhusha May 17 '18 at 06:02
  • I read. I am unable to understand it. – S.Sakthybaalan May 17 '18 at 06:16
  • Why would you use a socket when an HttpRequest might be sufficient? – Markus Deibel May 17 '18 at 06:21
  • Yes, how it is possible with `HttpRequest` ? – S.Sakthybaalan May 17 '18 at 06:25
  • @SAKTHY Maybe this can help you: https://stackoverflow.com/a/4015346/5731129. You probably need only to send json string, not a file. Otherwise this: https://stackoverflow.com/a/19664927/5731129 – erikscandola May 17 '18 at 06:32
  • Have you considered MySQL Replication instead of using HTTP in this strange way? https://dev.mysql.com/doc/refman/8.0/en/replication-howto.html Why are you populating JSON from a DataTable manually? Why are you saving to a temporary file instead of streaming directly to an HttpRequest? – Anders Marzi Tornblad May 17 '18 at 06:42
  • So,, how can I streaming directly the records directly to the remote server without storing on temporarily – S.Sakthybaalan May 17 '18 at 06:52
  • @AndersTornblad, Please say the way... – S.Sakthybaalan May 18 '18 at 08:13

1 Answers1

0

I use the following code

    private void btnUploadToServer_Click(object sender, EventArgs e)
    {
        bool connection = NetworkInterface.GetIsNetworkAvailable();
        if (connection == true)
        {
            //MessageBox.Show("Internet Available");

            try
            {
                using (WebClient client = new WebClient())
                {
                    string filePath = @"C:\Users\SAKTHYBAALAN-PC\Desktop\app_sample.json";
                    var myUri = new Uri(@"http://your_address/path/file.php");
                    client.UploadFile(myUri, filePath);
                    client.Credentials = CredentialCache.DefaultCredentials;
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }

            MessageBox.Show("Successfully Uploaded", "Success");
            btnExecuteURL.Enabled = true;
        }

        else
        {
            MessageBox.Show("There is no internet connection.\n Please make sure that you have an internet connection.", "No Internet");
        }
    }
S.Sakthybaalan
  • 499
  • 6
  • 20