I am trying to update a row in Hbase from a MVC site. I am using .NET 4.5 and the best solution I have found to do this is using the Thrift package and Hbase.Thrift to do this.
I have :
private static Hbase.Client _hbase; //this is actually a class header
var socket = new TSocket("localhost",9090);
var transport = new TBufferedTransport(socket);
var proto = new TBinaryProtocol(transport);
_hbase = new Hbase.Client(proto);
try
{
transport.Open();
_hbase.mutateRows(Encoding.UTF8.GetBytes("Images"), new List<BatchMutation>()
{
new BatchMutation()
{
Row = Guid.NewGuid().ToByteArray(),
Mutations = new List<Mutation> {
new Mutation{Column = Encoding.UTF8.GetBytes("Image"), IsDelete = false, Value = Encoding.UTF8.GetBytes(testImage) }
}
}
});
transport.Close();
}
While this creates a new image in a given column I have not found a way for it to overwrite and existing column. Has anyone successfully pulled this off or is there another client tool I should be using to achieve what I am going for?
I was unable to get this setup to work so I went on to use Hbase Rest. Here is the code for the future lost souls looking for the solution as I was.
System.Diagnostics.Debug.WriteLine("Hbase_update");
//check your port number to make sure you have the right one
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"http://localhost:8080/Images/" + key + "?data=");
request.Method = "PUT";
//NOTE:The name of the column I am pushing to is int the Column Family "Image" and column "Binary"
string requestStr = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><CellSet><Row key=""" + Convert.ToBase64String(Encoding.UTF8.GetBytes(key)) + #"""><Cell column=""" + Convert.ToBase64String(Encoding.UTF8.GetBytes("Image:Binary")) + #""">"+ imageBinary + #"</Cell></Row></CellSet>";
var data = Encoding.ASCII.GetBytes(requestStr);
request.Accept = "text/xml";
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = data.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
try
{
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
System.Diagnostics.Debug.WriteLine(responseString);
}
catch (System.Net.WebException e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
Related
So, basically I am creating a Windows Service that is going to consult a SOAP Service and after that return an item. To find that item, who made the service created 2 "filters". customerFilter and itemFilter.
So, when I create the web request I need to insert thoose 2 parameters.
I have this:
static string date = DateTime.Now.Date.ToString("yyyy_MM_dd");
static string pathLog = "Logs/LogGetSalesLineDiscount/" + date + "LogGetSalesLineDiscount.txt";
public static string[] CallWebService(IOrganizationService service)
{
var action = "http://...";
var url = "http://...";
var request = (HttpWebRequest)WebRequest.Create(url);
var postData = "customerFilter=" + Uri.EscapeDataString("TESTE");
postData += "&itemFilter=" + Uri.EscapeDataString("TESTE");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Headers.Add("SOAPAction", action);
request.ContentLength = data.Length;
request.Accept = "text/xml";
request.Credentials = new NetworkCredential("...", "...");
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + pathLog, true))
{
file.WriteLine(responseString);
}
return null;
}
}
If I have that, it will return an error 500. I donĀ“t know why.
If I remove the action, it will return something about all the actions in the service...
Please help me, I dont know what to do....
I am developing a desktop application which communicates with our mobile application. They use Firebase as database but since Firebase doesn't support C# I am having really hard times. I could find a solution for Select&Insert operations but I am really stacked at Update&Delete operations.
public void recordEntry(Record rec) {
var json = JsonConvert.SerializeObject(rec);
var request = WebRequest.CreateHttp("firebaseLink");
request.Method = "POST";
request.ContentType = "application/json";
var buffer = Encoding.UTF8.GetBytes(json);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
var response = request.GetResponse();
json = (new StreamReader(response.GetResponseStream())).ReadToEnd();
}
And a part of select function is like:
public List<RecordUI> FillDataGridView()
{
string result = null;
var request = WebRequest.CreateHttp("firebaseLink");
request.Method = "GET";
request.ContentType = "application/json";
try
{
var response = (HttpWebResponse)request.GetResponse();
Encoding responseEncoding = Encoding.GetEncoding(response.CharacterSet);
using (StreamReader sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
result = sr.ReadToEnd();
}
JObject json = (JObject)JsonConvert.DeserializeObject(result);
I've tried "request.Method = "DELETE" but it deletes all the database. I think I need a kind of SQL command to delete and update but no idea how to insert it into a Http Request. Any ideas?
I am trying to change the price of an article using the websites API
the documentation for it is at https://www.mkmapi.eu/ws/documentation/API_1.1:Stock
When run the class I get an error 417 Expectation Failed, which is described from the documentation as:
Typically you get a 417 Expectation Failed HTTP status code, when your request has an XML body without the corresponding header and/or the body not sent as text, but its byte representation. Another possible reason for a 417 is, when you send body data with more than 1.024 bytes without adding the header Expect: to your request.
Any help would be appreciated. I should also say that the authentication is not the problem I can download my article prices.
public void UpdateMarketPrice(string MarketID, string NewPrice)
{
// https://www.mkmapi.eu/ws/documentation/API_1.1:Stock
String finalResult;
String method = "PUT";
String url = "https://www.mkmapi.eu/ws/v1.1/stock";
HttpWebRequest request = WebRequest.CreateHttp(url) as HttpWebRequest;
OAuthHeader header = new OAuthHeader();
request.Headers.Add(HttpRequestHeader.Authorization, header.getAuthorizationHeader(method, url));
request.Method = method;
request.ContentType = "text/xml; encoding='utf-8'";
XElement xmlDoc =
new XElement("request",
new XElement("article",
new XElement("idArticle", MarketID),
new XElement("idLanguage", 1),
new XElement("comments", "Edited through the API"),
new XElement("count", 7),
new XElement("price", 11),
new XElement("condition", "NM"),
new XElement("isFoil", false),
new XElement("isSigned", false),
new XElement("isPlayset", false)
)
);
String finalXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + xmlDoc.ToString();
MessageBox.Show(finalXML);
byte[] bytes = Encoding.ASCII.GetBytes(finalXML);
request.ContentLength = bytes.Length;
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
finalResult = reader.ReadToEnd();
}
MessageBox.Show(finalResult);
}
I have read that HttpWebRequest adds an "expect 100 continue" header to requests unless you turn it off. There are servers that possibly don't support this header. And will produce this 417 Expectation Failed message.
You could try setting it to false:
System.Net.ServicePointManager.Expect100Continue = false;
So the header isn't sent.
I've seen this suggested sollution to other similar questions also.
Maybe use StreamWriter ?
using (Stream putStream = request.GetRequestStream())
{
using (var writeStream = new StreamWriter(putStream, Encoding.ASCII))
{
writeStream.Write(finalXML);
}
request.ContentLength = putStream.Length; // I am not sure about that
}
Firstly, I understand this code isn't necessarily "safe" and is VERY basic. I'm learning how to consume rest services with web forms in C# (both are new topics for me). Pretty much the only thing there is 2 textboxes for authentication credentials, a query textbox and button to send the request with a label. I just want to enter the ID1 into the textbox, and then return the First and Last name for the entry with that ID.
I have tried many different ways after thoroughly searching the web but can't seem to figure out the issue.
The Issue: The StreamReader data from the WebResponse isn't coming back as XML.
The Question: How do I return the XML tags that I want? Do I need to parse them? If so, how?
The XDoc version is returning nothing while the straight stream reader is returning a string with some data in addition to numbers that shouldn't be there and no angle brackets. Below is the code as it stands now:
if (QueryTextBox2.Text != "")
{
string tableName = "Entry";
string requestURL = "https://myUrl.com/rest/services/" + tableName;
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml; encoding:='charset=utf-8'";
request.Headers["CustomUserName"] = TextBox1.Text;
request.Headers["CustomPassword"] = TextBox3.Text;
string xml = "<Entry><ID1>" + QueryTextBox2.Text + "</ID1></Entry>";
byte[] byteArray = Encoding.UTF8.GetBytes(xml.ToString());
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK) {
Stream postData = response.GetResponseStream();
StreamReader reader = new StreamReader(postData, Encoding.UTF8);
string result = reader.ReadToEnd();
Label2.Text = result;
} else
{
Label2.Text = "There was an error: " + response.StatusDescription;
}
}
else
{
TextBox2.Text = "Please Enter an ID";
}
}
}
I have also tried using:
XDocument doc = new XDocument();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
doc = XDocument.Parse(reader.ReadToEnd());
string fname = doc.Root.Element("NameFirst").Value;
string lname = doc.Root.Element("NameLast").Value;
Label2.Text = fname + lname;
to replace the whole block within: if statusCode == OK.
The data returned from the firefox Poster add-on is:
<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">Search Results</title>
<id>https://myUrl.com/rest/services</id>
<updated>2015-10-07T09:51:32Z</updated>
<link rel="self" type="application/atom+xml" href="https://myUrl.com/rest/services" />
<entry>
<id>https://myUrl.com/rest/services</id>
<Entry>
<ID1>900009</ID1>
<NameLast>Smith</NameLast>
<NameFirst>Tom</NameFirst>
<NameTitle></NameTitle>
<NamePreferred>Alex</NamePreferred>
<NameWeb>tsmith</NameWeb>
<NameOther></NameOther>
<NameInitials></NameInitials>
</Entry></content></entry></feed>
I've removed a lot of the response data because it's so large and anonymized it all for the most part so keep that in mind.
I would use System.Net.Http.HttpClient, it has a much easier interface for consuming http requests.
I haven't tested the document parsing, but just follow the nested levels in until you find the element you want.
async void Main()
{
var textBox2String = "2"
if (!string.IsNullOrEmpty(textBox2String))
{
const string table = "Entry";
var client = new HttpClient();
var url = $"https://myurl.com/rest/services/{table}";
var xml = $"<Entry><ID1>{textBox2String}</ID1></Entry>";
client.DefaultRequestHeaders.TryAddWithoutValidation("CustomUserName", "username");
client.DefaultRequestHeaders.TryAddWithoutValidation("CustomPassword", "password");
var response = await client.PostAsync(url, new StringContent(xml, Encoding.UTF8, "text/xml"));
var content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var document = XDocument.Parse(content);
var entry = document.Root.Element(table);
var firstName = entry.Element("FirstName").Value;
var lastName = entry.Element("LastName").Value;
$"{firstName} {lastName}".Dump();
}
else
{
Console.WriteLine($"An error occurred processing this request: {content}");
}
}
else
{
textBox2String = "Please enter an ID";
}
}
I am trying to upload some documents to Box and create and retrieve a shared link for each of them.
This is the code I am using for it, but I always retrieve 403:access_denied_insufficient_permissions.
Any idea of why this is happening?
Hope you can help me! Thanks.
// CREATE THE FILE
BoxFileRequest req = new BoxFileRequest
{
Name = zipFile.Name,
Parent = new BoxRequestEntity { Id = newFolder.Id}
};
BoxFile uploadedFile = client.FilesManager.UploadAsync(req, stream).Result;
//REQUEST SHARED LINK
BoxSharedLinkRequest sharedLinkReq = new BoxSharedLinkRequest()
{
Access = BoxSharedLinkAccessType.open,
Permissions = new BoxPermissionsRequest
{
Download = BoxPermissionType.Open,
Preview = BoxPermissionType.Open,
}
};
BoxFile fileLink = fileManager.CreateSharedLinkAsync(uploadedFile.Id, sharedLinkReq).Result;
you need to give the access token and url. I have use the Following code and in JSON Format you will get the Response. For more reference check the box API document
HttpWebRequest httpWReq = HttpWebRequest)WebRequest.Create("https://api.box.com/2.0/folders/" + FolderID);
ASCIIEncoding encoding = new ASCIIEncoding();
string putData = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] data = encoding.GetBytes(putData);
httpWReq.Method = "PUT";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
Use the httpwebrequest PUT method after this.
Mark it as Answer if its helpful.
It looks as if you are using the 3rd party BoxSync V2 API object. If you would like to just code to the API directly I had a similar issue that you are having. If you view this post you will see the answer. Here is the code I use and it works.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;