How to call controller methods from react - javascript

I am trying to learn React with ASP.NET Core 3.0 and I have some issues with calling Controllers' methods. If controller has single method like Get() everything is fine. But if it has more than one, then it turns out as error. Something like Multiple Endpoint conflict. I can't understand and can't find any information about this.
I call methods with code like this:
await FetchData(){
const response = await fetch('api/article/makenewpost/?id=');
const data = await response.json();
this.setState({data:data});
}
async fetchData() {
const response = await fetch('api/article/getarticles/?id=' + this.props.id);
const data = await response.json();
this.setState({ blocktitle: this.props.blocktitle, data: data, id: this.props.id });
}
As temporary solution I made Get method in controller with switch statement, but it looks very bad to me.
public IActionResult Get(int? id, string method){
switch (method)
{
case "GetArticles":
{...}
case "MakeNewPost":
{...}
}
}
UPDATE:
Tried saidutt's solution. There is no conflict anymore, but in response I have something like manifest file, so it's error as I read. Why I can't get correct response? I just separated my methods from single switch method.
[Route("api/[controller]")]
public class ArticleController : Controller
{
private readonly DzikanContext _context;
public ArticleController(DzikanContext context)
{
_context = context;
}
// GET: api/<controller>
[Route("api/[controller]/getarticles")]
public IActionResult GetArticles(int id)
{
var titles = _context.Post.Where(p => p.TypeId == id).Select(p => p);
var filtered = titles.Skip(Math.Max(0, titles.Count() - 3)).ToList();
Dictionary<int, string> icons = new Dictionary<int, string>
{
{1, "someUrl" },
{2, "someUrl2"},
{3, "someUrl3" }
};
List<PostsPayload> articles = new List<PostsPayload>();
foreach (var title in filtered)
{
articles.Add(new PostsPayload
{
IconUrl = icons[title.ResourceId],
ArticleBody = title.Title
});
}
return Json(articles.ToArray());
}
[Route("api/[controller]/makenewpost")]
public IActionResult MakeNewPost(int id)
{
var articles = _context.Post.Where(p => p.Id == id).Select(p => p);
var title = articles.Select(p => p.Title).First();
var body = articles.Select(p => p.Body).First();
List<Post> posts = new List<Post>{
new Post
{
Title = title,
Body = body
}};
return Json(posts.ToArray());
}
}
As I said earlier, when I use single method with switch (nothing has been changed in methods when I separated them) it works fine.

Add Routes to individual endpoints in the controller.
[Route("api/posts/createnewpost")]
public IActionResult CreateNewPost(...) { /* your logic */ }

[Route("api/[controller]")]
[ApiController]
public class ArticleController : Controller
{
private readonly DzikanContext _context;
public ArticleController(DzikanContext context)
{
_context = context;
}
// GET: api/<controller>
[HttpGet]
public IActionResult GetArticles(int id)
{
var titles = _context.Post.Where(p => p.TypeId == id).Select(p => p);
var filtered = titles.Skip(Math.Max(0, titles.Count() - 3)).ToList();
Dictionary<int, string> icons = new Dictionary<int, string>
{
{1, "someUrl" },
{2, "someUrl2"},
{3, "someUrl3" }
};
List<PostsPayload> articles = new List<PostsPayload>();
foreach (var title in filtered)
{
articles.Add(new PostsPayload
{
IconUrl = icons[title.ResourceId],
ArticleBody = title.Title
});
}
return Json(articles.ToArray());
}
// api/<controller>/makenewpost
[HttpGet("makenewpost")]
public IActionResult MakeNewPost(int id)
{
var articles = _context.Post.Where(p => p.Id == id).Select(p => p);
var title = articles.Select(p => p.Title).First();
var body = articles.Select(p => p.Body).First();
List<Post> posts = new List<Post>{
new Post
{
Title = title,
Body = body
}};
return Json(posts.ToArray());
}
}

Related

ReplaySubject it is not updating the array when new object is added Angular

I am dealing with an error which when I try to create new page Object, it send to backend but it is not updating the array, I need to reload the page to see the all the array.
I am using Observable within async in the frontend.
I tried to console.log the ngOnInit of the page.component.ts but when I add new page and navigate to pages then the ngOnInit it isn't calling.
On Create new page it happens this.
It sends me to the route of pages where there I show all the list of pages.
But when I create new Page it is returningback an error which says.
ERROR Error: Error trying to diff 'Here is the name of the object'. Only arrays and iterables are allowed.
Update: as Marco said this happens because I mix page as Object instead I am iterating through array
But I am unable to resolve it and i need your help.
In the page.service.ts at pageModel when I add new Object it is returning me only the added Object not the whole array and there is the problem I think, but I don't know how to fix.
But If I reload page then I see all my Array.
This is my updated code.
This is my code.
export class PagesService {
public baseUrl = environment.backend;
private data = new ReplaySubject<any>();
public userID = this.authService.userID;
public editDataDetails: any = [];
public subject = new Subject<any>();
private messageSource = new BehaviorSubject(this.editDataDetails);
getPageID = this.messageSource.asObservable();
constructor(private http: HttpClient, private authService: AuthService) { }
public getPages() {
return this.http.get<any>(`${this.baseUrl}/pages/${this.userID}`).subscribe(res => this.data.next(res));
}
public pageModel(): Observable<Page[]> {
return this.data.asObservable(); // Here it throws error
}
public getPage(id): Observable<any> {
return this.http.get(`${this.baseUrl}/page/${id}`);
}
public setPage(page: Page, id: string) {
const api = `${this.baseUrl}/page`;
const user_id = id;
this.http.post<any>(api, page, {
headers: { user_id }
}).subscribe(res => this.data.next(res));
}
changeMessage(message: string) {
this.messageSource.next(message)
}
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe(res => this.data.next(res.data));
}
Updated Code from Answer.
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe(res => {
this.lastSetOfData = res;
this.data.next(this.lastSetOfData);
});
}
}
export class Page {
_id = "";
name = "";
slogan = "";
description = "";
url = "";
telephone: number;
pageUrl: string;
website: string;
founded: number;
organization: number;
email: string;
coverImage: string;
profileImage: string;
specialty?: Specialty[];
branches: Branches[];
locations?: Location[];
phone?:Phone;
userRole?: string;
roles?: Roles[];
}
export class Roles {
role= "";
userID = "";
}
This is the HTML of page.component .
<div class="main" *ngIf="!showWeb">
<div *ngFor="let page of pages$ | async" class="card width-900">
<app-pages-list class="d-flex width-900" [page]="page" [details]="'details'"></app-pages-list>
</div>
<div>
</div>
</div>
This is the TS file.
public pages$: Observable<Page[]>;
ngOnInit(): void {
this.pageService.getPages();
this.pages$ = this.pageService.pageModel();
}
And this is the code when I create new Page.
export class CreatePageComponent implements OnInit {
public page = new Page();
search;
public branch = [];
constructor(public router: Router,
public branchesService: BranchesService,
public authService: AuthService,
public pageService: PagesService,
public shareData: SenderService) { }
ngOnInit(): void {
}
createPage() {
this.page.url = this.page.name;
this.page.branches = this.branch;
this.page.locations = [];
this.page.specialty = [];
this.page.roles = [];
this.page.phone = this.page.phone;
this.page.pageUrl = `${this.page.name.replace(/\s/g, "")}${"-Page"}${Math.floor(Math.random() * 1000000000)}`;
this.pageService.setPage(this.page, this.authService.userID);
}
addBranch(event) {
this.branch.push(event);
this.search = "";
}
removeBranch(index) {
this.branch.splice(index, 1);
}
}
From my understanding of your code, your error is thrown because the data variable hold 2 types of objects.
In the PagesServices:
In getPages you give data a list of Page.
In setPage and updatePage you give data an instance of Page.
private data = new ReplaySubject<any>();
When you create a new page, data hold the last page you created (not an array). Then you try to iterate this page.
<div *ngFor="let page of pages$ | async"
This error come from the fact that you can't iterate a Page object.
You should stop using any so that this type of error occurs at compilation time, not at runtime. Also you need to store an instance of the array of page, add the item in your array after a post, and then replay the whole array.
Code
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe((res) => {
const index: number = lastSetOfData.findIndex((_page: Page) => _page._id === res._id);
lastSetOfData[index] = res;
lastSetOfData = [...lastSetOfData];
this.data.next(lastSetOfData);
});
}
Also the updateDate function should be named updatePage.
The issue is the one identified in the response from #Marco. I elaborate starting from there.
There are several ways of fixing this problem. Probably the fastest is to add an instance variable lastSetOfData to PagesService where you hold the last version of the array. Then you initiatlize lastSetOfData in the getPages method. Finally in the setPage method you update lastSetOfData appending the Page returned by the service at the end of lastSetOfData and notify it using the ReplaySubject.
So the code could look like this
export class PagesService {
public baseUrl = environment.backend;
// specify the type of data notified by the ReplaySubject
private data = new ReplaySubject<Array<Page>>();
// define lastSetOfData as an array of Pages
private lastSetOfData: Array<Page> = [];
....
public getPages() {
return this.http.get<any>(`${this.baseUrl}/page/${this.userID}`).subscribe(res => {
// res should be an array of Pages which we use to initialize lastSetOfData
lastSetOfData = res;
this.data.next(lastSetOfData)
});
}
....
public setPage(page: Page, id: string) {
const api = `${this.baseUrl}/page`;
const user_id = id;
this.http.post<any>(api, page, {
headers: { user_id }
}).subscribe(res => {
// update lastSetOfData appending resp, which should be a Page
// not the use of the spread operator ... to create a new Array
lastSetOfData = [...lastSetOfData, resp];
// now you notify lastSetOfData
this.data.next(lastSetOfData)
});
}
// probably you have to modify in a similar way also the method updateTable
public updateDate(id: string, page: Page) {
....
}
....
....
}
Consider that this may be the fastest way to fix the problem. Check if it works and then you may want to try to refactor the code to look for a more rx-idiomatic solution. But my suggestion is first to see if this fixes the problem.
Problem is that you put an object in your replaysubject although an array is expected in other places.
next(myarray)
next(myobject)
This does not magically append an object to the array.
To do so, you'd need something like this:
data.pipe(take(1)).subscribe(list => {
list.push(newvalue);
data.next(list);
});
Basically you take the last value, a the new item, and push the new list.

Using ReplaySubject in Angular at PUT Request it is losing the data

I am having an issue with the ReplaySubject, I don't know what I have done wrong but the problem it is that when I change something and save it in backend, the ReplaySubject it calls new data but it is hiding them to show me see the picture.
I tried to use detectChanges but without any luck, but as i know the detectChanges will work only when we have parent -> child iterration.
This happens on update
This happens when I reload the page
If I remove the the this.data.next(res) at this line of the Put Request then it works but I need again to reload page to get new data.
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
This is the code of the service.
#Injectable({
providedIn: "root"
})
export class ModelDataService {
public baseUrl = environment.backend;
private data = new ReplaySubject<any>();
public userID = this.authService.userID;
constructor(private http: HttpClient, private authService: AuthService) {
}
public getJSON() {
return this.http.get(`${this.baseUrl}/data/${this.userID}`).subscribe(res => this.data.next(res));
}
public dataModel(): Observable<any> {
return this.data.asObservable();
}
public setData(data: Model) {
const api = `${this.baseUrl}/data`;
const user_id = this.authService.userID;
this.http.post(api, data, {
headers: {user_id}
}).subscribe(res => this.data.next(res));
}
public updateDate(id: string, dataModel: Model) {
const api = `${this.baseUrl}/data/${id}`;
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
}
}
This is the component.
public model$: Observable<Model>;
public model: Model;
constructor(
public authService: AuthService,
private modelDataService: ModelDataService,
public dialog: MatDialog,
public cd: ChangeDetectorRef) {
}
ngOnInit() {
this.authService.getUserProfile(this.userID).subscribe((res) => {
this.currentUser = res.msg;
});
this.modelDataService.getJSON();
this.model$ = this.modelDataService.dataModel();
this.model$.subscribe((data) => {
this.model = data; // here if i try to console log then I have the array but the page it will be blank
console.log(data);
});
}
And then for example I try to show data like this.
<ng-container class="Unit-unit-unitGroup" *ngFor="let personalData of model.personalData; let id = index">
</ng-container>
In the put Request I have added an console log and this is what I am getting.
But on reload I am getting I think another way of strucuter of data.
See picture
Use ChangeDetectorRef to detect changes again in the view when the data comes back.
this.model$.subscribe((data) => {
this.model = data;
this.cd.detectChanges();
});
<ng-container class="Unit-unit-unitGroup" *ngFor="let personalData of model.personalData; let id = index">
</ng-container>
this.model$.subscribe((data) => {
this.model = data; // here if i try to console log then I have the array but the page it will be blank
console.log(data);
});
public updateDate(id: string, dataModel: Model) {
const api = `${this.baseUrl}/data/${id}`;
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
}
You expect personalData to be a property of your model. However, as seen in the console log your res is an object including data as an object between. All you need to do is mapping res to it's data.
public updateDate(id: string, dataModel: Model) {
const api = `${this.baseUrl}/data/${id}`;
return this.http.put(api, dataModel).subscribe(res => this.data.next(res.data));
}

Values null when I make a simple post request to my .net controller from angular

This used to be a 415 error question.
Now it is a a receiving null values on the server side question.
I am having difficulty trying to get my values in the object myMessage over to the server side.
I have so far tried to add JSON.stringify to newMessage which is being console.logged in the service file.
I tried many ways to alter or make the object the way it would be recognized such as JSON.stringify() and creating a url ending with the correct parameters.
Sorry if it seems like I am dumping code below, but I have been working on this for a second day and don't understand why I can't do a simple post request with three parameters. One string, one int, and one datetime.
If anyone can see where I have gone wrong I would so appreciate it. I will be desperately waiting.
Below I am trying to hit api/SlgCorpNotes/Edit in backend from updateMessage(message: any) in the service in service.ts
slg-corp-notes.service.ts
import { Component, Injectable, Inject } from '#angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '#angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { SLGReportParams, CorpNotes } from './models/slg.model';
import { SlgOverviewComponent } from './slg-overview/slg-overview.component';
import { SlgNote } from './models/slg-notes';
#Injectable({
providedIn: 'root'
})
export class SlgCorpNotesService {
constructor(private http: HttpClient, #Inject('BASE_URL') private baseUrl: string) { }
getWeekTempValue(endDate, department) {
var Params = '?endDate=' + endDate + '&department=' + department;
return this.http.get<any>(this.baseUrl + 'api/SlgCorpNotes/getWeekTempValue' + Params);
}
updateMessage(message: any) {
console.log("at service")
console.log(message)
var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
console.log(newMessage)
console.log(JSON.stringify(newMessage))
console.log(Params)
const headers = new HttpHeaders()
.set('Content-Type', 'application/json;charset=UTF-8')
let options = { headers: headers };
return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options).subscribe(res => {
console.log(res);
}, error => {
console.log(error);
});;
}
}
model.ts
export class CorpNotes {
constructor(
public department: number,
public note: string,
public weekEnding: Date
) { }
}
SLGCorpNotesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mocHub2.Models;
using mocHub2.Models.Enterprise;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
namespace mocHub2.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SlgCorpNotesController : Controller
{
SLGContext _SLGContext;
BRDataContext _BRDataContext;
//injects new context
public SlgCorpNotesController(SLGContext context, BRDataContext context2)
{
_SLGContext = context;
_BRDataContext = context2;
}
// GET: api/SlgCorpNotes
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/SlgCorpNotes/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "value";
}
// POST: api/SlgCorpNotes
[HttpPost]
public void Post([FromBody] string value)
{
}
// Get Corporate Notes
[HttpGet("[action]")]
public JsonResult getWeekTempValue(DateTime endDate, int department)
{
// Find the WeekID from the weekending from SLGHeaderTemplate table
var WeekID = (from x in _SLGContext.SlgheaderTemplate
where x.WeekEnding == endDate
select x.Id).ToList();
// Find Department name by ID
var DepartmentString = (from x in _BRDataContext.Departments
where x.Department == department
select x.Description).ToList();
// Get the Note.
var DeptNote = from x in _SLGContext.SLGCorpNotes
where x.Department == DepartmentString[0]
&& x.WeekID == WeekID[0]
select x.Notes;
// Create return object
var notes = new Notes();
// If Note exists then return Json containing note and department for display, else return empty string.
if (DeptNote.Any() && WeekID.Count() > 0 && DepartmentString.Count() > 0)
{
var ReturnDeptNote = DeptNote.First();
notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
}
else
{
var ReturnDeptNote = "";
notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
}
return Json(notes);
}
[HttpPost]
[Route("Edit")]
public void Edit([FromForm] CorpNotes item)
{
_SLGContext.Entry(item).State = EntityState.Modified;
_SLGContext.SaveChanges();
}
}
public class CorpNotes
{
public int department { get; set; }
public string note { get; set; }
public DateTime weekEnding { get; set; }
}
public class Notes
{
public int ID { get; set; }
public int WeekID { get; set; }
public string Department { get; set; }
public string Note { get; set; }
}
}
Results of console.logs in the service file.
at service
slg-corp-notes.service.ts:22 {departments: 2, weeks: SLGTime, noteBody: "asdf"}
slg-corp-notes.service.ts:25 CorpNotes {department: 2, note: "asdf", weekEnding: "2019-11-02T00:00:00"}
slg-corp-notes.service.ts:26 {"department":2,"note":"asdf","weekEnding":"2019-11-02T00:00:00"}
slg-corp-notes.service.ts:27 ?Department=2&Note=asdf&WeekEnding=2019-11-02T00:00:00
slg-corp-notes.service.ts:28 Observable {_isScalar: false, source: Observable, operator: MapOperator}
app.module.ts
This is in my app.module.ts where I specify routes
{ path: 'slg-corp-notes', component: SlgCorpNotesComponent },
{ path: 'slg-corp-notes/edit/', component: SlgCorpNotesComponent }
slg-corp-notes.component.ts
save() {
console.log("at save")
if (!this.optionsForm.valid) {
return;
}
//this.Notes.note = this.optionsForm.get['noteBody'].value;
console.log(this.Notes);
this._slgCorpNotesService.updateMessage(this.optionsForm.value)
.subscribe((data) => {
this._router.navigate(['/slg-corp-notes']); //This will navigate back to the mochhub2 index where the message will be displayed
}, error => this.errorMessage = error)
}
Please let me know if additional info is needed.
1) You need to set the Content-Type header to application/json.
2) stringify the message.
const headers = new HttpHeaders()
.set('Content-Type', 'application/json;charset=UTF-8')
let options = { headers : headers };
this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options);
At your angular side update your method like this
updateMessage(message: any) {
console.log("at service")
console.log(message)
var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
console.log(newMessage)
console.log(JSON.stringify(newMessage))
console.log(Params)
var item = {
"Departments": message["Departments"],
"Note": message["noteBody"],
"WeekEnding": message["weeks"]
}
return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', item).subscribe(res
=> {
console.log(res);
}, error => {
console.log(error);
});
}

Lightning Web Component to display JSON String is not working

I have the following lightning web component to read a JSON string and display them in Contact record Details page. Please note that I am new to lighting web components and making a considerable amount of effort to learn.
MyComponent.html
<template>
<lightning-record-form
object-api-name={contactObject}
fields={myFields}
onsuccess={handleContactCreated} onload={handleContactInitialized} >
</lightning-record-form>
</template>
MyComponent.js
import { LightningElement, wire, track } from 'lwc';
import findDetails from
'#salesforce/apex/JSONDemoController.getContactWithRelatedDataById';
import CONTACT_OBJECT from '#salesforce/schema/Contact';
import NAME_FIELD from '#salesforce/schema/Contact.Name';
import TEST_FIELD from '#salesforce/schema/Contact.TestField__c';
import SPOUSE_FIELD from '#salesforce/apex/ResponseJSONWrapper.spouse';
import ADDRESS_FIELD from
'#salesforce/apex/ResponseJSONWrapper.mailingAddress';
export default class ContactCreator extends LightningElement {
contactObject = CONTACT_OBJECT;
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
#track contacts;
#track error;
handleContactCreated(){
// Run code when account is created.
}
handleContactInitialized(){
findDetails()
.then(result => {
var responseObj = JSON.parse(result.getReturnValue());
this.SPOUSE_FIELD = responseObj.spouse;
this.ADDRESS_FIELD = responseObj.mailingAddress;
})
.catch(error => {
this.error = error;
});
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
}
}
JSONDemoController.cls
public class JSONDemoController {
#AuraEnabled
public static String getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
response = JSON.serialize(wrapper);
return response;
}
}
ResponseJSONWrapper.cls
public with sharing class ResponseJSONWrapper {
public String spouse;
public String contactRecordType;
public Date birthDate;
public String mobile;
public String mailingAddress;
public String otherAddress;
public String languages;
public String level;
public String Description;
}
But I don't get the values I have hard coded in the lightning component when it is rendered. Nothing is there it's empty.
Can someone help to point out where I am going wrong ?
Change this line:
var responseObj = JSON.parse(result.getReturnValue());
To:
var responseObj = JSON.parse(result);
getReturnValue() is for Aura components.
You don't actually need to serialize the wrapper in apex and then parse in the component explicitly, the framework does the job by itself!
public class JSONDemoController {
#AuraEnabled //change return type to ResponseJSONWrapper
public static ResponseJSONWrapper getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
return wrapper; //return the wrapper itself
}
and in .js file
findDetails()
.then(result => {
var responseObj = result;
...
})
This way the code will be less cluttered with not-needed code :)

Office Apps, how send copy of doc file with ajax to C# controller

hello i have this problem:
I have a addins for office(word);
I want to send a copy of current file (.docx) to C# controller, i have this code now, at this stage of the code i get a array of chars or somethis in the "yourfile", how ca i get a .docx file?
JavaScript
function sendFile() {
Office.context.document.getFileAsync("compressed",
{ sliceSize: 100000 },
function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
var myFile = result.value;
var state = {
file: myFile,
counter: 0,
sliceCount: myFile.sliceCount
};
getSlice(state);
}
});
}
function getSlice(state) {
state.file.getSliceAsync(state.counter, function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
sendSlice(result.value, state);
}
});
}
function myEncodeBase64(str)
{
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function sendSlice(slice, state) {
var data = slice.data;
if (data) {
var fileData = myEncodeBase64(data);
var _url = '../../api/file';
useAjax(_url, 'Post', JSON.stringify(fileData), _contentType).done(function (data) {
writeData(data);
app.showNotification("Translation was successfully done!");
});
}
}
And the C# CONTROLLER:
public static string filemame = #"c:\yourfile";
[Route("file")]
[HttpPost]
public void getFile([FromBody] string data)
{
Base64ToFile(data,filemame);
}
public static void Base64ToFile(string base64String, string filename)
{
byte[] fileByteArray = Convert.FromBase64String(base64String);
// Instantiate FileStream to create a new file
System.IO.FileStream writeFileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
// Write converted base64String to newly created file
writeFileStream.Write(fileByteArray, 0, fileByteArray.Length);
// Clean up / disposal
writeFileStream.Close();
}
Late to the party, but I'm adding the answer here nonetheless, in case someone else will need it at some later date.
Instead of using myEncodeBase64 you should use
var fileData = OSF.OUtil.encodeBase64(data);
It's a function that is part of the Office API, so you don't have to define anything else.
I have been struggling to construct a correct pptx serverside. Eventually this is what I came up with.
Javascript
function sendSlice(slice, state) {
var data = slice.data;
if (data) {
var isLastSlice = state.counter >= (state.sliceCount -1);
var ajaxData = {
isLastSlice: isLastSlice,
counter: state.counter,
documentData: btoa(data)
}
$.ajax({
url: "/api/Constructpptx", method: "POST", data: ajaxData, success: function (result) {
state.counter++;
if (isLastSlice) {
closeFile(state);
}
else {
getSlice(state);
}
}, error: function (xhr, status, error) {
}
});
}
}
And as an API backend I use this
C# ApiController
public class ConstructpptxController : ApiController
{
public static List<byte> Document { get; set; } = new List<byte>();
public string Post([FromBody]ConstructpptxPayload payload)
{
if (payload.counter == 0)
Document.Clear();
var payloadData = Convert.FromBase64String(payload.documentData);
var pptBytes = Encoding.UTF8.GetString(payloadData).Split(',').Select(byte.Parse).ToArray();
Document.AddRange(pptBytes);
if(payload.isLastSlice)
{
var path = #"C:/Some/Local/Path/Presentation.pptx";
var fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
fileStream.Write(Document.ToArray(), 0, Document.Count());
fileStream.Close();
Document.Clear();
}
return $"Counter: {payload.counter}, isLast: {payload.isLastSlice}, docLength: {Document.Count}";
}
}
public class ConstructpptxPayload
{
public bool isLastSlice { get; set; }
public int counter { get; set; }
public string documentData { get; set; }
}
Please note: only use this example as a quick starting point, as you don't want to save the bytes in a static List Document. Instead you want to make your webserver stateless.

Categories