Updating xml file in windows 8 phone application - windows-phone-8

I am creating a windows 8 phone application, in which i am reading a xml file called User and add want to add the attributes id and name to the user element of the xaml using XDocument.
But I am not getting how to save it back to the xml file.
XDocument doc = XDocument.Load(#"XDocument.Load(#"Assets\User.xml");
XElement element = doc.Element("user");
XAttribute idAtt = new XAttribute("id", userDetails.UserId);
element.Add(idAtt);
XAttribute nameAtt = new XAttribute("name", userDetails.UserName);
element.Add(nameAtt);
Please help.

That's how I save my XML files:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("User.xml", FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(PrivacyDataClass));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, data);
}
}
}

Related

parsing issue with JSON data from SQL 2017 to MongoDB

I am working on c# utility to migrate data from SQL server 2017 to MongoDB. Below are steps I am following
1) Getting data from SQL server in JSON format (FOR JSON AUTO)
2) Parsing into BSON document
3) Then trying to insert into MongoDB
But I am getting error while reading JSON data from SQL.
My Json data is combination of root attributes as well as nested objects.
So Its dynamic data, that I want to PUSH as it is to MongoDB.
string jsonData = string.Empty;
foreach (var userId in userIdList)
{
using (SqlConnection con = new SqlConnection("Data Source=;Initial Catalog=;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("Usp_GetUserdata", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userId", SqlDbType.Int).Value = userId;
con.Open();
var reader = cmd.ExecuteReader();
jsonResult = new StringBuilder();
//cmd.ExecuteNonQuery();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0));
jsonData = reader.GetValue(0).ToString();
File.WriteAllText(#"c:\a.txt", jsonResult.ToString());
File.WriteAllText(#"c:\a.txt",jsonData);
jsonData.TrimEnd(']');
jsonData.TrimStart('[');
//Create client connection to our MongoDB database
var client = new MongoClient(MongoDBConnectionString);
//Create a session object that is used when leveraging transactions
var session = client.StartSession();
//Create the collection object that represents the "products" collection
var employeeCollection = session.Client.GetDatabase("mongodev").GetCollection<BsonDocument>("EmpData");
//Begin transaction
session.StartTransaction();
try
{
dynamic resultJson = JsonConvert.DeserializeObject(result);
var document = BsonSerializer.Deserialize<BsonDocument>(resultJson);
//MongoDB.Bson.BsonDocument document
// = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonResult);
employeeCollection.InsertOneAsync(document);
//BsonArray pipeline =
// MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonArray>(jsonData);
//var documents = pipeline.Select(val => val.AsBsonDocument);
//employeeCollection.InsertManyAsync(documents);
session.CommitTransaction();
}
catch (Exception e)
{
Console.WriteLine(e);
session.AbortTransaction();
throw;
}
}
}
}
}
}

MaxLength not available in MVC Core json result

I have developed web API with this method and I test it with Advanced Rest Client in my machine and everything is alright, but after deploy to server the result is omitted by the server and not recognize as valid JSON text and not parse correctly.
[Route("[action]")]
[HttpGet]
public async Task<JsonResult> GetAllCityEvent(string apiKey)
{
List<CityMapMarker> availableMapMarkers = new List<CityMapMarker>();
PersianUtilCore.Api.MethodResult result = new PersianUtilCore.Api.MethodResult();
List<PersianUtilCore.Api.MethodError> errors = new List<PersianUtilCore.Api.MethodError>();
ApiBO apiBO = new ApiBO(AggregateService);
bool isValidKey = apiBO.IsValidKey(apiKey);
if (!isValidKey)
{
result.IsSuccess = false;
errors.Add(new PersianUtilCore.Api.MethodError(300, "your key is not valid!"));
}
else
{
JunctionBO junctionBO = new JunctionBO(AggregateService);
StreetBO streetBO = new StreetBO(AggregateService);
HighwayBO highwayBO = new HighwayBO(AggregateService);
SightBO sightBO = new SightBO(AggregateService);
TrafficLightBO trafficLightBO = new TrafficLightBO(AggregateService);
CameraBO cameraBO = new CameraBO(AggregateService);
TransportationStationBO bussStationBO = new TransportationStationBO(AggregateService);
TrafficBO trafficBO = new TrafficBO(AggregateService);
CityEventBO cityEventBO = new CityEventBO(AggregateService);
//availableMapMarkers.AddRange(junctionBO.CityMapMarkers());
//availableMapMarkers.AddRange(streetBO.CityMapMarkers());
//availableMapMarkers.AddRange(highwayBO.CityMapMarkers());
//availableMapMarkers.AddRange(sightBO.CityMapMarkers());
//availableMapMarkers.AddRange(trafficLightBO.CityMapMarkers());
//availableMapMarkers.AddRange(trafficBO.CityMapMarkers());
//availableMapMarkers.AddRange(cameraBO.CityMapMarkers());
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.Bus));
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.Train));
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.BRT));
availableMapMarkers.AddRange(cityEventBO.CityMapMarkers());
result.Result = availableMapMarkers;
result.IsSuccess = true;
}
result.Errors = errors;
result.Result = availableMapMarkers;
result.IsSuccess = errors.Count <= 0;
var logHistoryResult = apiBO.LogHistory(apiKey, nameof(this.GetAllCityEvent));
return Json(result);
}
I couldn't find any way to change JsonResult max length like with I did in Asp.net MVC4 or Asp.net Webforms
How can I increase JsonResult maxlength in MVC Core?
Why there is different in IIS publish or local machine when I try to get result from my web API?

IsolatedStorage Edit in Windows Phone ScheduledTask

I am reading data from IsolatedStorage, but can't edit it in ScheduledTask. How can I edit it?
private void StartToastTask(ScheduledTask task)
{
long rank = 0, difference = 0;
string text = "", nickname = "";
PishtiWCF.PishtiWCFServiceClient ws = ServiceClass.GetPishtiWCFSvc();
ws.GetUsersRankCompleted += (src, e) =>
{
try
{
if (e.Error == null)
{
difference = rank - e.Result.GeneralRank;
if (!String.IsNullOrEmpty(nickname))
{
if (difference < 0)
text = string.Format("{0}, {1} kişi seni geçti!", nickname, difference.ToString(), e.Result.GeneralRank);
else if (difference > 0)
text = string.Format("{0}, {1} kişiyi daha geçtin!", nickname, Math.Abs(difference).ToString(), e.Result.GeneralRank);
else if (e.Result.GeneralRank != 1)
text = string.Format("{0}, sıralamadaki yerin değişmedi!", nickname, e.Result.GeneralRank);
else
text = string.Format("{0}, en büyük sensin, böyle devam!", nickname);
}
else
return;
Mutex mut;
if (!Mutex.TryOpenExisting("IsoStorageMutex", out mut))
mut = new Mutex(false, "IsoStorageMutex");
mut.WaitOne();
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = file.OpenFile("UserRanks", FileMode.Open, FileAccess.Write))
{
StreamWriter writer = new StreamWriter(stream);
writer.Write(string.Format("{0},{1}", nickname, e.Result.GeneralRank));
writer.Close();
stream.Close();
}
}
mut.ReleaseMutex();
ShellToast toast = new ShellToast();
toast.Title = "Pishti";
toast.Content = text;
toast.Show();
}
FinishTask(task);
}
catch (Exception)
{
}
};
try
{
Mutex mut;
if (!Mutex.TryOpenExisting("IsoStorageMutex", out mut))
mut = new Mutex(false, "IsoStorageMutex");
mut.WaitOne();
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = file.OpenFile("UserRanks", FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(stream))
{
string temp = reader.ReadToEnd();
if (temp.Split(',').Count() > 1)
{
nickname = temp.Split(',')[0];
rank = long.Parse(temp.Split(',')[1]);
ws.GetUsersRankAsync(nickname);
}
reader.Close();
}
stream.Close();
}
}
mut.ReleaseMutex();
}
catch (Exception)
{
}
}
I am getting rank from UserRanks file, for example 1200, but when I get and data from WCF, edit it to 1000 and want to write it to IsolatedStorage, It doesn't crash application but it fails.
Do you know why?
Thanks.
I've fixed it with delete file.
Mutex mut;
if (!Mutex.TryOpenExisting("IsoStorageMutex", out mut))
mut = new Mutex(false, "IsoStorageMutex");
mut.WaitOne();
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
if (file.FileExists("UserRanks"))
file.DeleteFile("UserRanks");
using (IsolatedStorageFileStream stream = file.OpenFile("UserRanks", FileMode.OpenOrCreate, FileAccess.Write))
{
StreamWriter writer = new StreamWriter(stream);
writer.Write(string.Format("{0},{1}", nickname, e.Result.GeneralRank));
writer.Close();
stream.Close();
}
}
mut.ReleaseMutex();
You appear to write to the file first, which makes sense, but when you do so you use a file access mode - FileMode.Open - which means "open an existing file". The first time you do this the file won't exist and the open will fail.
You should either use FileMode.OpenOrCreate, which is self explanatory, or FileMode.Append which will open the file if it exists and seek to the end of the file, or create a new file if it doesn't.
If you want to throw away any pre-existing file (which is what your delete then create will do) then just use FileMode.Create

How to write byte array to StorageFile in WindowsPhone 8

I searched and found this but it's not available for Windows Phone 8 and only works for Windows Store apps:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.fileio.writebytesasync
How do I do this in WP8?
You can use binary writer:
byte[] buffer;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream FS = new IsolatedStorageFileStream(fileName, FileMode.Create, ISF))
{
using (BinaryWriter BW = new BinaryWriter(FS))
{
BW.Write(buffer, 0, buffer.Lenght);
}
}
}
Or make it simpler as #KooKiz said:
using (IsolatedStorageFileStream FS = new IsolatedStorageFileStream(fileName, FileMode.Create, ISF))
{
FS.Write(buffer, 0, buffer.Lenght);
}

Write output values to a json file using java

Hi below is my code to extract particular metadata tags and write those tags to a json file. And i imported json.lib.jar and tika-app.jar into my build path.
File dir = new File("C:/pdffiles");
File listDir[] = dir.listFiles();
for (int i = 0; i < listDir.length; i++)
{
System.out.println("files"+listDir.length);
String file=listDir[i].toString();
File file1 = new File(file);
InputStream input = new FileInputStream(file1);
Metadata metadata = new Metadata();
BodyContentHandler handler = new BodyContentHandler(10*1024*1024);
AutoDetectParser parser = new AutoDetectParser();
parser.parse(input, handler, metadata);
Map<String, String> map = new HashMap<String, String>();
map.put("File name: ", listDir[i].getName());
map.put("Title: " , metadata.get("title"));
map.put("Author: " , metadata.get("Author"));
map.put("Content type: " , metadata.get("Content-Type"));
JSONObject json = new JSONObject();
json.accumulateAll(map);
FileWriter file2;
file2 = new FileWriter("C:\\test.json");
file2.write(json.toString());
file2.flush();
}
But it is writing only single file metadata to the json file. Is there any problem with my code, please suggest me.
may be you should use-
file2.write(json.toJSONString());
instead of this line -
file2.write(json.toString());