What can be better way to send WBXML data to web server? - java-me

Please could you help me in sending a data from Mobile appication to Web Server in WBXML format ? I have got a bit to convert xml to wbxml but not getting how to send that to web server in efficient way ?

I'm not sure I fully understand your question but here goes...
You need to use a POST HTTP request, and write the WBXML data to the connection objects output stream. Here is a brief example, obviously you'll need more code for it to actually work:
byte[] wbxml = getMyWbxmlData();
HttpConnection conn = (HttpConnection)Connector.open("http://myserver.com/mywbxmlhandler");
conn.setRequestMethod(HttpConnection.POST);
OutputStream output = conn.openOutputStream();
output.write(wbxml);
InputStream input = conn.openInputStream(); // This will flush the outputstream
// Do response processing
That is all assuming your WBXML already includes the preamble, such as version number, public code page identifier etc.

Related

Sending excel data to Tally

I have a macro enabled worksheet which saves the data as XML format.
I have prepared the excel template which saves the out put file in XML format. Then i import the XML file in Tally manually with import data option.
Now i am looking for a solution which would make the process automatic i.e. once i save the file as XML format, immediately the data should get imported in Tally without any manual process.
Hope i explained my query properly.
Thanks in Advance.
Best Regards,
You can use Requests to send the xml to tally. Here's a C# example, you can translate it to your preferred language -
private static string Connect(string host, string request)
{
string response = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(host);
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = (long)request.Length;
StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
writer.Write(request);
writer.Close();
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream receiveStream = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
response = reader.ReadToEnd();
reader.Close();
httpResponse.Close();
}
Where host is your tally server ip - usually http://localhost:9000/ and request is your xml - load your xml file as a string.
Ensure your ODBC Server is enabled on Tally. Set your Tally to act as both server and client & choose your port - https://help.tallysolutions.com/article/Tally.ERP9/sync/configuring_client_server.htm
You'll get a response from tally which will have either of the following XML tags -
<CREATED>1</CREATED>
or
<ERROR> // some error </ERROR>
Tally Intergration documentation isn't great but it can still give you an idea - http://mirror.tallysolutions.com/tallyweb/tally/td9/Tally.ERP9_Integration_Capabilities.pdf
Lastly, for automatic upload to tally when the file is created - you can use FileSystemWatcher (C#) or Watchdog library to watch for when the file is created/modified within your specified folder. There is plenty of help in regards to this on stackoverflow.

gRPC: How to call a remote procedure with combination of static and stream parameters?

I'm trying to transfer a file using gRPC. I can send the data, broken into chunks, using gRPC stream. I'm looking for way to also transfer the filename with the data. I'm sure there is an obvious solution that I'm missing. But here are a few approaches that I can think of
Sending filename with each chunk, which as the obvious disadvantage of retransmitting the same data. The .proto file will look like
service KeyValueStore {
rpc upload (stream FileData) returns (UploadStatus) {}
}
message FileData {
string filename = 1;
bytes data = 2;
}
Sending the filename as the first chunk. The receiver will need to be aware of such encoding.
But I'm looking for a non-hacky solution.
I was hoping to have a solution like
service KeyValueStore {
rpc upload (FileName, stream FileData) returns (UploadStatus) {}
}
But it's not possible and also discouraged according to answer here
In general, is there a cleaner way to call a procedure with a combination of normal and stream parameters? or achieve the same effect?
The post you linked is correct. Your input will be a single protocol buffer and in general, it should be named something like "FooRequest". The same is true for the response object, which should be called something like "FooResponse". Decoupling the request and response objects from their contents will give you room to change your API in a backwards-compatible manner over time.
The fact that we don't support multiple request types is not a barrier in practice, because protos can be nested arbitrarily. Consider an API like this.
message FileData {
string filename = 1;
bytes data = 2;
}
message UploadRequest {
oneof payload {
string filename = 1;
FileData file_data = 2;
}
}
service KeyValueStore {
rpc upload (stream UploadRequest) returns (UploadResponse) {}
}
Of course, from the server's perspective, it is now possible for a misbehaving client to send a filename in the middle of the stream. Or, conversely, to start sending chunks of data without first sending a filename.
You could decide that a client must send a filename as the first message. Or perhaps it's okay as long as the filename is sent before the stream ends. Or perhaps sending the filename is entirely optional and not sending one will result in a default value for the filename.
Your decision on these points will be part of your API, but will not be enforced automatically by protobuf as an IDL. You'll need to explicitly handle these corner cases in your server code. Please remember though that, since these are API considerations, they should be written somewhere in your protobuf file. Do your very best to ensure that every message, RPC, and field has a clear and concise docstring.

Web Api HttpResponseMessage not returning file download

I am currently doing a POST to a Web Api method and am posting an array of objects. When I get to the method, my parameters are resolved properly, and I make a call to the DB and return a list of records.
I then take those records and convert them to a MemoryStream to be downloaded by the browser as an Excel spreasheet. From there, I create an HttpResponseMessage object and set properties so that the browser will recognize this response as a spreadsheet.
public HttpResponseMessage ExportSpreadsheet([FromBody]CustomWrapperClass request){
var result = new HttpResponseMessage();
var recordsFromDB = _service.GetRecords(request);
MemoryStream export = recordsFromDB.ToExcel(); //custom ToExcel() extension method
result.Content = new StreamContent(export);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.Name = "formName";
result.Content.Headers.ContentDisposition.FileName = "test.xlsx";
return result;
}
Instead of seeing the spreadsheet being downloaded, nothing seems to happen. When I check the developer tools (for any browser), I see the Response Headers below while the Response tab just shows binary data. Does anyone know what I might be missing here?
How are you doing your POST? It sounds like you might be trying to this via a javascript AJAX call, which cannot be done (https://stackoverflow.com/a/9970672/405180).
I would instead make this a GET request for starters, and use something like window.location="download.action?para1=value1....". Generally web api Post requests are made to create a file/entry, not retrieve one.
Alternatively, you could use a HTML Form with hidden elements corresponding to your query parameters, and use javascript to submit the form.

Web API action filter content can't be read

Related question: Web API action parameter is intermittently null and http://social.msdn.microsoft.com/Forums/vstudio/en-US/25753b53-95b3-4252-b034-7e086341ad20/web-api-action-parameter-is-intermittently-null
Hi!
I'm creating a ActionFilterAttribute in ASP.Net MVC WebAPI 4 so I can apply the attribute in action methods at the controller that we need validation of a token before execute it as the following code:
public class TokenValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext filterContext)
{
//Tried this way
var result = string.Empty;
filterContext.Request.Content.ReadAsStringAsync().ContinueWith((r)=> content = r.Result);
//And this
var result = filterContext.Request.Content.ReadAsStringAsync().Result;
//And this
var bytes = await request.Content.ReadAsByteArrayAsync().Result;
var str = System.Text.Encoding.UTF8.GetString(bytes);
//omit the other code that use this string below here for simplicity
}
}
I'm trying to read the content as string. Tried the 3 ways as stated in this code, and all of them return empty. I know that in WebApi I can read only once the body content of the request, so I'm commenting everything else in the code, and trying to get it run to see if I'm getting a result. The point is, the client and even the Fiddler, reports the 315 of the content length of the request. The same size is getting on the server content header as well but, when we try read the content, it is empty.
If I remove the attribute and make the same request, the controller is called well, and the deserialization of Json happens flawless. If I put the attribute, all I get is a empty string from the content. It happens ALWAYS. Not intermittent as the related questions state.
What am I doing wrong? Keep in mind that I'm using ActionFilter instead of DelegatingHandler because only selected actions requires the token validation prior to execution.
Thanks for help! I really appreciate it.
Regards...
Gutemberg
By default the buffer policy for Web Host(IIS) scenarios is that the incoming request's stream is always buffered. You can take a look at System.Web.Http.WebHost.WebHostBufferPolicySelector. Now as you have figured, Web Api's formatters will consume the stream and will not try to rewind it back. This is on purpose because one could change the buffer policy to make the incoming request's stream to be non-buffered in which case the rewinding would fail.
So in your case, since you know that the request is going to be always buffered, you could get hold of the incoming stream like below and rewind it.
Stream reqStream = await request.Content.ReadAsStreamAsync();
if(reqStream.CanSeek)
{
reqStream.Position = 0;
}
//now try to read the content as string
string data = await request.Content.ReadAsStringAsync();

How to save Excel file to local drive from browser

I've got an XPage that creates an Excel file using server-side javascript (thank to Russ Maher). I know how to save it to the C: drive if I'm running the XPage locally in a browser, but don't know how to save it to the user's machine when it's running on the server without first saving it to the server. The following code is used to save it from the server's perspective.
var fileOut = new java.io.FileOutputStream(directory+fileName);
xl.write(fileOut);
fileOut.close();
Any ideas how I can direct that to the user's drive?
Instead of writing the Excel workbook to a FileOutputStream, you should write it to a ByteArrayOutputStream:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
xl.write(outputStream);
You probably need to use an XAgent to create the output and then link to the XAgent from your XPage. Maybe this blog entry by Declan Lynch combined with this answer on how to do it in a servlet can guide you in the right direction.
Paul Calhoun sent me some sample code that I massaged to get it to produce the spreadsheet that I wanted. I don't know what it was that he'd done that I hadn't, but, for now, I think this is the heart of the solution, just harnessing an OutputStream instead of either a FileOutputStream or ByteArrayOutputStream.
// The Faces Context global object provides access to the servlet environment via the external content
var extCont = facesContext.getExternalContext();
// The servlet's response object provides control to the response object
var pageResponse = extCont.getResponse();
//Get the output stream to stream binary data
var pageOutput = pageResponse.getOutputStream();
// Set the content type and headers
pageResponse.setContentType("application/x-ms-excel");
pageResponse.setHeader("Cache-Control", "no-cache");
pageResponse.setHeader("Content-Disposition","inline; filename=" + fileName);
//Write the output, flush the buffer and close the stream
wb.write(pageOutput);
pageOutput.flush();
pageOutput.close();
// Terminate the request processing lifecycle.
facesContext.responseComplete();
I will gladly provide help if someone else encounters this issue and, hopefully, by the time someone asks, I will understand more of what was different that worked....

Resources