How to read a .aspx file in Flutter? - asp.net

I have an aspx file:
I want to upload the file to a flutter web project and read the data as a nested list
[
['Data', 'Data', null, "Data"],
['Data', 'Data', null, "Data"],
['Data', 'Data', null, "Data"],
]
How can I achieve this?
I have the upload part using the filepicker package but what next?
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['aspx'],
);
if (result != null) {
print(result.files.first.bytes);
} else {
// User canceled the picker
}

Related

Office-JS API with Fetch to get data from server, replace fields in Word

I am new to the Office-JS API, but trying to develop a POC to demonstrate the ability to, with the click of a button, replace all fields in a Word document with corresponding data retrieved from an API.
So I have developed an API as an Azure Function, which I can call, passing a value, and it will return the field names and values as JSON for the record that matches the passed value. I have tested this already using Postman.
Now I am trying to get the Office-JS piece working. I started with the VS-2022 template.
My intended approach is that when the user clicks the button, the application will call the API and obtain the record (data) fields as a set of name/value pairs.
Then, I want loop through all of the (data) fields returned, and for each (data) field name, check to see if there is a (document) field in the document by that name; if so, replace the (document) field with the (data) field's value.
In the end, I realize it would likely be more efficient to loop the other way (loop through the doc fields, and then get the (data) field's value, etc.), but I figure I can tweak this once I get it working.
I also realize it's bad practice to perform a context.sync() within a loop, but again - I can clean that up once I get it working.
Right now, my code is reporting "Error: InvalidRequestContext: Cannot use the object across different request contexts."
My code follows:
(function () {
"use strict";
var messageBanner;
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// Initialize the notification mechanism and hide it
var element = document.querySelector('.MessageBanner');
messageBanner = new components.MessageBanner(element);
messageBanner.hideBanner();
// If not using Word 2016, use fallback logic.
if (!Office.context.requirements.isSetSupported('WordApi', '1.1')) {
$("#template-description").text("This sample displays the selected text.");
$('#button-text').text("Display!");
$('#button-desc').text("Display the selected text");
$('#highlight-button').click(displaySelectedText);
return;
}
$("#template-description").text("This POC demonstrates template capabilities for NLRB within WORD.");
$('#button-text').text("Merge Template!");
$('#button-desc').text("Replaces fields with approprate data.");
// Add a click event handler for the highlight button.
$('#highlight-button').click(loadCaseData("08-CA-036441"));
});
};
//CaseNum=08-CA-036441&DataType=1
function loadCaseData(caseNum) {
Word.run((context) => {
const ul = document.getElementById('caseData'),
url = `[URL to my API]`;
const createNode = element => { return document.createElement(element); };
const append = (parent, el) => { return parent.appendChild(el); };
fetch(url)
.then(response => { return response.json(); })
.then(json => {
let caseDataResult = json;
// Identify fields in the document
// Loop through case data for field substitution
var range = context.document.body;
context.load(range, 'text');
var searchResults;
for (let fieldName in caseDataResult) {
var searchFieldName = "«" + fieldName + "»";
let fieldValue = caseDataResult[fieldName];
return context.sync()
.then(function () {
// Queue a search command.
searchResults = range.search(searchFieldName, { matchCase: true, matchWholeWord: true });
// Queue a commmand to load the font property of the results.
context.load(searchResults, 'text');
})
.then(context.sync)
.then(function () {
var replaceCount = searchResults.items.length;
if (replaceCount && replaceCount >= 1) {
for (var replaceItem = 0; replaceItem < replaceCount; replaceItem++) {
searchResults[replaceItem].insertText(fieldValue,
Word.InsertLocation.replace);
}
}
})
.then(context.sync);
}
return context.sync();
})
.catch(errorHandler);
return context.sync();
});
}
//$$(Helper function for treating errors, $loc_script_taskpane_home_js_comment34$)$$
function errorHandler(error) {
// $$(Always be sure to catch any accumulated errors that bubble up from the Word.run execution., $loc_script_taskpane_home_js_comment35$)$$
showNotification("Error:", error);
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
}
// Helper function for displaying notifications
function showNotification(header, content) {
$("#notification-header").text(header);
$("#notification-body").text(content);
messageBanner.showBanner();
messageBanner.toggleExpansion();
}
})();
And the sample JSON returned from my data API:
{
"CaseAssgnedDt": "2011-07-22T17:12:19",
"AsgnUsrExcldFlg": "N",
"BuId": "0-R9NH",
"CaseFiledDt": "2006-03-09T00:00:00",
"InquiryId": "08-CA-036441",
"ChgofccmReqFlg": "N",
"DisputeUnitCity": "Cleveland",
"CaseClasification": "Unclassified",
"CaseClosedDt": null,
"Created": "2010-10-07T15:32:29",
"CreatedBy": "0-1",
"CrimeSubTypeCd": null,
"TypeCd": null,
"DbLastUpd": "2019-10-20T17:17:14.31",
"DbLastUpdSrc": "ScriptingService_PreInvokeMethod",
"CaseDescription": null,
"LastUpd": "2019-10-20T17:17:14",
"LastUpdBy": "1-CGA",
"LocalSeqNum": 1,
"ModificationNum": 11,
"CaseName": "Sample test case name",
"ParCaseId": null,
"PrAgencyId": "No Match Row Id",
"PrAgentId": "No Match Row Id",
"PrPostnId": "1-5D2V9F ",
"PrPrtnrId": "No Match Row Id",
"PrRepDnrmFlg": "Y",
"PrRepManlFlg": "Y",
"PrRepSysFlg": "Y",
"PrSgroupId": "No Match Row Id",
"PrSubjectId": "No Match Row Id",
"PrSuspctId": "No Match Row Id",
"IaCategory": "2",
"RewardExchangeDt": "2010-10-07T11:09:02",
"RowId": "1-2DCA-1327",
"CaseNumber": "08-CA-036441",
"CaseSource": "Visit",
"DisputeUnitState": "OH",
"CaseStatus": "Open",
"CaseSubType": "CA",
"CaseSubTypeCd": null,
"TerritoryTypeCd": "08",
"ThreatLvlCd": "Batch",
"CaseType": "C",
"BlockedFlag": null,
"CaseLongName": "Long sample test case name",
"XCaseNumCi": null,
"DojCaseType": null,
"ElectionTargetDt": null,
"HearingTargetDt": null,
"MethodType": null,
"XNameCi": null,
"Num8a3Discriminatees": null,
"Num8b2Discriminatees": null,
"NumOfEmployees": 146,
"PostElectionSelfCertification": null,
"Potential10j": "N",
"XPrPostnBrdId": "1-4P8HN1",
"XPrPostnSpvId": "1-1RAQT2",
"ElectionSelfCertification": null,
"XTypeCdCi": null,
"Moved2dh": 1,
"IdentityVal": 5792070,
"CdcRecordedFields": null,
"NxgenTestCase": "N",
"InquiryChargePetition": null,
"ChangeCaptureDatetime": "2019-10-20T13:17:15.83",
"RegionRecommendsPursuing10j": "N",
"SurrogateKey": 1731295
}
I appreciate any and all help to get this working, please.
Thank you.
This is another common symptom of nested calls of context.sync. Fix the nesting first. Also, performance is better when you push filtering logic as close to the data source as possible. Consider designing the Azure Function to take in a list of fields and send back only data for matching names. Then your client side code is greatly simplified because you can assume there is a matching field for every data record that is returned.

How to backfill new AppSync fields using AWS Amplify

I'm adding a sort field to one of my AppSync tables using GraphQL. The new schema looks like:
type MyTable
#model
#auth(rules: [{allow: owner}])
#key(name: "BySortOrder", fields: ["sortOrder"], queryField: "tableBySortOrder")
{
id: ID!
name: String!
sortOrder: Int
}
However, when retrieving a list using tableBySortOrder I get an empty list because the new field sortOrder is null.
My question is, how do I backfill this data in the DynamoDB table so that my existing users will not be disrupted by this new change? With a traditional database, I would run a SQL update: UPDATE MyTable SET sortOrder = #.
However, I'm new to NoSQL/AWS and couldn't find a way to do this except build a backfill script whenever a user logs into my app. That feels very hacky. What is the best practice for handling this type of scenario?
Have you already created the new field in DDB?
If yes, I think you should backfill it before making the client side change.
Write a script to iterate through and update the table. Options for this:
Java - Call updateItem to update the table if you have any integ tests running.
Bash - Use AWS CLI: aws dynamodb scan --table-name item_attributes --projection-expression "whatever" > /tmp/item_attributes_table.txt and then aws dynamodb update-item --table-name item_attributes --key. This is a dirty way.
Python - Same logic as above.
Ended up using something similar to what Sunny suggested with a nodejs script:
const AWS = require('aws-sdk')
AWS.config.update({
region: 'us-east-1'
})
// To confirm credentials are set
AWS.config.getCredentials(function (err) {
if (err) console.log(err.stack)
// credentials not loaded
else {
console.log('Access key:', AWS.config.credentials.accessKeyId)
console.log('Secret access key:', AWS.config.credentials.secretAccessKey)
}
})
const docClient = new AWS.DynamoDB.DocumentClient()
const table = 'your-table-dev'
const params = {
TableName: table
}
const itemMap = new Map()
// Using scan to retrieve all rows
docClient.scan(params, function (err, data) {
if (err) {
console.error('Unable to query. Error:', JSON.stringify(err, null, 2))
} else {
console.log('Query succeeded.')
data.Items.forEach(item => {
if (itemMap.has(item.owner)) {
itemMap.set(item.owner, [...itemMap.get(item.owner), item])
} else {
itemMap.set(item.owner, [item])
}
})
itemMap.forEach(ownerConnections => {
ownerConnections.forEach((connection, index) => {
connection.sortOrder = index
update(connection)
})
})
}
})
function update(connection) {
const params = {
TableName: table,
Key: {
'id': connection.id
},
UpdateExpression: 'set sortOrder = :s',
ExpressionAttributeValues: {
':s': connection.sortOrder,
},
ReturnValues: 'UPDATED_NEW'
};
console.log('Updating the item...');
docClient.update(params, function (err, data) {
if (err) {
console.error('Unable to update item. Error JSON:', JSON.stringify(err, null, 2));
} else {
console.log('UpdateItem succeeded:', JSON.stringify(data, null, 2));
}
});
}

Uploaded File not showing in asp.net web api controller

I am trying to build simple image upload program and it's not working
my code as follows . if anyone can figure this out it will be life saving for me
thanks
here is my angular service
postFiles(caption: string, filetouplaod: File) {
const headerss = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': this.globalsr.PrimaryTocken
})
let file: File = filetouplaod;
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
return this._http.post(`${this.globalsr.PrimaryAPI}Uploader/UploadSingleImage`, formData, {headers:headerss})
}
Auth token
private _primaryTocken: string = "Bearer ansKFMPonKyab-TBmgQAThXNKoSAt8ZHej31-Is1a0X0wo5iSIjiaXvRdHscyr9J3v3iG3PTg8_BnoZaiMRCEY03zAONYrKppp1ZdSAgGenMcqeW-UYyKKkOEk7UhXO3l1_-9kXc9rBnekuOIqCrH8TfbcF_G_hgUVFS2N8omQYetJ-VobtaW8n-8AZL72wigGeckLtjZhm12aEEwxsDxnrrY4WA0kB3T9eNURvSO_9lwjJ2_oBRwOPojcAh-dfrlOln0DkSpYL8F2Si2Od63pesFnMZ9uhBkYjZvWCfeN0k8-V7jvBLae_Pz_ljoYM1rVRF-CXwQgBOKiKmSi9h65DUAsqaQY8gLXb69xqPmomscXLn4yVwsdkNyZlayuVlL3EhQgjslgss6xqiUw36SPSsfTN9rMmRQr3dpiJogn61U7kF5FqCRAhmjj_JPOo8aXoh1EGkov0ArerB6lgMDvt3UM_f8-Dzi0i8vtZrstg" ;
My Web api Controller
[Authorize]
[HttpPost]
[Route("UploadSingleImage")]
public HttpResponseMessage UploadSingleImage()
{
var exMessage = string.Empty;
try
{
string uploadPath = "~/content/upload";
HttpPostedFile file = null;
if (HttpContext.Current.Request.Files.Count > 0)
{
file = HttpContext.Current.Request.Files.Get("file");
}
// Check if we have a file
if (null == file)
return Request.CreateResponse(HttpStatusCode.BadRequest, new
{
error = true,
message = "Image file not found"
});
// Make sure the file has content
if (!(file.ContentLength > 0))
return Request.CreateResponse(HttpStatusCode.BadRequest, new
{
error = true,
message = "Image file not found"
});
if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadPath)))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadPath));
}
//Upload File
file.SaveAs(HttpContext.Current.Server.MapPath($"{uploadPath}/{file.FileName}"));
}
catch (Exception ex)
{
exMessage = ex.Message;
}
return Request.CreateResponse(HttpStatusCode.BadRequest, new { error = true, message = exMessage == string.Empty ? "An unknown error occured" : exMessage });
}
but the case is this file count is zero all the time.
HttpContext.Current.Request.Files.Count
so I've send the exact data using postman and web api method works fine.
any ideas please
Don't set 'Content-Type': 'multipart/form-data' - just remove it.
Generaly after it I removed Content-Type in all my requests and replaced it by 'Accept': 'application/json'.
file is not able to get the file you are trying to upload from file input element. Use cosole log to check contents of filetouplaod.
let file: File = filetouplaod;
Lets say fileInput is the input element, then you should assign something like this filetouplaod = fileInput.files[0]

How to fetch firestore data via reference value in a key

here is the multiple document for offer and each offer cantains bidderId that is referenced to users collection and user id.
I want to fetch offer list contains user collection.
I am using angularfire and here is my code.
this.liveOffers=this.db.collection("offers",ref => ref.where('offerExpired', '==', 0).where('isStart', '==', 1)).snapshotChanges().pipe(
map(actions => actions.map(a => {
const data={} = a.payload.doc.data() as offer;
const id = a.payload.doc.id;
var bidder=this.db.doc(data.bidderId).snapshotChanges().subscribe(key=>{
console.log(key.payload.data());
});
return { id, ...data,bidder };
})) );
Here console.log(key.payload.data()); is logging the data for user but it can not bind with bidder variable and i can not use the user object in front end.
Please let me know how can I fetch the offer record with user details.
You need to use a combination of switchMap and combineLatest to get it done.
This is a pseudo-code approach
const temp = []
this.offers$ = this.db.collection().snapshotChanges().pipe(
map(auctions=>{
//we save all auctions in temp and return just the bidderId
return auctions.map(auction=>{
const data={} = a.payload.doc.data() as offer;
const id = a.payload.doc.id;
temp.push({id, ...data})
return data.bidderId
})
}),
switchMap(bidderIds=>{
// here you'll have all bidderIds and you need to return the array to query
// them to firebase
return combineLatest(bidderIds.map(bidderId=> return this.db.doc(bidderId)))
}),
map(bidders=>{
// here you'll get all bisders you'll have to set the bidder on each temp obj
// you saved previously
})
)
Make sure you import { combineLatest } from 'rxjs/operators' not 'rxjs'
I found a way. It is working. But I think it is bit big and there might be way to optimize it. Also it is node-js server API and not for the web (JS). Again there might be similar solution for the web (JS)
Once you get data from snapshot object there is _path key in the object returned by data which again have segments which is array and contain collection and ID
const gg = await firestore.collection('scrape').doc('x6F4nctCD').get();
console.log(JSON.stringify(gg.data(), null, 4));
console.log(gg.data().r._path.segments[0]);
console.log(gg.data().r._path.segments[1]);
const gg2 = await firestore
.collection(gg.data().r._path.segments[0])
.doc(gg.data().r._path.segments[1])
.get();
console.log(gg2.data());
{
"fv": {
"_seconds": 1578489994,
"_nanoseconds": 497000000
},
"tsnowpo": 1578489992,
"createdAt": {
"_seconds": 1578489992,
"_nanoseconds": 328000000
},
"r": {
"_firestore": {
"_settings": {
"libName": "gccl",
"libVersion": "3.1.0",
"servicePath": "firestore.googleapis.com",
"port": 443,
"clientConfig": {},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/datastore"
]
},
"_settingsFrozen": true,
"_serializer": {},
"_projectId": "sss",
"_lastSuccessfulRequest": 1578511337407,
"_preferTransactions": false,
"_clientPool": {
"concurrentOperationLimit": 100,
"activeClients": {},
"terminated": false
}
},
"_path": {
"segments": [
"egpo",
"TJTHMkxOx1C"
]
}
}
}
egpo
TJTHMkxOx1C
{ name: 'Homeware' }

Why am I getting a 404 'App [my-project-id] was not found. The app preview may have expired.' trying push notifications on my Actions on Google?

I'm following the official instructions on how to send push notifications to users that gives their permission.
I'm able to follow all the instructions until this code
appMap.set('finish.push.setup', function(app)) {
if (app.isPermissionGranted()) {
const intent = app.getArgument('UPDATE_INTENT');
const userID = app.getArgument('UPDATES_USER_ID');
// code to save intent and userID in your db
app.tell("Ok, I'll start alerting you");
} else {
app.tell("Ok, I won't alert you");
}
}
the app.getArgument('UPDATE_INTENT') return undefined and checking the JSON it looks like it doesn't contain the intent at all but I have only one intent configured for updates so I hardcoded it's name in the code.
I got a userID and I hardcoded it too in the code.
Then I followed the instructions to get a service account key and I saved the JSON key locally.
Then the nasty problems begins.
I installed the required packages with npm install googleapis request --save and copied the code
const google = require('googleapis');
const key = require(PATH_TO_KEY);
let jwtClient = new google.auth.JWT(
key.client_email, null, key.private_key,
['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
null
);
jwtClient.authorize(function (err, tokens) {
// code to retrieve target userId and intent
let notif = {
userNotification: {
title: '',
},
target: {
userId: '',
intent: ''
}
}
request.post('https://actions.googleapis.com/v2/conversations:send', {
'auth': {
'bearer': tokens.access_token
},
'json': true,
'body': { 'customPushMessage': notif }
}, function(err,httpResponse,body) {
console.log(httpResponse.statusCode + ': ' + httpResponse.statusMessage)
});
});
I edited it setting the right path to my key and edited the notification property with fixed values (the same title configured in the action, the userID returned by dialogflow and the name of my intent).
Then I noticed that the code is missing a const request = require('request'); and the line
let jwtClient = new google.auth.JWT(
gives an error so I changed to
let jwtClient = new google.google.auth.JWT(
I added a console.log('body', body); just to get more data and I got
body { error:
{ code: 404,
message: 'App [my-project-id] was not found. The app preview may have expired.',
status: 'NOT_FOUND' } }
Am I doing something wrong or the documentation has other errors I still have to catch?
try to add locale at target object:
let notif = {
userNotification: {
title: '',
},
target: {
userId: '',
intent: '',
locale: ''
}
}
For locale follow IETF BCP-47 language code as described here.
By default Google Actions use en-US language, and I figure out you are using a differente language code, so the system reply that cannot found us version of your application.

Resources