I am developing an app for windows phone 8.1, I have three pages, I'm using the Frame.Navigate(typeof(Page2),nav) to pass data between pages, I'm using a class
public class PassedData
{
public string Name { get; set; }
public string Name1 { get; set; }
public string Name3 { get; set; }
public int Value { get; set; }
}
for the object:
var nav = (passedData)e.Parameter;
myTextBlock.Text = nav.Name;
mytex1.Text = nav.Name1;
my problem how do the object for the int value? I have a problem with the conversion type int in the object.
just try this
int convertValue = 0;
var passedData= new PassedData;
passedData.Name="Name"; passedData.Name1="Name1"; passedData.Name3="Name3";
long number1 = 0;
bool canConvert = long.TryParse(myTextBox.Text, out convertValue );
if (canConvert == true)
{
passedData.Value= Convert.ToInt32(myTextBox.Text);
}
I think it will works
Related
Controller.cs
[HttpGet]
public async Task<ActionResult<IEnumerable<RankDistribution>>> GetTodoItems()
{
List<rank> rklist = new List<rank>();
rank rk = new rank
{
rankID = 0,
rankName = "Plastic 1",
playersInRank = 1,
percentInRank = 100f
};
rklist.Add(rk);
var rb = new RankDistribution
{
Id = 0,
rank = rklist
};
return rb;
}
Class.cs
public class RankDistribution
{
public long Id { get; set; }
public List<rank> rank { get; set; }
}
public class rank
{
public string rankName { get; set; }
public int rankID { get; set; }
public int playersInRank { get; set; }
public float percentInRank { get; set; }
}
Error Message
Cannot implicitly convert type 'RankAPI.Models.RankDistribution' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<RankAPI.Models.RankDistribution>>
I have only recently started working on an api, but I am pretty familiar on C#. How do I convert the return value so it goes through? Thanks!
You are returning a single item of RankDistribution
You should include it in a List and return the list
var toRet = new List<RankDistribution>();
toRet.Add(rb);
return toRet;
But in my opinion if you have the RankDistribution that contains a list inside of the items you want to return why not returning just rb and change the syntax of your method to
ActionResult<RankDistribution>
This question already has answers here:
SQLite .NET performance, how to speed up things?
(2 answers)
Closed 7 years ago.
I am having a hard time trying to save the data faster, to a local DB.
Even though this is a one time saving, when the app runs for the first time, it takes like 90 seconds, in a Lumia 920, to save "only" the "map tables".
What I do:
1) I call an API, where I receive all the grids, with its Xs, Ys, Map Id, etc.
2) I deserialize the info based on a class I have defined.
3) For each item, in that info, I save the "misc" info (since I will use it)
4) I save, in a GRIDS table, each grid inside the previous item.
This code snipet is what I use to deserialize the info, and call the function to save in the DB
public class Maps
{
public string id { get; set; }
public string name { get; set; }
public string height { get; set; }
public string width { get; set; }
public string tile { get; set; }
public string shopping_id { get; set; }
public string url { get; set; }
public string updated_at { get; set; }
public string created_at { get; set; }
public GridFirst gridFirst { get; set; }
public GridLast gridLast { get; set; }
public List<Grid> grid { get; set; }
public class GridFirst
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string maps_id { get; set; }
public string value { get; set; }
}
public class GridLast
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string maps_id { get; set; }
public string value { get; set; }
}
public class Grid
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string maps_id { get; set; }
public string value { get; set; }
}
public void deserializeAndConvert(string aaa)
{
JObject myGeneral = JObject.Parse(aaa);
IList<JToken> results = myGeneral["resp"].Children().ToList();
// serialize JSON results into .NET objects
IList<Maps> searchResults = new List<Maps>();
foreach (JToken result in results)
{
Maps searchResult = JsonConvert.DeserializeObject<Maps>(result.ToString());
searchResults.Add(searchResult);
}
var respuesta = from data in searchResults
select new
{
id = data.id,
name = data.name,
height = data.height,
width = data.width,
tile = data.tile,
url = data.url,
lastX = data.gridLast.x,
lastY = data.gridLast.y,
grid = data.grid
};
foreach (var a in respuesta)
{
Database_Controller.getReadyToSaveData("mapinfo", 8, a.id, a.name, a.height, a.width, a.tile, a.url, a.lastX, a.lastY, "", "", "", "", "", "", "");
foreach (var data in a.grid)
{
Database_Controller.getReadyToSaveData("mapgrid", 5, data.id, data.x, data.y, data.maps_id, data.value, "", "", "", "", "", "", "", "", "", "");
}
}
}
}
And these are the functions that save the data, in the DB
public static void getReadyToSaveData(string dbName, int numberOfParams, string param1, string param2, string param3, string param4, string param5, string param6, string param7, string param8, string param9, string param10, string param11, string param12, string param13, string param14, string param15)
{
List<string> myParams = new List<string>();
myParams.Add(param1);
myParams.Add(param2);
myParams.Add(param3);
myParams.Add(param4);
myParams.Add(param5);
myParams.Add(param6);
myParams.Add(param7);
myParams.Add(param8);
myParams.Add(param9);
myParams.Add(param10);
myParams.Add(param11);
myParams.Add(param12);
myParams.Add(param13);
myParams.Add(param14);
myParams.Add(param15);
List<string> myParamsToDB = new List<string>();
for (var i = 0; i < numberOfParams; i++)
{
myParamsToDB.Add(myParams[i]);
}
insertData(dbName, myParamsToDB);
}
public static void insertData(string dbName, List<string> paramsToGo)
{
try
{
using (var connection = new SQLiteConnection("Unicenter.sqlite"))
{
if (dbName == "mapgrid")
{
using (var statement = connection.Prepare(#"INSERT INTO mapgrid (ID,X,Y,MAPS_ID,VALUE)
VALUES(?, ?,?,?,?);"))
{
statement.Bind(1, paramsToGo[0]);
statement.Bind(2, paramsToGo[1]);
statement.Bind(3, paramsToGo[2]);
statement.Bind(4, paramsToGo[3]);
statement.Bind(5, paramsToGo[4]);
// Inserts data.
statement.Step();
statement.Reset();
statement.ClearBindings();
}
}
if (dbName == "mapinfo")
{
using (var statement = connection.Prepare(#"INSERT INTO mapinfo (ID,NAME,HEIGHT,WIDTH,TILE,URL,LASTX,LASTY)
VALUES(?, ?,?,?,?,?,?,?);"))
{
statement.Bind(1, paramsToGo[0]);
statement.Bind(2, paramsToGo[1]);
statement.Bind(3, paramsToGo[2]);
statement.Bind(4, paramsToGo[3]);
statement.Bind(5, paramsToGo[4]);
statement.Bind(6, paramsToGo[5]);
statement.Bind(7, paramsToGo[6]);
statement.Bind(8, paramsToGo[7]);
// Inserts data.
statement.Step();
statement.Reset();
statement.ClearBindings();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception\n" + ex.ToString());
}
}
***Edit: As a kind reminder, in case some people does not see the tags (and mark this question as duplicated), this is FOR WINDOWS PHONE 8.1, so, the functions, references and classes ARE different from plain c#
Any idea on how to make it faster? ... What am I doing wrong?
you can use parallel.for loop which is more faster if you have large data or you can easily check each loop how much time it takes to execute in VS-2015
I have one xml file and I want to generate custom list from that xml using Linq.
here is my code. But I am not getting any records.Here is my code.
public class TemplateSettings {
public string DecimalSeparator { get; set; }
public string ThousandSeparator { get; set; }
public string DateSeparator { get; set; }
public string TimeSeparator { get; set; }
}
XML Here
<TemplateSetting>
<DecimalSeparator>1</DecimalSeparator>
<ThousandSeparator>2</ThousandSeparator>
<DateSeparator>3</DateSeparator>
<TimeSeparator>4</TimeSeparator>
<DateFormat>dd/MM/yyyy</DateFormat>
<ValueDelimiter>tr</ValueDelimiter>
<QuoteCharacter>r</QuoteCharacter>
<IsHeader>False</IsHeader>
</TemplateSetting>
And my code to get object from xml is
var a = (from x in objTemplateMasterEAL.TemplatSettingsXML.Elements("TemplateSetting")
select new TemplateSettings()
{
DateFormat = (string)x.Element("DateFormat"),
DecimalSeparator = (string)x.Element("DecimalSeparator"),
ThousandSeparator = (string)x.Element("ThousandSeparator"),
DateSeparator = (string)x.Element("DateSeparator"),
TimeSeparator = (string)x.Element("TimeSeparator"),
QuoteCharacter = (string)x.Element("QuoteCharacter"),
ValueDelimiter = (string)x.Element("ValueDelimiter"),
IsHeaderLine = (bool)x.Element("IsHeader")
}).ToList<TemplateSettings>();
Can any one suggest me what is wrong here ?
If your goal is just to deserialize the XML to object you can simply use this:
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = new StreamReader("Sample.xml"))
{
var serializer = new XmlSerializer(typeof(TemplateSetting));
var templateSetting = (TemplateSetting)serializer.Deserialize(reader);
}
}
}
[XmlRoot]
public class TemplateSetting
{
public string DecimalSeparator { get; set; }
public string ThousandSeparator { get; set; }
public string DateSeparator { get; set; }
public string TimeSeparator { get; set; }
}
I make only on one change and its working fine for me.
<TemplateSettings>
<TemplateSetting>
<DecimalSeparator>1</DecimalSeparator>
<ThousandSeparator>2</ThousandSeparator>
<DateSeparator>3</DateSeparator>
<TimeSeparator>4</TimeSeparator>
<DateFormat>dd/MM/yyyy</DateFormat>
<ValueDelimiter>tr</ValueDelimiter>
<QuoteCharacter>r</QuoteCharacter>
<IsHeader>False</IsHeader>
</TemplateSetting>
</TemplateSettings>
I am trying to populate a List in C# but the values are not appearing in the array - though it does not throw an error until I try and set a variable with an array index (because it is out of range of course).
This is the exact return string strJSON I am seeing while debugging.
strJSON "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}"
Why is the List (array) not populating?
This is the code for KeyValue.cs (which to be honest I do not know yet why it needs another class)
namespace LoLSummoner
{
public class KeyValue
{
public int id {get; set;}
public string name {get; set;}
public int profileIconId {get; set;}
public int summonerLevel {get; set;}
public int revisionDate {get; set;}
}
}
And this is the code from Summoner.svc.cs
namespace LoLSummoner
{
public class Summoner : ISummoner
{
public int GetSummonerID(string SummonerName)
{
int summonerId = 0;
WebClient client = new WebClient();
string strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.2/summoner/by-name/" + SummonerName + "?api_key=xxxx");
JavaScriptSerializer js = new JavaScriptSerializer();
KeyValue[] arrJSON = js.Deserialize<List<KeyValue>>(strJSON).ToArray();
summonerId = Convert.ToInt32(arrJSON.GetValue(0));
return summonerId;
}
}
}
Your JSON contains a single object, not an array.
Therefore, you can only deserialize it as KeyValue.
Your RevisionDate property has to be long, because 1387913628000, and that's the value your trying to deserialize, exceeds int range.
Your JSON contains information about only one KeyValue object, not an array of there, so you have to deserialize it as KeyValue, no KeyValue[]:
KeyValue item = js.Deserialize<KeyValue>(strJSON);
Having KeyValue instance you can use standard property syntax to return ID:
return item.id;
I find this code working:
public class KeyValue
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
static void Main(string[] args)
{
var input = #"{""id"":34379899,""name"":""Revelation22"",""profileIconId"":547,""summonerLevel"":30,""revisionDate"":1387913628000}";
JavaScriptSerializer js = new JavaScriptSerializer();
var item = js.Deserialize<KeyValue>(input);
var summonerId = item.id;
}
I do not know yet why it needs another class
You don't need that class. It think the simplest way would be to deserialize your json directly to Dictionary<string, object>
var strJSON = "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}";
var dict = new JavaScriptSerializer()
.Deserialize<Dictionary<string, object>>(strJSON);
Console.WriteLine(dict["name"]);
Console.WriteLine(ToDateTime((long)dict["revisionDate"]));
DateTime ToDateTime(long l)
{
return new DateTime(1970, 1, 1).AddMilliseconds(l);
}
As already noted, the revisionDate will cause a runtime binding exception if it is not typed as a long.
public class KeyValue
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
In addition to that, you may wish to attempt a simple detection in order to deserialize this as either an object or an array of objects (if in the future the name is no longer unique).
public int GetSummonerID(string SummonerName)
{
int summonerId = 0;
WebClient client = new WebClient();
string strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.2/summoner/by-name/" + SummonerName + "?api_key=xxxx");
JavaScriptSerializer js = new JavaScriptSerializer();
if(strJSON[0] == '[')
{
return js.Deserialize<KeyValue[]>(strJSON)[0].id;
}
else
{
return js.Deserialize<KeyValue>(strJSON).id;
}
return summonerId;
}
One thing to note is that your JSON string contains only a single KeyValue, not a list of them. Another problem is that the revision date is too large to fit in a 32 bit int, so consider using a long instead.
Here's some example code that reads your sample string and prints out some of the values.
public class KeyValue
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
static void Main(string[] args)
{
var strJSON = "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}";
var serializer = new JavaScriptSerializer();
var keyValue = serializer.Deserialize<KeyValue>(strJSON);
var id = keyValue.id;
var name = keyValue.name;
var level = keyValue.summonerLevel;
Console.WriteLine("Summoner name:{0}, Id:{1}, Level:{2}", name, id, level);
Console.Read();
}
In my controller I'm looping through items and saving them to my db. The problem is that it saves the first item, but none of the others. I put a breakpoint on the "SaveItem()" line in the loop and it hits it every time, but what seems odd to me is that it only goes through to the method for the 1st item.
What am I doing wrong?
public void SubmitItem(Cart cart, ShippingDetails shippingDetails, ProcessedItems processedItem, string orderID)
{
var cartItems = cart.Lines;
//CartIndexViewModel cartIndex = new CartIndexViewModel();
//var customID = cartIndex.OrderID;
foreach(var item in cartItems)
{
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
}
public class EFProcessedItemsRepository : IProcessedItems
{
private EFDbContext context = new EFDbContext();
public IQueryable<ProcessedItems> ProcessedItem
{
get { return context.ProcessedItems; }
}
public void SaveItem(ProcessedItems processedItem)
{
if(processedItem.ProcessedID == 0)
{
try
{
context.ProcessedItems.Add(processedItem);
context.SaveChanges();
}
catch (Exception)
{
throw;
}
}
else
{
context.Entry(processedItem).State = EntityState.Modified;
}
}
public void DeleteItem(ProcessedItems processedItem)
{
context.ProcessedItems.Remove(processedItem);
context.SaveChanges();
}
}
here is the class for the processedItem:
public class ProcessedItems
{
[Key]
public int ProcessedID { get; set; }
public string OrderID { get; set; }
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string ImageName { get; set; }
public string Image2Name { get; set; }
public string Image3Name { get; set; }
public string Status { get; set; }
//shipping
public string BuyerName { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
Interface:
public interface IProcessedItems
{
IQueryable<ProcessedItems> ProcessedItem { get; }
void SaveItem(ProcessedItems processedItem);
void DeleteItem(ProcessedItems processedItem);
}
try calling context.SaveChanges() after adding all of the items, I think it should persist them all in one go.
Another thing to try:
Refactor your code so that SaveItem accepts only one item to save, Add it and call SaveChanges()
Loop through the cart items outside the method and call the method with one item to save at a time.
// set orderID, shippingDetails above
foreach(var item in cartItems)
{
ProcessedItems processedItem = new ProcessedItems();
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
SubmitItem(processedItem);
}
public void SubmitItem(ProcessedItems processedItem)
{
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
I think it is because processedItem is the same instance for each loop iteration. So after it has been through SaveItem once, it has its ProcessedID set and therefore won't get processed again.
My first guess is that you always store one entity, which is stored in processedItem, which is a input parameter. Try to create new Entity on each loop and then save it. In other words, you assign values to input parameter
processedItem.OrderID = orderID;
and then store same entity each time, but with changed fields
processedItems.SaveItem(processedItem);