Upload image from mobile device to a remote Server using Icenium Cordova and ASP.NET - asp.net

I am trying to figure out a way to to upload an image from the mobile phone to a remote server using Icenium+Cordova (mobile) and ASP.NET.
I did try to use FileTransfer() command while providing a remote webservice address but without success. I am using Icenium simulator and Visual Studio to test the code locally.
What I need is a code example of the mobile (Javascript) and Server (.NET) side to support that image upload communication. Thanks.
The code that I am currently using:
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="image_file"; // recFile
var imagefilename = Number(new Date())+".png";
options.fileName=imagefilename;
options.mimeType= "text/plain";
options.chunkedMode = false;
params = {
val1: "some value",
val2: "some other value"
};
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI,"http://127.0.0.1:1691/ImageWebService.asmx/SaveImage", success, fail, options);
}
On the server side:
[WebMethod]
[ScriptMethod]
public string SaveImage()
{
try
{
HttpPostedFile file = HttpContext.Current.Request.Files[0];
if (file == null)
return "0";
HttpPostedFile file =
HttpContext.Current.Request.Files[0];
string targetFilePath = "c:\\" + file.FileName;
file.SaveAs(targetFilePath);
}
catch (Exception ex)
{
}
return "1";
}
I also have:
<access origin="*" />
In the config.xml for cordova.
Note: I tested the webservice for image upload using the standard file upload control using "Advanced Rest Client" and it returned 200 OK.
Other than that, I'm stuck and can find a way to successfully upload am image to the remote server. I am open to using other method, but I think that using the native Cordova FileTransfer() is the safer way to do that if I want the best comparability.

You should use machine name and your device should be connected to the same network. There is no way for your device to know what 127.0.0.1 is, as it is a loopback address. Always test your services by trying to access them from a browser from another machine.
Cordova version has nothing to do with it, Icenium provides all device API even now, there is no need to manually include them as separate plugins.

I suppose you are trying to compile with cordova version 3.
From what I have understood, in cordova-3 most of the device-level API has been moved to external plugins:
Read "Accessing the Feature" in
http://cordova.apache.org/docs/en/3.0.0/cordova_file_file.md.html#File
So in Icenium it doesn't work anymore.
If you try to go in you project properties and set cordova 2.7.0 everything will works.
To be sure add this line in your main javascript, in the deviceready event:
alert("deviceReady!");
alert(device.platform);
if you get both alert msg, the app is working correctly and also the filetransfer will work.
But if you import the File-Transfer GitHub project in Icenium, still using the cordova-3, it will work correctly. That's really a mistery and only Telerik can explain us what they are doing!
Ciao
Marco

Related

Xamarin Android project cannot connect to localhost API

I have been working on this problem for quite some time. I've read the many similar posts and their solutions don't help me (many posts are old and stale). I have a new Xamarin project and a localhost API that I am testing to. Initially I installed our production API locally and it doesn't connect. So I created a smaller test API and have had varying results in connecting. Xamarin Android will not connect with a "Failed to connect to localhost:XXXXX" message. I built a WPF project and get the same results. However I can connect to outside public API's (github) with both. I can connect to my localhost with a Windows forms desktop app and successfully get & post. Postman and httprepl both connect locally and successfully get & post. A couple of the other things the other posts suggested are 1) Client handler to ignore SSL - doesn't work, 2) Use the emulator's browser to connect to localhost - cannot connect. (this might be exposing where the problem really is but not sure).
Also The debugger seems to be behaving oddly. When the debugger gets to the HttpResponseMessageresponse.... line it rarely makes it to the next line so I cannot inspect the statuscode. The block I have below is in a try/catch and rarely makes it to the catch if the connection truly fails. Sometimes it will be caught at the catch and that's how I get the "failed to connect" message. Another developer here has run the project on his computer and gets the same results/errors on his computer.
HttpResponseMessage response = await client.SendAsync(request);
var Statuscode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
var jsonbody = response.Content.ReadAsStringAsync().Result;
var ResponseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
}
else
{
string oops = "Nothing";
}
I seem to be running out of options and am looking for any advice.
Thanks in advance.

Signalr send message from browser to .net client on the same machine

We need to communicate a native application with a web application.
We think to use signalr to send the message/command.
The pipeline would be:
User clicks to make an action.
Javascript (with signalr) send a message to a server in azure.
The server re-send the message a specific client. It must be the client installed on the same machine.
Once the result is completed, NET sends the resulting reverse.
The matter is, How I can find client from the same machine in the signalr Server?
The organization in our system is:
There is center/gym.
Every center has staff who can login.
We could identify client at the same center with some file configuration. Saving our key center, for example. But, in a center, could there are more than one.NET client installed on the different computer.
We think to use the private IP of the computer to make a key on the signalr server.
var ips = [];
var RTCPeerConnection = window.RTCPeerConnection ||
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
var pc = new RTCPeerConnection({
// Don't specify any stun/turn servers, otherwise you will
// also find your public IP addresses.
iceServers: []
});
// Add a media line, this is needed to activate candidate gathering.
pc.createDataChannel('');
// onicecandidate is triggered whenever a candidate has been found.
pc.onicecandidate = function (e) {
if (!e.candidate) { // Candidate gathering completed.
pc.close();
console.log(ips);
return;
}
var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
ips.push(ip);
};
pc.createOffer(function (sdp) {
pc.setLocalDescription(sdp);
}, function onerror() { });
This data can be obtained in .NET client without a problem. But in javascript, the previous code works regularly. In some PC, it only returns ipv4. And in Mozilla it doesn't work.
How can we identify both clients? Do You know another way to reach the goal?
Thanks,
Finally, we didn't find a good solution filtering ip adress.
We did the as follow:
We used URI schema to launch our app. URI Schema windows
Public Class RegistrarURI
Const URI_SCHEME As String = "xxx"
Const URI_KEY As String = "URL:xxx"
Private Shared APP_PATH As String = Location.AssemblyDirectory() ' "C:\Program Files (x86)\xxx.exe"
Public Shared Sub RegisterUriScheme()
Using hkcrClass As RegistryKey = Registry.ClassesRoot.CreateSubKey(URI_SCHEME)
hkcrClass.SetValue(Nothing, URI_KEY)
hkcrClass.SetValue("URL Protocol", [String].Empty, RegistryValueKind.[String])
Using defaultIcon As RegistryKey = hkcrClass.CreateSubKey("DefaultIcon")
Dim iconValue As String = [String].Format("""{0}"",0", APP_PATH)
defaultIcon.SetValue(Nothing, iconValue)
End Using
Using shell As RegistryKey = hkcrClass.CreateSubKey("shell")
Using open As RegistryKey = shell.CreateSubKey("open")
Using command As RegistryKey = open.CreateSubKey("command")
Dim cmdValue As String = [String].Format("""{0}"" ""%1""", APP_PATH)
command.SetValue(Nothing, cmdValue)
End Using
End Using
End Using
End Using
End Sub
End Class
In an Azure WebApp we launch a SignalR Server. This server will send data from our .NET app to Chrome.
To achive that, when the web is loaded, we connect to the signalR server. To build de uri, We send the connectionId from Javascript client to the .NET Client.
Then, when the native process is completed. .NET client send the information to signalR server, and this server mirrored the data to javacript client using the connectionId.
To avoid launch some instance of our native app, we use IPC channel to send data to one instance to the previous and closind the new one.
Link to source Blog source

How can I get the URL in Google AppMaker?

I am trying to get the current URL in an AppMaker app. However, the standard JavaScript ways do not work, ScriptApp is not available in AppMaker, and the objects that are in AppMaker do not return the correct URL (that starts with https://script.google.com).
Thanks for any suggestions.
You can run a backend/serverside script and use Apps Script
ScriptApp.getService().getUrl()
See the doc ScriptApp Documentation
To have an app URL on client side, you can load it during app startup. Firstly, let's create server script that returns app URL:
/**
* Get the URL of the published web app.
*/
function getAppUrl() {
return ScriptApp.getService().getUrl();
}
Open your Project settings and put next code to App startup script section:
loader.suspendLoad();
google.script.run.withSuccessHandler(function(url) {
appUrl = url;
loader.resumeLoad();
}).getAppUrl();
Now you are able to use appUrl everywhere in Client Scripts.
Using this approach you can create initial app config on startup that requires specific data from server.

Authentication Issue when accesing Reporting Service

Well, I already tried a lot of stuff to solve this issue, but none did.
I developed a Reporting Service (2005) and deployed it.
This report will be used by everyone who access a website (it's a internet site, so, won't be accessed by intranet) developed on the framework 3.5 (but I think the framework's version is not the source of the problem).
When the user clicks on the button to download the .pdf which the Reporting automatically generates (the end-user never sees the html version of the Report), it asks for windows credentials.
If the user enters a valid credential (and this credential must be a valid credential on the server which the Reporting Service is deployed), the .pdf is obviously downloaded.
But this can't happen. The end-user must download the .pdf directly, without asking for credentials. Afterall, he doesn't even have the credentials.
Response.Redirect("http://MyServer/ReportServer/Pages/ReportViewer.aspx?%2fReportLuiza%2fReportContract&rs:Format=PDF&NMB_CONTRACT=" + txtNmbContractReport.Text);
The code snippet above, shows the first version of my code when the user clicks the button. This one propmts for the Windows credentials.
I already tried to change on IIS the Authentication of the virtual directory ReportServer, but the only one which works is the Windows Credentials. The other ones doesn't even let me open the virtual directory of the Report or the Report Manager's virtual directory.
When I tried to change it to Anonymous Authentication he couldn't access the DataBase. Then I choose the option to Credentials stored securely on the report server. Still doesn't work.
The physical directory of my ReportServer virtual directory points to the reporting server folder on the Hard Disk (C:\Program Files\Microsoft SQL Server\MSSQL.5\Reporting Services\ReportServer). I moved the same folder to my wwwroot directory.
Didn't work. The virtual directory didn't even open. Then I read this could be a problem because I had the same name on two folders (one in C: and other in wwwroot). So I changed the name of the one in wwwroot. Same issue of the DataBase connection couldn't be done.
I returned the physical path to C:
Below, is the second version of my button's event code:
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
For this code, I had to add a WebReference to the .asmx file mentioned in it.
When I'm debugging (on Visual Studio 2010), the code above works fine, doesn't asking for credentials (unfortunately, it doesn't prompt the option to open, save or cancel de file download. But this is another problem, no need to worry with it now) and save the file on C:.
When published, the code doesn't work. An erros says: The permission granted to user 'IIS APPPOOL\ASP.NET v4.0' are insuficient for performing this operation. So I added to the Reporting Service's users this user. When I tried again, the error is: Login failed for user IISAPPPOOL\ASP.NET v4.0. Cannot create a connection to data source 'MyDataSourceName'.
Both Report and WebSite are deployed/published on the same server with a IIS 7.5 version.
Summarizing: I need a solution where there is no credential prompt, and the user can choose where it wants to save the .pdf file.
Any help will be appreciated.
If you need more information to help me, just ask.
Thanks in advance.
One solution would be to create a new App Pool with an account that has the rights to access your restricted resources and then assign your web application to it.

Blackberry http connection not working on 3g

hi friends i'm a newbie in blackberry programming and have managed to make a small application... The application downloads an xml file through http and parses it and displays it on the screen... now the problem is that though it works fine on my simulator... the client complains that he's getting an error in connection if he connects it through 3G... do i need to add anything other than the following...
// Build a document based on the XML file.
url = <my clients url file>;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
hc = (HttpConnection)Connector.open(url+";deviceside=true");
hc.setRequestMethod(HttpConnection.GET);
InputStream inputStream = hc.openInputStream();
hc.getFile();
Document document = builder.parse(inputStream);
hc.close();
inputStream.close();
Do i need to add anything to make it download http content through 3G also??
Specifying "deviceside=true" requires the device have the APN correctly configured, or you include APN specification in the URL. Have a look at this video.
You need to be able to detect what sort of connection the device is using as was said above deviceside=true works only for APN. If you want to just test it out try using
;deviceside=false //for mds
;deviceside=false;ConnectionType=mds-public //for bis-b
;interface=wifi //for wifi

Resources