How to write data back to storage? - nearprotocol

I have a method called changePlaceName and i know it is working but after i call getPlaces to see the changes, i don't see the new place name instead i see the name when i created a new place.
this is changePlaceName
export function changePlaceName(placeId: u32, placeName: PlaceName): void {
assert(placeId >= 0, 'Place ID must be >= 0');
const place = Place.find(placeId);
logging.log(place.name); //gives "Galata Tower"
place.name = placeName;
logging.log(place.name); // gives "New Galata Tower"
}
I need to save it somehow but I don't know how to do it.
I also tried this way;
export function changePlaceName(placeId: u32, placeName: string): void {
assert(placeId >= 0, 'Place ID must be >= 0');
const place = Place.find(placeId);
logging.log(place.name);
place.name = placeName;
let newPlace = storage.get<string>(placeName, 'new galata tower');
storage.set<string>(placeName, newPlace);
logging.log('New place is now: ' + newPlace);
}
Now my visual code is complaining about the newPlace inside the storage.set
How do I fix it?

What is the code of Place.find? I assume you are using a persistent map under the hood.
Is there a Place.set? You need to store the Place back to the same key used to find it.

because you're using some kind of class to manage the concept of "Place", why not add an instance method to that class to save() the place once you've changed it's name?
would help if you also posted your code for Place here, by the way
my guess is that it looks something like this?
!note: this is untested code
#nearBindgen
class Place {
private id: number | null
private name: string
static find (placeId: number): Place {
// todo: add some validation for placeId here
const place = places[placeId]
place.id = placeId
return place
}
// here is the instance method that can save this class
save(): bool {
places[this.id] = this
}
}
// a collection of places where placeId is the index
const places = new PersistentVector<Place>("p")

Related

Creating TypeScript enum with display value

I have a typescript enum that looks like this:
enum State {
NotRequired,
Working,
PendingReview,
Reviewed,
Done
}
And this generates this:
var State;
(function (State) {
State[State["NotRequired"] = 0] = "NotRequired";
State[State["Working"] = 1] = "Working";
State[State["PendingReview"] = 2] = "PendingReview";
State[State["Reviewed"] = 3] = "Reviewed";
State[State["Done"] = 4] = "Done";
})(State || (State = {}));
I would like to have the values a nicely formed string with spaces where required.
So State[State["PendingReview"] = 2] = "PendingReview"; would become State[State["PendingReview"] = 2] = "Pending Review";
I have managed to achieve something close to this by defining my enum like so:
enum State {
"Not Required",
Working,
"Pending Review",
Reviewed,
Done
}
However this has the drawback that to use any enum value in code with a space i now have to use my key instead.
So State.PendingReview now has to be used like this State["Pending Review"]
Can i have the best of both worlds by somehow defining an alternative display string to my key?
So that when i say State[State.PendingReview] it gives me the value "Pending Review"
As you're not specifying explicit values for the enum, you may as well use a string enum (available as of TypeScript 2.4) for this:
enum State {
NotRequired = "Not Required",
Working = "Working",
PendingReview = "Pending Review",
Reviewed = "Reviewed",
Done = "Done"
}
The display value then simply becomes e.g. State.NotRequired.
Since enums does not supports string values,
would be better to use a class with static fields like this.
You have the compilation checks like if you where using enum, you call it the same way in your code also.
module rizze.tests {
enum State{
NotRequiered,
Working,
Pending,
Reviewed,
Done
}
class StateConvert {
static NotRequiered="Not Required";
static Working="I'm Working";
static Pending = "Pending Review";
static Reviewed="Reviewed Done";
static Done="Done All";
static convert(state:State):String{
if( state == null) return null;
switch(state){
case State.NotRequiered:{return StateConvert.NotRequiered;}
case State.Working:{return StateConvert.Working;}
case State.Pending:{return StateConvert.Pending;}
case State.Reviewed:{return StateConvert.Reviewed;}
case State.Done:{return StateConvert.Done;}
}
console.log("Error state undefined + " +state );
return null;
}
}
export class StateTest {
constructor(){
let state:State = State.Reviewed;
console.log("state:"+state + " / " + StateConvert.convert(state));
}
}
//TEST
let s:StateTest= new StateTest();
}
Can i have the best of both worlds by somehow defining an alternative
display string to my key?
No. This is not supported in TypeScript. You could try to make a feature request if you think this would be valuable.

ES6 read-only enums that can map value to name

I would like to define an enum-like structure in JS, but have two requirements:
The values be read-only, i.e. no users can assign to them.
The values (0, 1, 2, ...) can be mapped back into the names (as with Java's name method)
The methods I know to create enums like this typically meet one requirement or the other, not both.
I've tried:
const MyEnum = {
a: 0,
b: 1,
c: 2
};
The enum itself is constant, but the values are still mutable and I can't map values back to names efficiently.
When writing an enum in Typescript, it outputs:
var MyEnum;
(function (MyEnum) {
MyEnum[MyEnum["a"] = 0] = "a";
MyEnum[MyEnum["b"] = 1] = "b";
MyEnum[MyEnum["c"] = 2] = "c";
})(MyEnum || (MyEnum = {}));
This can map both ways, but still doesn't have constant values.
The only option I've found that meets both requirements would be using getters on a class:
class MyEnum {
get a() {
return 0;
}
...
}
This method dramatically restricts the legal names and has a lot of overhead, especially in browsers that don't inline getters well (or can't).
#Shmiddty suggested freezing an object:
const MyEnum = Object.freeze({
a: 0,
b: 1,
c: 2
});
This meets the constant requirement well, but doesn't provide a great way to map values back to names.
I could write a helper that builds the reverse mapping like:
function reverseEnum(enum) {
Object.keys(enum).forEach(k => {
enum[enum[k]] = k;
});
}
But any kind of programmatic solution to generate the reverse mapping will run into problems if the original object is frozen or otherwise actually constant.
Is there a clean, concise solution to this in JS?
This does a pretty good job, IMHO.
function Enum(a){
let i = Object
.keys(a)
.reduce((o,k)=>(o[a[k]]=k,o),{});
return Object.freeze(
Object.keys(a).reduce(
(o,k)=>(o[k]=a[k],o), v=>i[v]
)
);
} // y u so terse?
const FOO = Enum({
a: 0,
b: 1,
c: "banana"
});
console.log(FOO.a, FOO.b, FOO.c); // 0 1 banana
console.log(FOO(0), FOO(1), FOO("banana")); // a b c
try {
FOO.a = "nope";
}
catch (e){
console.log(e);
}
I'd use a Map so that your enum values can be any type, rather than having them coerced into strings.
function Enum(obj){
const keysByValue = new Map();
const EnumLookup = value => keysByValue.get(value);
for (const key of Object.keys(obj)){
EnumLookup[key] = obj[key];
keysByValue.set(EnumLookup[key], key);
}
// Return a function with all your enum properties attached.
// Calling the function with the value will return the key.
return Object.freeze(EnumLookup);
}
If your enum is all strings, I'd also probably change one line to:
EnumLookup[key] = Symbol(obj[key]);
to ensure that the enum values are being used properly. Using just a string, you have no guarantee that some code hasn't simply passed a normal string that happens to be the same as one of your enum values. If your values are always strings or symbols, you could also swap out the Map for a simple object.
Just recently implemented an Es6 version that works quite well:
const k_VALUES = {}
export class ErrorCode {
constructor(p_apiCode, p_httpCode){
this.apiCode = p_apiCode;
this.httpCode = p_httpCode;
k_VALUES[p_apiCode] = this;
}
static create(p_apiCode){
if(k_VALUES[p_apiCode]){
return k_VALUES[p_apiCode];
}
return ErrorCode.UNKNOWN;
}
}
ErrorCode.UNKNOWN = new ErrorCode(0, 500);
ErrorCode.NOT_FOUND = new ErrorCode(-1000, 404);
ErrorCode.NOT_FOUND_EMAIL = new ErrorCode(-1001, 404);
ErrorCode.BAD_REQUEST = new ErrorCode(-1010, 404);
I wanted to implement a similar pattern as what we do with Java enums. This enables me to use a constructor to pass values. The constructor then freezes the ErrorCode object - nice and convenient.
Usage: first import your enum class...
import {ErrorCode} from "../common/services/errors/ErrorCode";
Now, after importing the enum class, access it like so:
if( errCode.includes(ErrorCode.BAD_REQUEST.apiCode) ){...}
PS> This is used in conjunction with a Webpack setup using Babel to convert our ES6 classes down for browser compatibility.

isolated storage in windows phone developement

Im using VS to develop a windows phone app. Im doing it wp8 but it doesnt matter because it the code works for 7 too. Anyway, I have a text box and a button. When the text from the text box is entered, and the button is clicked it adds that to isolated storage.
On my other page, I have a textblock. Which should display what I wrote in the text box. It does work, but first let me sho you my code.
if (appsettings.Contains("name"))
{
appsettings.Remove("name");
appsettings.Add("name", TitleTextBox.Text); //rename if already exists
}
and then the second page that collects the info is below.
if (appsettings.Contains("name"))
{
string content = appsettings["name"].ToString(); //converts to string
titleTextBlock.Text = content; //shows title in text block
}
The problem is, the "name" works. However, if I call it ANYTHING else it does not. I want to add a different name because i want to be able to input two lots. For example two text box's and then when you press the button and go to the other page, it has two textblocks displaying each string in each one. I can't seem to do this because only "name" works. Ive changed it to other names and it doesnt work. Does anyone know why?
IsolatedStorageSettings works as a Dictionary. If you want to acces a specific key it should exist in the Dictionary.
If you try to change the value that already exists you can do like this:
if (appSettings.Contains("key")) appSettings["key"] = "new value";
else appSettings.Add("key", "new value");
Don't also forget to save your appSettings:
appSettings.Save();
And also according to your code - in ISS you can put not only string - it can be any object, if you want to get it, you should make a cast or use as:
string content = (string)appsettings["name"]; //converts to string
string content = appsettings["name"] as string;
EDIT - after comments, rebuild once more
If you want to have a to-do-list and you know that every task has its specific title, description and time then I would advise to create a special class for this, for example:
public class myTodo
{
public string TaskTitle { get; set; }
public string TaskDescription { get; set; }
public TimeSpan ElapsedTime { get; set; }
}
I used TimeSpan because I think it's easier to manage Time with it. Then if you want to Save/Load your myTodo you can do like this:
// create an example of your task
myTodo newTask = new myTodo() { TaskTitle = "Clean", TaskDescription = "Clean room", ElapsedTime = new TimeSpan(2, 0, 0) };
// add it to ISS and save
if (appSettings.Contains("firatTask")) appSettings["firatTask"] = newTask;
else appSettings.Add("firatTask", newTask);
appSettings.Save();
// try to load
myTodo read = appSettings["firatTask"] as myTodo;
You can access your item like this:
read.Title = TitleTextBox.Text; // and so on
Consider also making a List<myToDo> and be aware that ISS shoul also handle this:
List<myTodo> listJob = new List<myTodo>();
listJob.Add(firstTask); // firstTask is myToDo
listJob.Add(secondTask); // secondTask is myToDo
if (appSettings.Contains("listTask")) appSettings["listTask"] = listJob;
else appSettings.Add("listTask", listJob);
appSettings.Save();
List<myTodo> readList = appSettings["listTask"] as List<myTodo>;

Observing properties of an array that is being observed in KnockoutJS

I'm working on an ASP.Net MVC application. My action is returning a view with a model that is an array of objects (a class with properties like Name, ID, IsViewable).
var model = #Model.ToJson(); // done via extension call
I want to observe this array, so whenever it changes I can update a table that has been bound to a template.
var viewModel = {
accounts = ko.observableArray(model)
}
This works just fine for adding and deleting elements from the array. However, I also want the template to update when a property in one of the accounts changes (ie, Name or ID).
On the KnockoutJS website, it says: Of course, you can make those properties observable if you wish, but that’s an independent choice. This is what I cannot figure out how to do.
I tried something like this with no avail:
var viewModel = {
accounts = ko.oservableArray([])
}
for(var i = 0; i < model.length; i++) {
ko.observableArray(model[i]);
viewModel.accounts.push(model[i]);
}
I can post the template and the table if it's needed.
You should look into the knockout.mapping plugin. I think it does everything you are looking to do.
I ended up getting this to work, so I thought I would share with anyone that might have having the same problem.
You need to wrap your array items in a JavaScript class. Then in the constructor, set each property to obserable:
var model = #Model.ToJson();
var viewModel = {
accounts = ko.observableArray(ko.utils.arrayMap(model, function(account) {
return new AccountWrapper(account);
}))
};
function AccountWrapper(account) {
this.Property1 = ko.observable(account.Propery1);
this.Property2 = ko.observable(account.Propery2);
this.Property3 = ko.observable(account.Propery3);
}
ko.applyBindings(viewModel);
And if you want to modify one of the items directly to see the change, you could do something like:
viewModel.accounts()[3].Name('My Name Changed');
And you can still get notified when items are added or remove:
viewModel.accounts.remove(viewModel.accounts()[4]);
Here's another approach that works and doesn't require the mapping plugin:
var model = #Model.ToJson();
var viewModel = {
accounts: ko.observableArray([]),
fromJS: function(js) {
for (var i = 0; i < js.length; i++) {
this.accounts.push({
Property1: ko.observable(js[i].Property1),
Property2: ko.observable(js[i].Property2),
Property3: ko.observable(js[i].Property3)
});
}
}
};
viewModel.fromJS(model);
ko.applyBindings(viewModel);

How can I create an Expression within another Expression?

Forgive me if this has been asked already. I've only just started using LINQ. I have the following Expression:
public static Expression<Func<TblCustomer, CustomerSummary>> SelectToSummary()
{
return m => (new CustomerSummary()
{
ID = m.ID,
CustomerName = m.CustomerName,
LastSalesContact = // This is a Person entity, no idea how to create it
});
}
I want to be able to populate LastSalesContact, which is a Person entity.
The details that I wish to populate come from m.LatestPerson, so how can I map over the fields from m.LatestPerson to LastSalesContact. I want the mapping to be re-useable, i.e. I do not want to do this:
LastSalesContact = new Person()
{
// Etc
}
Can I use a static Expression, such as this:
public static Expression<Func<TblUser, User>> SelectToUser()
{
return x => (new User()
{
// Populate
});
}
UPDATE:
This is what I need to do:
return m => (new CustomerSummary()
{
ID = m.ID,
CustomerName = m.CustomerName,
LastSalesContact = new Person()
{
PersonId = m.LatestPerson.PersonId,
PersonName = m.LatestPerson.PersonName,
Company = new Company()
{
CompanyId = m.LatestPerson.Company.CompanyId,
etc
}
}
});
But I will be re-using the Person() creation in about 10-15 different classes, so I don't want exactly the same code duplicated X amount of times. I'd probably also want to do the same for Company.
Can't you just use automapper for that?
public static Expression<Func<TblCustomer, CustomerSummary>> SelectToSummary()
{
return m => Mapper.Map<TblCustomer, CustommerSummary>(m);
}
You'd have to do some bootstrapping, but then it's very reusable.
UPDATE:
I may not be getting something, but what it the purpose of this function? If you just want to map one or collection of Tbl object to other objects, why have the expression?
You could just have something like this:
var customers = _customerRepository.GetAll(); // returns IEnumerable<TblCustomer>
var summaries = Mapper.Map<IEnumerable<TblCustomer>, IEnumerable<CustomerSummary>>(customers);
Or is there something I missed?
I don't think you'll be able to use a lambda expression to do this... you'll need to build up the expression tree by hand using the factory methods in Expression. It's unlikely to be pleasant, to be honest.
My generally preferred way of working out how to build up expression trees is to start with a simple example of what you want to do written as a lambda expression, and then decompile it. That should show you how the expression tree is built - although the C# compiler gets to use the metadata associated with properties more easily than we can (we have to use Type.GetProperty).
This is always assuming I've understood you correctly... it's quite possible that I haven't.
How about this:
public static Person CreatePerson(TblPerson data)
{
// ...
}
public static Expression<Func<TblPerson, Person>> CreatePersonExpression()
{
return d => CreatePerson(d);
}
return m => (new CustomerSummary()
{
ID = m.ID,
CustomerName = m.CustomerName,
LastSalesContact = CreatePerson(m.LatestPerson)
});

Resources