So I have a list in c# that's being converted to a string, which is then converted to a 2-dimensional array in PHP, which is then sent to MySQL database. Now how do I go about reversing this, whereby I can download from the database to PHP than to c# list.
This is what I have so far, but I'm not sure if I need to download the data back to an array in PHP or if I should download it as a string and break it up into a list in c#?
This is my c# code:
public List<Ship> shipList = new List<Ship>();
string shipListString = "";
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("shipcount", ShipInventory.Count);
for (int i = 0; i < shipList.Count; i++)
{
shipListString = shipListString + " " + shipList[i].id + " '" + shipList[i].username + "' '" + shipList[i].name + "' " + shipList[i].power +
"zzz";// + ShipInventory[i];
}
form.AddField("shipinventory", shipListString);
WWW www = new WWW("x.x.x.x/savedata.php", form);
yield return www;
And this is my php:
$shiparraytobesplit = $_POST["shipinventory"];
$ships = explode("zzz", $shiparraytobesplit);
unset($ships[count($ships)-1]);
$shipinfo = array_map(function($ship) {
$tempshipinfo = explode(" ", $ship);
$ship_assoc = [
"id" => $tempshipinfo[1],
"name" => $tempshipinfo[2],
"username" => $tempshipinfo[3],
"hp" => $tempshipinfo[4]
];
return $ship_assoc;
}, $ships);
$sql = sprintf('INSERT INTO shipinventory (shipid,shipname,username,shippower) VALUES (%s)', implode(',',array_values($shipinfo[$i])));
if(!mysqli_query($con, $sql))
{
echo("error description: " . mysqli_error($con));
}
This is working well to upload my c# list into the database, but I'm not sure what's the best way to download it from the database back to a c# list. Any advice would be awesome! Thanks
Ok so I managed to make it work but I imagine there are better methods so please share! Thanks:
C# Script:
WWW www = new WWW("x.x.x.x/loaddata.php");
yield return www;
stringFromPHP = www.text;
char[] delimiterENTER = new char[] {'\n' };
char[] delimiterSPACE = new char[] { ' ' };
shipStringArray = stringFromPHP.Split(delimiterENTER, StringSplitOptions.RemoveEmptyEntries);
shipList.Clear();
for (int i = 0; i < shipStringArray.Count(); i++)
{
string[] shipInfo = shipStringArray[i].Split(delimiterSPACE);
shipList.Add(new Ship(Int32.Parse(shipInfo[0]), shipInfo[1], shipInfo[2], Int32.Parse(shipInfo[3]), shipStringArray[i]));
}
and php:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT shipid, username, shipname, shippower FROM shipinventory";
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$stringtoexplodeincsharp printf ("%s %s %s %s\n",(int) $row["shipid"], $row["username"], $row["shipname"],(int) $row["shippower"]);
}
mysqli_free_result($result);
}
mysqli_close($con);
Related
I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.
I have one application which is gathering the videos from youtube users.
since 3 days it is stopped and not gatehring videos and the only one video in listview is showing the youtube url: "https://www.youtube.com/devicesupport"
I have read that url but still not understand why it is not working. If someone has same issue I will appreciate to help me out.
My code:
private void Get_Video_Of_Searched_User()
{
using (new CWaitCursor())
{
int TotalVideoFound = 0;
string VideoID = string.Empty;
string YouTube_User = this.Txt_Youtube_UserName.Text;
int StartIndex = (Current_Page * 50) + 1;
YouTubeService ytsService = new YouTubeService(strAppName, strKey);
Uri urlEntryUrl = default(Uri);
urlEntryUrl = new Uri("https://gdata.youtube.com/feeds/api/users/" + YouTube_User + "/uploads?&max-results=50&start-index=" + StartIndex.ToString() + "");
FeedQuery fqResults = new FeedQuery();
fqResults.Uri = urlEntryUrl;
Feed<Video> vidFeed = new Feed<Video>(ytsService, fqResults);
try
{
TotalVideoFound = vidFeed.TotalResults;
}
catch
{
MessageBox.Show("Incorrect Username.");
return;
}
if (StartIndex == 1)
Lbl_TotalVideos.Text = "Total Videos: (" + TotalVideoFound.ToString() + ")";
Enable_Disable_Next_And_Previous_Buttons(TotalVideoFound);
SortedDictionary<string, string> ListViewItems = new SortedDictionary<string, string>();
Dict_User_Links_With_Title.Clear();
foreach (Video vidEntry in vidFeed.Entries)
{
if (ListViewItems.ContainsKey(vidEntry.Title) == true) continue;
ListViewItems.Add(vidEntry.Title, vidEntry.ViewCount.ToString());
VideoID = vidEntry.Id;
if (!Dict_User_Links_With_Title.ContainsKey(VideoID.Substring(VideoID.LastIndexOf(":") + 1)))
Dict_User_Links_With_Title.Add(VideoID.Substring(VideoID.LastIndexOf(":") + 1), vidEntry.Title);
}
ListView_User_Video_Links.Items.Clear();
string[] MyListItems = new string[2];
foreach (KeyValuePair<string, string> entry in ListViewItems)
{
MyListItems[0] = entry.Key;
MyListItems[1] = entry.Value;
ListView_User_Video_Links.Items.Add(new ListViewItem(MyListItems));
}
string TotalViews = Get_Youtube_User_Total_Views(YouTube_User);
this.Total_Views_For_User.Text = "Total Views: (" + TotalViews + ")";
}
}
Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 30,000 units/second/user and 50,000,000 per day.
If you hit the limits, Google will stop returning results until your quota is reset.
I'm fairly new to both Unity and PHP, and I am currently working on a project where I can parse data from a MySQL database to Unity, using PHP.
I initially wanted to try and enable a method where the user can perhaps change the php script and enable it to choose a different table of data, however I was advised that it may be safer to list all variables within the php script and call it from Unity accordingly;
Display.php
$table = mysql_real_escape_string($_GET['table'], $db);
if ($table == "shoes") {
$query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";
elseif ($table == "sneakers") {
$query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);
for($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo $row['shopname'] . "\t" . $row['price'] . "\n";
}
I'm having trouble calling the php and choosing the table that I want to select, I am pretty new to this, so I apologise if this seems completely incompetent to you guys.
Here is the my Unity Script;
HSController.cs
void Start()
{
StartCoroutine(GetScores());
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{
string hash = Md5Sum(name + score + secretKey);
string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;
WWW hs_post = new WWW(post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print("There was an error posting the high score: " + hs_post.error);
}
}
IEnumerator GetScores()
{
gameObject.guiText.text = "Loading...";
WWW hs_get = new WWW(highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
gameObject.guiText.text = hs_get.text; // this is a GUIText that will display the scores in game.
}
}
Any help or a point in the right direction would be great!
Kind Regards
Let me try to rewrite this into a working example:
C#
void Start() {
StartCoroutine(GetData());
}
IEnumerator GetData() {
gameObject.guiText.text = "Loading...";
WWW www = new WWW("http://yoururl.com/yourphp.php?table=shoes"); //GET data is sent via the URL
while(!www.isDone && string.IsNullOrEmpty(www.error)) {
gameObject.guiText.text = "Loading... " + www.Progress.ToString("0%"); //Show progress
yield return null;
}
if(string.IsNullOrEmpty(www.error)) gameObject.guiText.text = www.text;
else Debug.LogWarning(www.error);
}
PHP
<?php
//DB connection goes here
if ($_REQUEST['table'] === "shoes") { //I'm using REQUEST instead of GET, so it will work with both GET and POST
$query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";
} elseif ($_REQUEST['table'] === "sneakers") {
$query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";
}
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['shopname'] . "\t" . $row['price'] . "\n";
}
?>
Hope this helps!
Using the C# Facebook SDK 5.0.3 everything works fine whit the client.Get("/me").
But when retrieving the status, I should get aan arraylist "data" with all the status messages according to the facebook Graph API, but instead my data array is empty and I get a 'Index out of bounds' exception.
Does anyone have an idea what my problem could be?
if (Request.Params["code"] != null)
{
var client = new FacebookClient(GetAccessToken());
dynamic me = client.Get("/me");
imgUser.ImageUrl = "https://graph.facebook.com/" + me.id + "/picture";
lblUsername.Text = me.name;
lblHometown.Text = me.hometown.name;
lblBirthday.Text = me.birthday;
lblCurrenttown.Text = me.location.name;
lblEmail.Text = me.email;
lblOpleidingen.Text = "";
lblOpleidingen.Text += me.education[1].type + ": " + me.education[1].school.name + ", " + me.education[1].year.name + "<br />"
+ me.education[0].type + ": " + me.education[0].school.name + ", " + me.education[0].year.name;
lblSex.Text = me.gender;
dynamic status = client.get("/me/statuses");
txtStatus.Text = status.data[0].message;
}
It requires the read_stream permission. Ensure you have it.
Your permission array should look like follows:
string[] extendedPermissions = new[] { "user_about_me", "read_stream" };
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
furthermore your second get() should be capitalized: Get()
dynamic status = client.get("/me/statuses");
dynamic status = client.Get("/me/statuses");
I am trying to make a web server in C#, i need to get the requested url and then list the files and folders requested.This is good to get the first directory .
For Eg. My webserver root is c:\test when i open localhost i get the contents of test folder. Say Data is subfolder of c:\test, i can click on data from the browser and get into C:\test\data now when i click on any folder then the get request comes with %2F instead of c:\test\data\ok and so i am stuck.
Code to Recieve The Request :
sRequest = sBuffer.Substring(0, iStartPos - 1);
sRequest.Replace("\\", "/");
if ((sRequest.IndexOf(".") < 1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);
sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - 3);
if (sDirName == "/")
sLocalDir = sMyWebServerRoot;
else
{
//Get the Virtual Directory
// sLocalDir = GetLocalPath(sMyWebServerRoot, sDirName);
Console.WriteLine("i am here");
sDirName = sDirName.Substring(1, sDirName.Length - 2);
//sDirName = sDirName.Replace("/", "\\");
Console.WriteLine("Amit:" + sDirName);
string test1 = Path.Combine("C:\\test\\", sDirName);
sLocalDir = Path.Combine(#"C:\\test", sDirName);
}
Now to List Dir I have the following Function :
public String listdir(string sLocaldir,string sDirName)
{
string sresult = "";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine("<head>");
sb.AppendLine("<title>Test</title>");
sb.AppendLine("</head>");
sb.AppendLine("<body>");
sb.AppendLine("<h1><center><u>Listing Folders Under " + sLocaldir + "</h1></u></center>");
string[] folderpaths = Directory.GetDirectories(sLocaldir);
sb.AppendLine("<font color=red><font size=5>Listing Directories<br>");
for (int i = 0; i < folderpaths.Length; i++)
{
string fpath = folderpaths[i];
string[] foldernames = fpath.Split('\\');
int j = foldernames.Length - 1;
string fname = foldernames[j];
string fullname;
if (sDirName != "/")
{
//fname= fname + "\\";
fullname = sDirName +"/"+ fname;
//fullname = fullname.Replace("\\", "/");
//fullname = Path.GetPathRoot("C:\\test");
Console.WriteLine("Get full path:" + fullname);
}
else
{
fullname = fname;
}
Console.WriteLine("Full Test:" + fullname);
//sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(fullname )),
HttpUtility.HtmlEncode(fname)));
}
string[] filePaths = Directory.GetFiles(#"C:\test");
sb.AppendLine("<font color=red><font size=5>Listing Files<br>");
for (int i = 0; i < filePaths.Length; ++i)
{
string name = Path.GetFileName(filePaths[i]);
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(name)),
HttpUtility.HtmlEncode(name)));
}
sb.AppendLine("</ul>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");
sresult = sb.ToString();
return sresult;
//Console.WriteLine(sresult);
}
Any help would be highly appreciated.
Thank you
%2F is safe encoding for the / symbol. You are HTMLEncoding the / symbol in your code above.
Your approach can be much simpler see:
http://www.codeproject.com/KB/IP/mywebserver.aspx