I have a WEB API C#, inside it I have Data which is a link, for example: images/Chinese/AbaloneEggCustard.jpg
but in JSON, it appear like this:
[{"BackgroundImage":"images\/Chinese\/AbaloneEggCustard.jpg", ......}]
May I know how can I remove the slash? Need it remove so hopefully I can access the images when I link with azure.
Here's my controller codes:
public IEnumerable<Food> Get()
{
List<Food> Cases = new List<Food>();
try
{
string connectionString = ConfigurationManager.ConnectionStrings["HealthyFoodDBConnectionString"].ConnectionString;
myConnection = new SqlConnection(connectionString);
myConnection.Open();
string sql = "SELECT * from [Recipe] ";
myCommand = new SqlCommand(sql, myConnection);
myDataReader = myCommand.ExecuteReader();
while (myDataReader.Read())
{
Cases.Add(new Food()
{
RecipeID = (int)myDataReader["RecipeID"],
RecipeTitle = (string)myDataReader["RecipeTitle"],
FoodCategoryID = Convert.ToInt32(myDataReader["FoodCategoryId"]),
Serves = (string)myDataReader["Serves"],
PerServing = (string)myDataReader["PerServing"],
Favourite = ((Convert.ToInt32(myDataReader["Favourite"]) == 1) ? true : false),
Directions = (string)myDataReader["Directions"],
BackgroundImage = (string)myDataReader["BackgroundImage"],
HealthyTips = (string)myDataReader["HealthyTips"],
Nutritions = (string)myDataReader["Nutritions"],
Ingredients = (string)myDataReader["Ingredients"]
});
}
}
finally
{
if (myConnection != null)
myConnection.Close();
}
return Cases;
}
here's my Index.cshtml code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
// Send an AJAX request
$.getJSON("api/food/",
function (data) {
// on success, 'data' contains a list of products
$.each(data, function (key, val){
//format the text to display
var str = val.RecipeTitle + ' | ' + val.FoodCategoryID + ' | ' + val.Serves + ' | ' + val.PerServing + ' | ' + val.Favourites + ' | ' + val.Directions + ' | ' + val.BackgroundImage + ' | ' + val.HealthyTips + ' | ' + val.Nutritions + ' | ' + val.Ingredients;
// add a list item for the product
$('<li/>', { html: str }).appendTo($('#cases'));
});
});
});
Assuming you're calling the API, and getting back the normally escaped JSON object:
var myObject = Foo.API.Call(); //returns object with BackgroundImage property.
If you're saving the result to a text file, you can use JavaScriptSerializer:
var bg = new JavaScriptSerializer().Deserialize(myObject);
using (var writer = new StreamWriter(#"C:\foo.txt"))
{
writer.Write(bg.BackgroundImage);
}
The text file saved should be the unescaped string.
You can use this:
string deserializedString = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(serializedString);
Related
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);
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'm trying to download a file from server but this thing won't work. Been tring doing it for more than 2 weeks. Here is the code:
IN CSHTML PAGE:
<script type="text/x-jsrender" id="docView">
View
</script>
<script>
function docView(id) {
docId = id;
$.ajax({
type: "GET",
url: '#Url.Action("DownloadFile", "Profile")' + "?docid=" + docId,
dataType: "json",
success: function (result) {
},
});
</script>
IN MVC Controller:
[HttpGet]
public ActionResult DownloadFile(Guid? docid)
{
int i = 1;
string key = ConfigurationManager.AppSettings["PhysicalDocumentPath"];
JApplicantDocument value = new JApplicantDocument();
var response = new Response();
var fName = "";
var savefileName = "";
var fileSavePath = "";
var prevPath = "";
var nextPath = "";
try
{
IApplicantDataService applicantDataService = new ApplicantDataService();
response = applicantDataService.GetDocument(docid, value);
var fileName = value.ApplicantId + "_" + value.DocumentName;
fName = fileName;
savefileName = fileName;
fileSavePath = Path.Combine(key, fileName);
prevPath = fileSavePath;
nextPath = fileSavePath;
var tmp = fileName.Split('.');
var tmp1 = tmp[0];
while (System.IO.File.Exists(nextPath)) //to get the latest file
{
tmp = fileName.Split('.');
fileName = tmp1 + i.ToString();
fileName = fileName + "." + tmp[1];
savefileName = fileName;
nextPath = Path.Combine(key, savefileName);
if (System.IO.File.Exists(nextPath))
{
prevPath = nextPath;
}
i++;
tmp = prevPath.Split(new string[] { "Docs\\" }, StringSplitOptions.None);
fName = tmp[1];
response.Message = prevPath;
}
}
catch (Exception e)
{
Utils.Write(e);
}
return File(prevPath, value.Format);
}
I just want on click of View button to download the file as per this(http://www.c-sharpcorner.com/UploadFile/db2972/file-download-sample-in-mvc-day-40/). i cannot use location.href(...) directly in tag due to the fact that i'm using it in script jsrender which is being used in syncfusion grid controls. Hence I wont be able to get the docid at all.
I am using Autocad 2014 with C#. I need to create a partial CUI.
I reference to Kean code via this link here
But it does not work as stated in the block.I encounter with follwing error.
Autodesk.AutoCAD.Customization.FileSaveException: Write permission denied. Unable to create: 'c:\MicHydro.cuix' ---> System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.
at Autodesk.AutoCAD.Customization.CustWrap.SaveToMenuPackageFormat(Boolean saveAll).
Here is my code:
public class Commands : IExtensionApplication
{
public void Initialize()
{
BuildMenuCUI();
}
public void Terminate()
{
}
[CommandMethod("BuildCUI")]
public void BuildMenuCUI()
{
const string myCuiFile = "c:\\MicHydro.cuix";
const string myCuiFileToSend = "c:/MicHydro.cuix";
const string myCuiSectionName = "MicHydro";
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
string mainCui = Application.GetSystemVariable("MENUNAME") + ".cuix";
CustomizationSection cs = new CustomizationSection(mainCui);
PartialCuiFileCollection pcfc = cs.PartialCuiFiles;
if (pcfc.Contains(myCuiFile))
{
ed.WriteMessage(
"\nCustomization file \""
+ myCuiFile
+ "\" already loaded."
);
}
else
{
if (System.IO.File.Exists(myCuiFile))
{
ed.WriteMessage(
"\nCustomization file \""
+ myCuiFile
+ "\" exists - loading it."
);
LoadMyCui(myCuiFileToSend);
}
else
{
ed.WriteMessage(
"\nCustomization file \""
+ myCuiFile
+ "\" does not exist - building it."
);
// Create a customization section for partial menu
CustomizationSection pcs = new CustomizationSection();
pcs.MenuGroupName = myCuiSectionName;
// add a menu group, with two commands
MacroGroup mg =
new MacroGroup(myCuiSectionName, cs.MenuGroup);
MenuMacro mm1 =
new MenuMacro(mg, "Cmd 1", "^C^CCmd1", "ID_MyCmd1");
MenuMacro mm2 =
new MenuMacro(mg, "Cmd 2", "^C^CCmd2", "ID_MyCmd2");
// Now let's add a pull-down menu, with two items
StringCollection sc = new StringCollection();
sc.Add("POP15");
PopMenu pm =
new PopMenu(
myCuiSectionName,
sc,
"ID_MyPop1",
pcs.MenuGroup
);
PopMenuItem pmi1 =
new PopMenuItem(mm1, "Pop Cmd 1", pm, -1);
PopMenuItem pmi2 =
new PopMenuItem(mm2, "Pop Cmd 2", pm, -1);
// Finally save the file and load it
// pcs.SaveAs(myCuiFile);
LoadMyCui(myCuiFileToSend);
}
}
}
private void LoadMyCui(string cuiFile)
{
Autodesk.AutoCAD.ApplicationServices. Document doc =
Application.DocumentManager.MdiActiveDocument;
object oldCmdEcho =
Application.GetSystemVariable("CMDECHO");
object oldFileDia =
Application.GetSystemVariable("FILEDIA");
Application.SetSystemVariable("CMDECHO", 0);
Application.SetSystemVariable("FILEDIA", 0);
doc.SendStringToExecute(
"_.cuiload "
+ cuiFile
+ " ",
false, false, false
);
doc.SendStringToExecute(
"(setvar \"FILEDIA\" "
+ oldFileDia.ToString()
+ ")(princ) ",
false, false, false
);
doc.SendStringToExecute(
"(setvar \"CMDECHO\" "
+ oldCmdEcho.ToString()
+ ")(princ) ",
false, false, false
);
}
}
Thanks in advance.
i am printing a gridview in asp.net that is contained within a panel - it works in IE perfectly
In Opera 12.02 it appears to be printing out my main form not the print page ? Do you know why this is.
In Mozilla firefox 16.0.2 it only loads one page in the print preview and prints that one page? Do you know why this is?
I'm assuming the issue is in my javascript - i can post markup if needed but hopefully that will not be required.
thanks
Damo
javascript
<script type="text/javascript">
function PrintGridData(GridToPrint, PanelName) {
try {
var Grid = document.getElementById(GridToPrint);
var printContent = document.getElementById(PanelName);
//alert(printContent);
if (Grid) // See if the Grid Exists First
{
if (Grid.rows.length > 0) { // See if the Grid contains any rows
var windowUrl = 'about:blank';
var UserLoggedIn = $("#lblUser").text()
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
var Database = 'ProductionDatabase';
var windowName = 'Report';
var AuditPrintDetailEverypage = UserLoggedIn + ' Time : ' + strDateTime ;
var AuditPrintDetailLastPage = ' System Report ' + ' Source Database: ';
var WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<' + 'html' + '><head><link href="assets/css/Print.css" rel="stylesheet" type="text/css" /><title>' + AuditPrintDetailEverypage + '</title> </head><' + 'body style="background:none !important"' + '>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write(' ' + AuditPrintDetailLastPage);
WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
WinPrint.document.close();
//alert(printContent.innerHTML);
//alert(WinPrint.document);
if (window.opera) {
//alert('opera browser detected')
window.onload = window.print();
//window.onload = WinPrint.print();
//WinPrint.close();
}
else {
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
}
else { // No Results to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Results to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
}
}
else { // No Grid to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Grid to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
function AddZero(num) {
try {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
</script>
window.onload = window.print(); should be window.onload = window.print;
Also my css had overflow: hidden; which opera and mozilla dont like so i removed these
now its working ok
thanks
damo