Making workable JSON file with Angularjs1 - angularjs

I have file that looks like this when I navigate to my local host server
URL:
http://localhost:9000/read/lol.json
And output looks like this:
"{\n \"firstName\" : \"Vladimir\"\n}\n"
Now, what I want is to read this file, so I made service in angular:
.service('messageService', ['$resource', function($resource){
this.getMessage = function(firstName) {
var gmList = $resource("read/lol.json");
return gmList.get({
firstName : firstName
});
};
}]);
and my controller.js
.controller('messageService', function(messageService){
this.firstName = messageService.firstName;
this.messageResult = messageService.getMessage(this.firstName);
});
Finally, my html file
<div data-ng-controller="messageService as mService">
<p>This is new controller: </p>
<div >
<ul data-ng-repeat="w in mService.messageResult">
<li>{{w.firstName}}</li>
</ul>
</div>
EDIT! This is how I got my output when i go to /read/lol.json
Its in java, to be precise, Play Framework.
public Result getFileContent(String filename) throws IOException {
String publicFolder = _appEnvironment.rootPath().getAbsolutePath().concat(folder);
String result = "";
FileReader in = null;
BufferedReader br = null;
File dataFile = new File(publicFolder + filename);
try {
in = new FileReader(dataFile);
br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
result = result.concat(line).concat("\n");
}
} finally {
if (in != null) {
in.close();
}
if (br != null) {
br.close();
}
}
return ok(Json.toJson(result));
}
Thats it. I feel something needs to be done to ignore those \n and .
When I load my page, I get empty list (dots and nothing in that list, just dots).
However, when I look in console, my lol.json file has status 200. I GET that file but cant get anything from it (object).
What is the problem?

Make use of JSON.parse. The code is below:
var data=JSON.parse("{\n \"firstName\" : \"Vladimir\"\n}\n"
);
console.log(data.firstName);
It would convert the string to javascript object format. And to get value of firstname, just log data.firstname.

Related

AngularJS : How can i convert .properties file in to json object

I got a requirement to convert .properties file to JSON object using angular js.
I have no clue how to achive this, i searched in net but did not found the solution. Could you please help me with this.
.properties file contains
a.b.10=M
a.b.11=M50
a.b.12=M508
Output should be
{"a":{"b":{"10":"M","11":"M50","12":"M508"}}}
Try this
var str1 = "a.b.12=M508";
var str2 = "a.b.10=M";
var str3 = "a.b.11=M50";
var result = {};
function createObject(str) {
str.split('.').reduce((obj, key) => {
if (!obj[key] && !key.includes('='))
obj[key] = {};
else if (key.includes('=')) {
var keys = key.split('=');
obj[keys[0]] = keys[1];
}
return obj[key];
}, result);
return result;
}
createObject(str1);
createObject(str2);
createObject(str3);
console.log(result);

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

Uploading CustomData with ng-file-upload and WebApi

I am trying to upload a file along with some metadata to a WebApi Service that I have created with ng-file-upload and Angular. I am getting the file name and bytes as expected, but I am not able to get the metadata I am passing as well. Here is what I am doing on the Angular side
Upload.upload({
url: '/api/FileStorage/AddContent' + location.search,
data: {file: files, year: vm.year }
})
And the WebApi side
var streamProvider = new CustomMultipartFileStreamProvider();
IEnumerable<HttpContent> parts = null;
Task.Factory
.StartNew(() => parts = Request.Content.ReadAsMultipartAsync(streamProvider).Result.Contents,
CancellationToken.None,
TaskCreationOptions.LongRunning, // guarantees separate thread
TaskScheduler.Default)
.Wait();
var customData = streamProvider.CustomData;
Here I am using a MultiStreamProvider to get the file, here is the meat of that provider
public override Task ExecutePostProcessingAsync()
{
foreach (var file in Contents)
{
var parameters = file.Headers.ContentDisposition.Parameters;
var filename = GetNameHeaderValue(parameters, "filename");
var year = GetNameHeaderValue(parameters, "year");
}
return base.ExecutePostProcessingAsync();
}
I am able to get filename without issue, but am never able to get the year. Here is the value in the debugger when I am looking at the parameters variable
As you can see, the name is "name" and the value is "year" when I would expect the name to be "year" and value to be "2016" or whatever I am passing in. What am I doing wrong here and how do I get the metadata included in the same call to the Api?
We use a similar approach with ng-file-upload and WebAPI. To get the values out of the form data, we weren't able to use GetNameHeaderValue. We had to do some manual parsing. We decided to use modified version of what was posted at http://conficient.wordpress.com/2013/07/22/async-file-uploads-with-mvc-webapi-and-bootstrap/ to dynamically take a form and unload it to a strongly-typed Model. But basically, here's what it does in the ExecutePostProcessingAsync method:
public override async Task ExecutePostProcessingAsync()
{
var formData = new FormCollection();
for (int index = 0; index < Contents.Count; index++)
{
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition != null)
{
HttpContent formContent = Contents[index];
string formFieldName = UnquoteToken(contentDisposition.Name) ?? String.Empty;
// Read the contents as string data and add to form data
string formFieldValue = await formContent.ReadAsStringAsync();
formData.Add(formFieldName, formFieldValue);
}
//For your case
var filename = formData["filename"];
var year = formData["year"];
This is the UnquoteToken method this uses:
private static string UnquoteToken(string token)
{
if (String.IsNullOrWhiteSpace(token))
{
return token;
}
if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
{
return token.Substring(1, token.Length - 2);
}
return token;
}

Ng-File-Upload to Save PDF Blob to Database

I'm editing this post to show my latest attempt per suggestions below.
I have been searching the forums trying to find a solution. I have an ASP.NET MVC Application in which I use Angular. I am trying to use danialfarid/ng-file-upload to allow users to upload PDFs which then get saved to the database as binary data (not my idea, but I have to do it that way).
I have the following (taken from the examples) in my HTML:
File:<input type="file" ngf-select ng-model="picFile" name="file" accept="image/*" ngf-max-size="2MB" required ngf-model-invalid="errorFile"><br />
<img ngf-thumbnail="picFile" class="thumb"> <button ng-click="picFile = null" ng-show="picFile">Remove</button><br />
<button type="button" class="btn btn-primary" ng-click="uploadPic(picFile)">Upload</button>
And this in my Angular controller:
$scope.uploadPic = function (files) {
file.upload = Upload.upload({
url: '/SSQV4/SSQV5/Document/UploadEMRDocument',
data: {file: files}
})
}
My MVC Controller:
namespace SSQV5.Controllers
{
public class DocumentController : ApiController
{
public async Task<IHttpActionResult> UploadEMRDocument()
{
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var buffer = await f.ReadAsByteArrayAsync();
//buffer now contains the file content,
//and filename has the original filename that was uploaded
//do some processing with it (e.g. save to database)
}
else
{
return BadRequest("Attachment failed to upload");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
}
}
This code never hits the MVC Controller at all. I'm obviously missing something, but I haven't the slightest clue as to what it could be. Any assistance is greatly appreciated!
You need to extract the file content out of the form data.
Below is how I do this (using ng-file-upload in the same manner as you from the front end) to upload attachments in my application.
public async Task<IHttpActionResult> UploadAttachment()
{
// Check if the request contains multipart/form-data.
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var buffer = await f.ReadAsByteArrayAsync();
//buffer now contains the file content,
//and filename has the original filename that was uploaded
//do some processing with it (e.g. save to database)
}
else
{
return BadRequest("Attachment failed to upload");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
When you configure the upload, you specify the URL where the file will be posted to:
file.upload = Upload.upload({
url: 'myMVC/MyMethod',
data: {file: file}
})

Rendering a child page in a parent page

is it possible to render a specific page in a razor function. I tried #RenderPage but i cant figure out the path. Are there any built in functions to accomplish this?
Thanks Johan
Not really a C1 specific approach, but personally my best approach has been to just make a separate web-request for the page in question, parse out the html and render it.
This code can serve as an example, its a 1:1 of what i'm using. As you can see the trick is to find the element that wraps your content, in my example its the element inside that has an id equals to ContentColumnInner
public static string GetContentFromPage(Guid pageId)
{
var DomainName = HttpContext.Current.Request.Url.Authority;
var Uri = String.Format("http://{0}/page({1})", DomainName, pageId);
var request = WebRequest.Create(Uri);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
if (response.StatusCode != HttpStatusCode.OK)
{
LogError("StatusCode: " + response.StatusCode);
return null;
}
// Get the stream containing content returned by the server.
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
LogError("ResponseStream is null");
return null;
}
// Open the stream using a StreamReader for easy access.
using (var stream = new StreamReader(responseStream))
{
// Read the content.
var responseFromServer = stream.ReadToEnd();
var beforeBodyStartIndex = responseFromServer.IndexOf("<body", StringComparison.Ordinal);
var afterBodyEndIndex = responseFromServer.LastIndexOf("</body>", StringComparison.Ordinal) + 7;
var body = responseFromServer.Substring(beforeBodyStartIndex, afterBodyEndIndex - beforeBodyStartIndex);
try
{
var xmlDocument = XElement.Parse(body);
var content = xmlDocument.Descendants().FirstOrDefault(o => o.Attribute("id") != null && o.Attribute("id").Value.EndsWith("ContentColumnInner"));
if (content == null || !content.HasElements)
{
return null;
}
var reader = content.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
catch (XmlException ex)
{
LogError("Error parsing xml: " + ex.Message);
return null;
}
}
}
}
}

Resources