The following is my code for using Google Translate. I have one dll I added as a reference: Google.Apis.Translate.V2
I also bought Google Translate API key.
I have 5 errors since I don't know what dll I need more: These objects do not exist missing namespace: DataContractJsonSerializer , TranslationRootObject , TranslationRootObject
What dll reference do I need for these namespaces?
This is my code, without my API key:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
namespace Google_Translate
{
public partial class Form1 : Form
{
static string apiKey = "";
static string texttotranslate = "hello world";
string text;
static String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
static String url = String.Format(apiUrl, apiKey, "en", "ge", texttotranslate);
Stream outputStream = null;
byte[] bytes = Encoding.ASCII.GetBytes(url);
// create the http web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
public Form1()
{
InitializeComponent();
webRequest.KeepAlive = true;
webRequest.Method = "POST";
// Overrride the GET method as documented on Google's docu.
webRequest.Headers.Add("X-HTTP-Method-Override: GET");
webRequest.ContentType = "application/x-www-form-urlencoded";
// send POST
try
{
webRequest.ContentLength = bytes.Length;
outputStream = webRequest.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();
}
catch (HttpListenerException e)
{
/*...*/
}
translate();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private string translate()
{
try
{
// get the response
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK && webRequest != null)
{
// read response stream
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string lista = sr.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationRootObject));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(lista));
TranslationRootObject tRootObject = (TranslationRootObject)serializer.ReadObject(stream);
string previousTranslation = string.Empty;
//deserialize
for (int i = 0; i < tRootObject.Data.Detections.Count; i++)
{
string translatedText = tRootObject.Data.Detections[i].TranslatedText.ToString();
if (i == 0)
{
text = translatedText;
}
else
{
if (!text.Contains(translatedText))
{
text = text + " " + translatedText;
}
}
}
return text;
}
}
}
catch (HttpListenerException e)
{
/*...*/
}
return text;
}
}
}
Can someone fix my code or tell me whats wrong please ?
What I need is to translate 29-33kb text file size and I wonder if it's possible to translate it as fast as it does online when using the Google Translate site.
I also found this link Google Translate V2 cannot hanlde large text translations from C# which someone say the translation can't translate big files so I wonder if 29-33kb files are counting as big? If so maybe someone can take a look at the link and fix my code according to the answer in the link I tried a lot now and didn't understand it really. But first I need to find why my original code here doesn't work.
In your project, add a reference to this assembly:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
There may be others you need, I just looked up this one.
Related
I have no access to Sharepoint server, only like standard user from web page. I can upload manually there my documents. I tried to solve it via C# and I complet any code from examples from net. Our Sharepoint is 2007. My code run without any error. I put there control text to see if its proceed. All runs fine but nothing happens in Sharepoint page, no doc is uploaded. I have no idea why its do nothing :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace Sharepoint
{
class Program
{
public static void CopyStream(Stream read, Stream write)
{
int len; byte[] temp = new byte[1024];
while ((len = read.Read(temp, 0, temp.Length)) > 0)
{
write.Write(temp, 0, len);
/// Console.WriteLine("test");
}
}
static void Main(string[] args)
{
Uri destUri = new Uri("http://gaja/mBreSKCZ/mreports/sales/reportysales/Test_new.txt");
using (FileStream inStream = File.OpenRead(#"C:\Users\TK20382\Test_new.txt"))
{
WebRequest req = WebRequest.Create(destUri);
req.Method = "PUT";
req.Credentials = CredentialCache.DefaultCredentials; // assuming windows Auth
Console.WriteLine("test");
Console.ReadKey();
using (Stream outStream = req.GetRequestStream())
{
CopyStream(inStream, outStream);
}
}
}
}
}
You are missing HttpWebRequest.GetResponse Method which basically invokes PUT request. In addition if you are targeting .NET Framework >=2.0 version, then CopyStream method could be omitted and the line:
CopyStream(inStream, outStream);
replaced with:
inStream.CopyTo(outStream);
Modified version
public static string UploadFile(string targetUrl,ICredentials credentials, string sourcePath)
{
var request = WebRequest.Create(targetUrl);
request.Method = "PUT";
request.Credentials = credentials;
using (var fileStream = File.OpenRead(sourcePath))
using (var requestStream = request.GetRequestStream())
{
fileStream.CopyTo(requestStream);
}
using (var response = request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
Usage
UploadFile("https://contoso.intranet.com/documents/guide.docx", CredentialCache.DefaultCredentials, #"D:\guide.docx");
Alternatively WebClient.UploadFile Method could be utilized as shown below:
public static void UploadFile(string targeUrl, ICredentials credentials, string fileName)
{
using (var client = new WebClient())
{
client.Credentials = credentials;
client.UploadFile(targeUrl, "PUT", fileName);
}
}
i have a problem in converting a regex match (that is basically a string) to an integer.
Match results = Regex.Match(websr.ReadToEnd(),
"\\d+\\S+\\d+ results", RegexOptions.Singleline);
var count = Regex.Match(results.ToString(), "\\d+\\S+\\d+");
these two lines are regex . i want to extract the number of results. "count" shows the correct number of results. in next step i want to convert it to integer type
i tried {int countN = int.parse(count.ToString())} or {Int32.TryParse(count,out countN)} and many other cases but returns "Input string was not in a correct format" or shows 0 in listbox.
i'm really confused by this.i tried many tricks but no success.
thanks for help :)
edit :
here is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
namespace bing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.bing.com/");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader response1 = new StreamReader(response.GetResponseStream());
cookies = response.Cookies;
try
{
string web = "http://www.bing.com";
//post
string getUrl = (web + "/search?q=" + textBox1.Text);
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(getUrl);
HttpWebResponse webrep = (HttpWebResponse)webreq.GetResponse();
StreamReader websr = new StreamReader(webrep.GetResponseStream());
Match results = Regex.Match(websr.ReadToEnd(), "\\d+\\S+\\d+ results", RegexOptions.Singleline);
var count = Regex.Match(results.ToString(), "\\d+\\S+\\d+");
int countN = int.Parse(count.Value);
listBox1.Items.Add(countN.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
You should use:
var count = int.Parse(Regex.Match(results.ToString(), "\\d+\\S+\\d+").Value);
Verify there is only numbers in the input string.
solved
when i extracted the result number, it was something like 123,456,789 and the problem was "," between digits.
Match results = Regex.Match(websr.ReadToEnd(), "\\d+\\S+\\d+ results", RegexOptions.Singleline);
Match count = Regex.Match(results.ToString(), "\\d+\\S+\\d+");
string countN = count.Value.Replace(",", "");
int countM = int.Parse(countN);
and countM shows 123456789
thanks to all friends whom answered :)
After managing to load data to my Rails Server through c# (check here to know what i am talking about), i am now trying to upload a file to that same server, along with other data.
In Ruby, I am able to do this with the code :
require 'HTTMultiParty'
class ReceiptCreate
include HTTMultiParty
# Log to file
# debug_output File.new("httparty1.log", "w+")
base_uri "localhost:3000"
format :json
headers "Accept" => "application/json"
def initialize
end
def post(machine_serial,filepath,tag_number,token)
options = { body:
{receipt:
{tag_number:tag_number,
receipt_file: File.new(filepath),
ispaperduplicate:0
},
machine:
{serial_number: machine_serial,
safe_token: token
}
}
}
self.class.post('/receipts', options)
end
end
receipt = ReceiptCreate.new()
filename1 = "C:\\filename1.pdf"
filename2 = "C:\\filename2.pdf"
response=receipt.post("2803433",filename2,"p94tt7w","123")
puts response
an when I inspect the parameters on the rails server i see
Parameters: {"receipt"=>{"tag_number"=>"p94tt7w", "receipt_file"=>#<ActionDispatch::Http::UploadedFile:0x4183ea8 #original_filename="Invoice.pdf", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"receipt[receipt_file]\"; filename=\"Invoice.pdf\"\r\nContent-Length: 11653\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n", #tempfile=#<File:C:/Users/diogo/AppData/Local/Temp/RackMultipart20130103-18168-efiqia>>, "ispaperduplicate"=>"0"}, "machine"=>{"serial_number"=>"2803433", "safe_token"=>"123"}}
But if i try to do the same with my c# code below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
namespace RonRestClient
{
class templateRequest
{
public Receipt receipt;
public class Receipt
{
public float total;
public String tag_number;
public bool ispaperduplicate = true;
public byte[] receipt_file;
public Receipt(float total, String tagnr, string filepath)
{
this.total = total;
this.tag_number = tagnr;
this.receipt_file = File.ReadAllBytes(filepath);
}
};
public Machine machine;
public class Machine
{
public String serial_number;
public String safe_token;
public Machine(String machinenr, String safe_token)
{
this.serial_number = machinenr;
this.safe_token = safe_token;
}
};
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\filename2.pdf";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";
float total = 100;
templateRequest req = new templateRequest();
req.receipt = new templateRequest.Receipt(total, tagnr, path);
req.machine = new templateRequest.Machine(machinenr, safe_token);
//string json_body = JsonConvert.SerializeObject(req);
//string json_body = new JavaScriptSerializer().Serialize(req);
//var json_body = "{\"receipt\" : {\"total\":"+total+", \"tag_number\":\""+tagnr+"\",\"ispaperduplicate\":true},\"machine\":{\"serial_number\": \""+machinenr+"\",\"safe_token\": \""+safe_token+"\"}}";
var client = new RestClient("http://localhost:3000/receipts");
var request = new RestRequest(Method.POST);
//set request Body
request.AddHeader("Content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddBody(req);
//request.AddParameter("application/json", json_body, ParameterType.RequestBody);
// easily add HTTP Headers
// add files to upload (works with compatible verbs)
//request.AddFile("receipt/receipt_file",path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
if(response.ErrorMessage !="") content += response.ErrorMessage;
response_box.Text = content;
}
}
}
I get this
Parameters: {"receipt"=>{"total"=>100, "tag_number"=>"p94tt7w", "ispaperduplicate"=>true, "receipt_file"=>[37, 80, [n3...nX], 10]}, "machine"=>{"serial_number"=>"2803433", "safe_token"=>"123"}}
This seems to mean basically that Restsharp just thinks that my file is just another field.
RestSharp seems to have a method to add files request.AddFile("receipt/receipt_file",path);, and i believe that this should probably be the way to go...but when i just try and add the file, i get an error message saying :
This property cannot be set after writing has started.
Do I need to set each attribute of the file separately?
EDIT
Meanwhile i found this post, changed my code to :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;
namespace RonRestClient
{
class templateRequest
{
public Receipt receipt;
public class Receipt
{
//public float total;
public String tag_number;
public bool ispaperduplicate = true;
//public byte[] receipt_file;
public Receipt(String tagnr)
{
//this.total = total;
this.tag_number = tagnr;
// this.receipt_file = File.ReadAllBytes(filepath);
}
};
public Machine machine;
public class Machine
{
public String serial_number;
public String safe_token;
public Machine(String machinenr, String safe_token)
{
this.serial_number = machinenr;
this.safe_token = safe_token;
}
};
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\filename2.pdf";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";
float total = 100;
templateRequest req = new templateRequest();
req.receipt = new templateRequest.Receipt(tagnr);
req.machine = new templateRequest.Machine(machinenr, safe_token);
var request = new RestRequest("/receipts",Method.POST);
request.AddParameter("receipt[total]", total);
request.AddParameter("receipt[tag_number]", tagnr);
request.AddParameter("machine[serial_number]", machinenr);
request.AddParameter("machine[safe_token]", safe_token);
request.AddFile("receipt[receipt_file]", File.ReadAllBytes(path), "Invoice.pdf", "application/octet-stream");
// Add HTTP Headers
request.AddHeader("Content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
//set request Body
//request.AddBody(req);
// execute the request
//calling server with restClient
RestClient restClient = new RestClient("http://localhost:3000");
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
//upload successfull
MessageBox.Show("Upload completed succesfully...\n" + response.Content);
}
else
{
//error ocured during upload
MessageBox.Show(response.StatusCode + "\n" + response.StatusDescription);
}
});
}
}
}
and now am getting the parameters :
Parameters: {"receipt"=>{"total"=>"100", "tag_number"=>"p94tt7w", "receipt_file"=>#<ActionDispatch::Http::UploadedFile:0x3db42d8 #original_filename="Invoice.pdf", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"receipt[receipt_file]\"; filename=\"Invoice.pdf\"\r\nContent-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Users/diogo/AppData/Local/Temp/RackMultipart20130103-18168-9mbt3h>>}, "machine"=>{"serial_number"=>"2803433", "safe_token"=>"123"}}
Along with an HTTP 422 - Unprocessable Entity error.
If I am to compare these parameters with the ones that i have working from the ruby code, now the only difference seems to be that this last message does not have the Content-length and Content-Transfer-Encoding fields...
Do you have any idea on how i might add the attributes?
This was a fight... In the end I discovered two different ways of solving this problem. The irony of it, as so many of coding problems, was that all i had to do was setting the right parameters in first place...Just one missing parameter cost me more than 4 hours..
Both detailed below :
1 - Use RestSharp (the total field shouldn't be there, and the ispaperduplicate field was missing)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;
namespace RonRestClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\filename2.pdf";
//localhost settings
string requestHost = #"http://localhost:3000/receipts";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";
// Do it with RestSharp
templateRequest req = new templateRequest();
req.receipt = new templateRequest.Receipt(tagnr);
req.machine = new templateRequest.Machine(machinenr, safe_token);
var request = new RestRequest("/receipts", Method.POST);
request.AddParameter("receipt[tag_number]", tagnr);
request.AddParameter("receipt[ispaperduplicate]", 0);
request.AddParameter("machine[serial_number]", machinenr);
request.AddParameter("machine[safe_token]", safe_token);
request.AddFile("receipt[receipt_file]", File.ReadAllBytes(path), Path.GetFileName(path), "application/octet-stream");
// Add HTTP Headers
request.AddHeader("Content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
//set request Body
//request.AddBody(req);
// execute the request
//calling server with restClient
RestClient restClient = new RestClient("http://localhost:3000");
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
//upload successfull
MessageBox.Show("Upload completed succesfully...\n" + response.Content);
}
else
{
//error ocured during upload
MessageBox.Show(response.StatusCode + "\n" + response.StatusDescription);
}
});
}
}
}
2 - Use FileStream with HttpWebRequest (thank you Clivant)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;
namespace RonRestClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Projectos\My Training Samples\Adobe Sample\RBO1574.pdf";
//localhost settings
string requestHost = #"http://localhost:3000/receipts";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";
FileStream fs1 = File.OpenRead(path);
long filesize = fs1.Length;
fs1.Close();
// Create a http request to the server endpoint that will pick up the
// file and file description.
HttpWebRequest requestToServerEndpoint =
(HttpWebRequest)WebRequest.Create(requestHost);
string boundaryString = "FFF3F395A90B452BB8BEDC878DDBD152";
string fileUrl = path;
// Set the http request header \\
requestToServerEndpoint.Method = WebRequestMethods.Http.Post;
requestToServerEndpoint.ContentType = "multipart/form-data; boundary=" + boundaryString;
requestToServerEndpoint.KeepAlive = true;
requestToServerEndpoint.Credentials = System.Net.CredentialCache.DefaultCredentials;
requestToServerEndpoint.Accept = "application/json";
// Use a MemoryStream to form the post data request,
// so that we can get the content-length attribute.
MemoryStream postDataStream = new MemoryStream();
StreamWriter postDataWriter = new StreamWriter(postDataStream);
// Include value from the tag_number text area in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"receipt[tag_number]",
tagnr);
// Include ispaperduplicate text area in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"receipt[ispaperduplicate]",
0);
// Include value from the machine number in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"machine[serial_number]",
machinenr);
// Include value from the machine token in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"machine[safe_token]",
safe_token);
// Include the file in the post data
postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n"
+ "Content-Length: \"{2}\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n\r\n",
"receipt[receipt_file]",
Path.GetFileName(fileUrl),
filesize);
postDataWriter.Flush();
// Read the file
FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postDataStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
postDataWriter.Flush();
// Set the http request body content length
requestToServerEndpoint.ContentLength = postDataStream.Length;
// Dump the post data from the memory stream to the request stream
Stream s = requestToServerEndpoint.GetRequestStream();
postDataStream.WriteTo(s);
postDataStream.Close();
}
}
}
Before you ask if I've looked at google let me answer yes, I've read page after page. Site after site, and wasn't able to get the information that I needed.
I'm trying to make a very simple update checker for my application. One that will parse the online xml file, and display the data in certain places. As well as being able to parse out the link for the download location(Will not be ftp or anything, but something like a filehost since my hosting plan doesn't allow me to ftp files over 3MBs)
Anyway here is what I got thus far:
XML Code:
<code>
<Info>
<Version>2.8.0.0</Version>
<Link>www.filehost.com</Link>
<Description>Added New Features To GUI</Description>
</Info>
</code>
Here's the application code, and what I want it to show and do.
using System;
using System.Windows.Forms;
using System.Xml;
namespace SAM
{
public partial class UpdateCheck : DevExpress.XtraEditors.XtraForm
{
public UpdateCheck()
{
InitializeComponent();
lblCurrentVersion.Text = "Current Version: " + Application.ProductVersion;
}
private void MainForm_Shown(object sender, EventArgs e)
{
BringToFront();
}
private void BtnChkUpdate_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("http://www.crimson-downloads.com/SAM/UpdateCheck.xml");
}
}
}
I'm looking to have the application parse the xml in this way.
<Version>2.8.0.0</Version> Will change the text for "lblUpdateVersion" like how I got the current version label set in the InitializeComponent();
<Description>Added New Features To GUI</Description> to be parsed out into the "textDescription" Which I can probably do myself.
<Link>www.filehost.com</Link> Will parse into the button control so when pressed will open up the users default browser and follow the link.
I've done the exact thing this in an application of my own.
First, you store an XML file on your webhost that holds the updater information. Mine is at http://getquitter.com/version.xml and is structured as follows:
<versioninformation>
<latestversion>1.2.0.0</latestversion>
<latestversionurl>http://www.getquitter.com/quitter-1.2.0.zip</latestversionurl>
<filename>quitter-1.2.0.zip</filename>
</versioninformation>
Second, write a method to retrieve that xml from your host:
Public Function GetWebPage(ByVal URL As String) As String
Dim Request As System.Net.HttpWebRequest = CType(WebRequest.Create(New Uri(URL)), HttpWebRequest)
With Request
.Method = "GET"
.MaximumAutomaticRedirections = 4
.MaximumResponseHeadersLength = 4
.ContentLength = 0
End With
Dim ReadStream As StreamReader = Nothing
Dim Response As HttpWebResponse = Nothing
Dim ResponseText As String = String.Empty
Try
Response = CType(Request.GetResponse, HttpWebResponse)
Dim ReceiveStream As Stream = Response.GetResponseStream
ReadStream = New StreamReader(ReceiveStream, System.Text.Encoding.UTF8)
ResponseText = ReadStream.ReadToEnd
Response.Close()
ReadStream.Close()
Catch ex As Exception
ResponseText = String.Empty
End Try
Return ResponseText
End Function
Next, call this method to get the xml and load into an xml document.
Dim VersionInfo As New System.Xml.XmlDocument
VersionInfo.LoadXml(GetWebPage("http://www.getquitter.com/version.xml"))
With version.xml loaded, you can now parse out the individual pieces of data you need to determine whether or not you need to grab the new version.
Dim LatestVersion As New Version(QuitterInfoXML.SelectSingleNode("//latestversion").InnerText)
Dim CurrentVersion As Version = My.Application.Info.Version
If LatestVersion > CurrentVersion Then
''download the new version using the Url in the xml
End If
This is how my application does it. You can download the source code if you like (it's an open source application) if you'd like to use it as a model. It's at http://quitter.codeplex.com. Hope this helps!
using System;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.IO;
using System.Diagnostics;
namespace SAM
{
public partial class UpdateCheck : DevExpress.XtraEditors.XtraForm
{
public UpdateCheck()
{
InitializeComponent();
lblCurrentVersion.Text = "Current Version: " + Application.ProductVersion;
}
private void MainForm_Shown(object sender, EventArgs e)
{
BringToFront();
}
public static string GetWebPage(string URL)
{
System.Net.HttpWebRequest Request = (HttpWebRequest)(WebRequest.Create(new Uri(URL)));
Request.Method = "GET";
Request.MaximumAutomaticRedirections = 4;
Request.MaximumResponseHeadersLength = 4;
Request.ContentLength = 0;
StreamReader ReadStream = null;
HttpWebResponse Response = null;
string ResponseText = string.Empty;
try
{
Response = (HttpWebResponse)(Request.GetResponse());
Stream ReceiveStream = Response.GetResponseStream();
ReadStream = new StreamReader(ReceiveStream, System.Text.Encoding.UTF8);
ResponseText = ReadStream.ReadToEnd();
Response.Close();
ReadStream.Close();
}
catch (Exception ex)
{
ResponseText = string.Empty;
}
return ResponseText;
}
private void BtnChkUpdate_Click(object sender, EventArgs e)
{
System.Xml.XmlDocument VersionInfo = new System.Xml.XmlDocument();
VersionInfo.LoadXml(GetWebPage("http://www.crimson-downloads.com/SAM/UpdateCheck.xml"));
lblUpdateVersion.Text = "Latest Version: " + (VersionInfo.SelectSingleNode("//latestversion").InnerText);
textDescription.Text = VersionInfo.SelectSingleNode("//description").InnerText;
}
private void simpleButton2_Click(object sender, EventArgs e)
{
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "http://www.crimson-downloads.com/SAM/Refresh.htm";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
}
}
}
Short and simple. Thanks man, was having trouble with something else that uses xml, but with the help you gave me I was able to apply the knowledge to that as well and got it working to.
Does anyone have experience using the Facebook Developer Toolkit? I am trying to post something to a Facebook user's Wall, but can't figure out how to use the API? Could someone could give me an example or point me to some documentation on the API's usage?
I actually found documentation and samples to do what I was looking for here: http://facebooktoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28001
EDIT:
After initializing the Facebook session I called the Stream.Publish() method on the API.
FacebookService.API.stream.publish(...);
I created a video tutorial showing how to do exactly this. Here is the link:
http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet
And here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace FBO
{
public partial class facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "374961455917802";
string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
string scope = "publish_stream,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
}
}
}
}
Bit late, but maybe it still helps others: http://facebooktoolkit.codeplex.com/Thread/View.aspx?ThreadId=75412