Error while reading data from azure table storage - c#

I'm writing a code to read values from a table storage. The code is similar to printing nodes in a tree level by level.
eg:
root
Level1child1 -> Level1child2 -> Level1child3
string tablename = "<table-name">;
string storageAccountName = "<storage-account-name";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = getAccountSASToken();
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = _tableStorageRepository.GetAccountSASToken();
filter = #"&$filter=ParentNodeId%20eq%20" + strQ.Peek();
url = $"{url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
foreach (var m in odata?.value)
{
Console.WriteLine(m.Email);
strQ.Enqueue(m.TreeNodeID);
}
strQ.Dequeue();
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
Code for HttpHelper class: https://github.com/xyz92/httphelper/blob/master/HttpHelper.cs
The first time when I ran this code, it only printed root node.
The second time when I ran this code, it printed root node and Level1child1 node.
For the next runs, it printed root node, Level1child1 node & Level1child2 node.
The last node Level1child3 node is getting printed very rarely on some runs.
What am I missing in this code?
UPDATE:
Sample responseData:
{
"odata_metadata": "https://<storage-account-name>_table_core_windows_net/$metadata#<table-name>",
"value": [{
"odata_type": "<storage-account-name>_<table-name>",
"odata_id": "https://<storage-account-name>_table_core_windows_net/<table-name>(PartitionKey='123',RowKey='abc')",
"odata_etag": "W/\"datetime'2020-09-01T16%3A34%3A21_3342187Z'\"",
"odata_editLink": "<table-name>(PartitionKey='123',RowKey='abc')",
"PartitionKey": "123",
"RowKey": "abc",
"Timestamp#odata_type": "Edm_DateTime",
"Timestamp": "2020-09-01T16:34:21_3342187Z",
"Email": "email",
"ParentNodeID": 1,
"TreeNodeID": 2
}
]
}
Table columns:
Sample data in Table:
Sample outputs while running code:

According to my test, I cannot reproduce your issue in my environment. My test is as below
Table columns:
Sample data in table
Code I use your HttpHelper class to send request
class Program
{
static async Task Main(string[] args)
{
string storageAccountName = "andyprivate" ;
string tableName = "test";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = "";
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
int i = 0;
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = "";
filter = #$"&$filter=ParentNodeID eq {strQ.Peek()}";
url = $"{ url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (var m in odata?.value)
{
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
Console.WriteLine(m.Email);
}
strQ.Dequeue();
}
Console.ReadLine();
}
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
Update
My test code
Rest API (I use your HttpHelper class to send request)
class Program
{
static async Task Main(string[] args)
{
string storageAccountName = "andyprivate" ;
string tableName = "test";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = "";
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
int i = 0;
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = "";
filter = #$"&$filter=ParentNodeID eq {strQ.Peek()}";
url = $"{ url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (var m in odata?.value)
{
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
Console.WriteLine(m.Email);
}
strQ.Dequeue();
}
Console.ReadLine();
}
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
SDK. I use the package Microsoft.Azure.Cosmos.Table
string storageAccountName = "andyprivate";
string accountKey ="";
string tableName = "test";
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKey), true);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
CloudTable table = tableClient.GetTableReference(tableName);
TableOperation retrieveOperation = TableOperation.Retrieve<CustomEntity>("123", "abc");
TableResult result = await table.ExecuteAsync(retrieveOperation);
CustomEntity entity = result.Result as CustomEntity;
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(entity.Email);
strQ.Enqueue(entity.TreeNodeID);
while (strQ.Any()) {
int i = 0;
TableQuery<CustomEntity> query = new TableQuery<CustomEntity>()
.Where(
TableQuery.GenerateFilterConditionForInt("ParentNodeID", QueryComparisons.Equal,strQ.Peek())
);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (CustomEntity m in table.ExecuteQuery(query) ) {
Console.WriteLine(m.Email);
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
}
strQ.Dequeue();
}

Related

Error "Unexpected character encountered while parsing value"

while I am trying to make a http request with httpClient I keep getting this error but I do not know why.
Unexpected character encountered while parsing value: c. Path '',
line 0, position 0."]},"title":"One or more validation errors
occurred.","status":400,
here is my code, and I am using console application to make the request:
class Program {
static void Main (string[] args) {
Data _dt = new Data();
_dt.IP = "192.156.25";
_dt.LogText = "test from http";
_dt.LogType = 1;
_dt.StoreId = 14;
_dt.StoreName = "testino";
_dt.UserId = 2;
NewAddStoreLog(_dt);
}
static void NewAddStoreLog (Data dt) {
HttpClient http = new HttpClient ();
var content = new StringContent (dt.ToString (), Encoding.UTF8, "application/json");
var result = http.PostAsync ("http://192.168.8.180:88/Logs/RecordLogs", content).Result;
string strResult = System.Text.Encoding.UTF8.GetString (result.Content.ReadAsByteArrayAsync ().Result);
System.Console.WriteLine(strResult);
}
}
public class Data {
public int StoreId { get; set; }
public int UserId { get; set; }
public string IP { get; set; }
public int LogType { get; set; } //Enum
public string LogText { get; set; }
public string StoreName { get; set; }
}

How to push to do a emdeded document in mongodb c# driver

i have a problem how to push a document into a another document to create a embeded document in c#.
my models look like :
public class ModelKnjiga
{
public ModelKnjiga() { }
[BsonId(IdGenerator = typeof(CombGuidGenerator))] // pojavljuje se greška kod BSON tipa podataka kod ID-a,preuzoteo s dokumentacije drivera 1.5
public Guid Id { get; set; }
[BsonElement("naziv")]
public string naziv { get; set; }
[BsonElement("autor")]
public string autor { get; set; }
[BsonElement("godina_izdanja")]
public string godina_izdanja { get; set; }
[BsonElement("izdavac")]
public string izdavac { get; set; }
[BsonElement("ocjena")]
public String ocjena { get; set; }
[BsonElement("čitam")]
public Boolean čitam { get; set; }
[BsonElement("završio")]
public Boolean završio { get; set; }
}
another model looks like :
public ModelKorisici () {
KnjigaLista = new List<ModelKnjiga>();
}
[BsonId] // pojavljuje se greška kod BSON tipa podataka kod ID-a,preuzoteo s dokumentacije drivera 1.5 CombGuidGenerator
public Guid Identifikator { get; set; }
[BsonElement("ime")]
public string ime { get; set; }
[BsonElement("prezime")]
public string prezime { get; set; }
[BsonElement("lozinka")]
public string lozinka { get; set; }
[BsonElement("email")]
public string email { get; set; }
[BsonElement("kor_ime")]
public string kor_ime { get; set; }
[BsonElement("uloga")]
public string uloga { get; set; }
public List<ModelKnjiga> KnjigaLista { get; set; }
}
and now i am tring to push a modelKnjiga into a modelKorisici
I am trying with this method...
public void dodajKnjiguKorisniku(ModelKnjiga knjiga, Guid id)
{
MongoCollection<ModelKorisici> korisniciKolekcija = GetTasksCollectionKlijenti();
try
{
var pronadiKorisnika = Query<ModelKorisici>.EQ(e => e.Identifikator, id);
var PushPodataka = Update<ModelKorisici>.Push(e => e.KnjigaLista, knjiga);
korisniciKolekcija.Update(pronadiKorisnika, PushPodataka);
}
catch (MongoCommandException ex)
{
string msg = ex.Message;
}
}
In robomongo, the object KnjigaLista is always Null...
Can somebody help?
I think Update is legacy.
(in your models you don't have to use strings only. Eg.: godina_izdanja could be DateTime(), and ocjena some numeric format...)
I made an (async) example with your models, hope it helps:
class Program
{
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
Console.WriteLine("");
Console.WriteLine("press enter");
Console.ReadKey();
}
static async Task MainAsync(string[] args)
{
ModelKnjiga knga = new ModelKnjiga()
{
autor = "Author",
godina_izdanja = "2015",
izdavac = "izdavac",
naziv = "naziv",
ocjena = "20",
završio = true,
čitam = true
};
ModelKnjiga knga2 = new ModelKnjiga()
{
autor = "Author2",
godina_izdanja = "2016",
izdavac = "izdavac2",
naziv = "naziv2",
ocjena = "202",
završio = false,
čitam = false
};
ModelKnjiga knga3 = new ModelKnjiga()
{
autor = "Author3",
godina_izdanja = "2017",
izdavac = "izdavac3",
naziv = "naziv3",
ocjena = "203",
završio = false,
čitam = true
};
ModelKorisici mcor = new ModelKorisici()
{
email = "no#where.com",
ime = "ime",
KnjigaLista = new List<ModelKnjiga>() { knga, knga2 },
kor_ime = "kor_ime",
uloga = "uloga",
lozinka = "lozinka",
prezime = "prezime"
};
var client = new MongoClient();
var db = client.GetDatabase("KnjigaDB");
var korisici = db.GetCollection<ModelKorisici>("Korisici");
//After first run comment this line out
await korisici.InsertOneAsync(mcor);
//After first run UNcomment these lines
//var filter = Builders<ModelKorisici>.Filter.Eq("email", "no#where.com");
//var update = Builders<ModelKorisici>.Update.Push("KnjigaLista", knga3);
//await korisici.UpdateOneAsync(filter, update);
}
}
if you don't like async, change the last line with this:
korisici.UpdateOne(filter, update);

How to fill mongo Db table by C# Driver?

I am not an expert of nosql but a year ago I created a mongodb table by using below code:
const string connectionString = "mongodb://localhost:27017";
// Create a MongoClient object by using the connection string
var client = new MongoClient(connectionString);
////Use the MongoClient to access the server
var database = client.GetDatabase("YUSUF");
////get mongodb collection
var collection = database.GetCollection("expressions");
var expression = new Expression { Id = Guid.NewGuid().ToString(),ExpressionSentence = "Test",Name = "yusuf",CreatedDate = DateTime.Now,Status = true };
collection.InsertOneAsync(expression);
public class Expression {
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string ExpressionSentence { get; set; }
public bool Status { get; set; }
public DateTime CreatedDate { get; set; }
}
Today above codes is doing nothing now. Not working also not throwing any error. What am I doing wrong?
static void insert()
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var database = client.GetDatabase("YUSUF");
var collection = database.GetCollection<Expression>("expressions");
var expression = new Expression { Id = Guid.NewGuid().ToString(),ExpressionSentence = "Test",Name = "yusuf",CreatedDate = DateTime.Now,Status = true };
collection.InsertOneAsync(expression);
}
public class Expression {
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string ExpressionSentence { get; set; }
public bool Status { get; set; }
public DateTime CreatedDate { get; set; }
}
have to work with the latest C# MongoDB Driver.
MY METHOD
static void insert()
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var database = client.GetDatabase("fairytale");
// var unicorns = database.GetCollection("unicorns");
var unicorns = database.GetCollection<BsonDocument>("unicorns");
int i = 0;
while (i < 5000)
{
var document = new BsonDocument
{
{"name",GenerateRandomUnicornName()},
{"horns",Random.Next(50)},
{"likes",new BsonArray{ "apple", "onion" }},
};
unicorns.InsertOneAsync(document);
i++;
}
}

Using the Constant Contact C# .net-sdk v2 to create/add

I'm using the official version 2 of the Constant Contact .net-sdk found here.
I've been unable to find methods for the following:
Creating a Contact List
Adding a contact to a Contact List
Removing a contact from a Contact List
Adding multiple contacts to a Contact List
Creating an Email Campaign
These features clearly exist in v2 of the API found here, but seem missing from the SDK.
Any help in accessing this functionality is appreciated.
Create Contact.
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");
ContactObject cont = new ContactObject
{
first_name = "Deepu",
last_name = "Madhusoodanan"
};
var email_addresses = new List<EmailAddress>
{
new EmailAddress{email_address = "deepumi1#gmail.com"}
};
cont.email_addresses = email_addresses;
cont.lists = new List<List>
{
new List {id = "<Replace with your List Id>"}
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(cont);
string MessageType = "application/json";
using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://api.constantcontact.com/v2/contacts?api_key=<Replace with your API key>"))
{
request.Headers.Add("Accept", MessageType);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(MessageType);
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
string responseXml = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var code = response.StatusCode;
}
request.Content.Dispose();
}
}
}
catch (Exception exp)
{
//log exception here
}
/*Model class*/
public class Address
{
public string address_type { get; set; }
public string city { get; set; }
public string country_code { get; set; }
public string line1 { get; set; }
public string line2 { get; set; }
public string line3 { get; set; }
public string postal_code { get; set; }
public string state_code { get; set; }
public string sub_postal_code { get; set; }
}
public class List
{
public string id { get; set; }
}
public class EmailAddress
{
public string email_address { get; set; }
}
public class ContactObject
{
public List<Address> addresses { get; set; }
public List<List> lists { get; set; }
public string cell_phone { get; set; }
public string company_name { get; set; }
public bool confirmed { get; set; }
public List<EmailAddress> email_addresses { get; set; }
public string fax { get; set; }
public string first_name { get; set; }
public string home_phone { get; set; }
public string job_title { get; set; }
public string last_name { get; set; }
public string middle_name { get; set; }
public string prefix_name { get; set; }
public string work_phone { get; set; }
}
Note : You have to replace oAuth token, API key and List id.
Delete method based on the api document.(http://developer.constantcontact.com/docs/contacts-api/contacts-resource.html?method=DELETE)
Note : I have not tested the delete method yet.
private async Task<string> DeleteContact(string contactId)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");
using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Delete, "https://api.constantcontact.com/v2/contacts/" + contactId + "?api_key=<Replace with your API key>"))
{
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
}
catch (Exception exp)
{
//log exp here
}
return string.Empty;
}
Here is my solution for adding a contact. What I did was combine the code that Deepu provided with the Constant Contact API v2. I also had to remove async and await references because they are incompatible with VS2010. I have not tried DELETE yet...
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using CTCT.Components.Contacts;
using System.Net.Http.Headers;
/// <summary>
/// Constant Contact Helper Class for POST, PUT, and DELETE
/// </summary>
public class ConstantContactHelper
{
private string _accessToken = ConfigurationManager.AppSettings["ccAccessToken"];
private Dictionary<string, System.Net.Http.HttpMethod> requestDict = new Dictionary<string, System.Net.Http.HttpMethod> {
{"GET", HttpMethod.Get},
{"POST", HttpMethod.Post},
{"PUT", HttpMethod.Put},
{"DELETE", HttpMethod.Delete}
};
private System.Net.Http.HttpMethod requestMethod = null;
private Dictionary<string, ConstantContactURI> uriDict = new Dictionary<string, ConstantContactURI> {
{"AddContact", new ConstantContactURI("contacts")},
{"AddContactList", new ConstantContactURI("lists")},
{"AddEmailCampaign", new ConstantContactURI("campaigns")},
};
private ConstantContactURI URI_Handler = new ConstantContactURI();
private ContactRequestBody RequestBody = new ContactRequestBody();
private const string messageType = "application/json";
public string jsonRequest = null;
public string responseXml = null;
public string status_code = null;
public ConstantContactHelper() {}
public ConstantContactHelper(string methodKey, string uriKey, string firstName, string lastName, string emailAddress, string listId)
{
this.requestMethod = this.requestDict[methodKey];
this.URI_Handler = this.uriDict[uriKey];
this.RequestBody = new ContactRequestBody(firstName, lastName, emailAddress, listId);
}
// Return Response as a string
public void TryRequest()
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this._accessToken);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(this.RequestBody.contact);
this.jsonRequest = json;
using (var request = new HttpRequestMessage(HttpMethod.Post, this.URI_Handler.fullURI))
{
request.Headers.Add("Accept", messageType);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(messageType);
using (var response = client.SendAsync(request))
{
this.responseXml = response.Result.Content.ReadAsStreamAsync().ConfigureAwait(false).ToString();
this.status_code = response.Status.ToString();
}
request.Content.Dispose();
}
}
}
catch(Exception exp)
{
// Handle Exception
this.responseXml = "Unhandled exception: " + exp.ToString();
}
}
}
public class ConstantContactURI
{
private const string baseURI = "https://api.constantcontact.com/v2/";
private const string queryPrefix = "?api_key=";
private string _apiKey = ConfigurationManager.AppSettings["ccApiKey"];
public string fullURI = null;
public ConstantContactURI() {}
public ConstantContactURI(string specificPath)
{
this.fullURI = baseURI + specificPath + queryPrefix + _apiKey;
}
}
public class ContactRequestBody
{
public Contact contact = new Contact();
private List<EmailAddress> email_addresses = new List<EmailAddress>()
{
new EmailAddress{
EmailAddr = "",
Status = Status.Active,
ConfirmStatus = ConfirmStatus.NoConfirmationRequired
}
};
private List<ContactList> lists = new List<ContactList>()
{
new ContactList {Id = ""}
};
public ContactRequestBody() { }
public ContactRequestBody(string firstName, string lastName, string emailAddress, string listId)
{
this.contact.FirstName = firstName;
this.contact.LastName = lastName;
this.email_addresses[0].EmailAddr = emailAddress;
this.contact.EmailAddresses = this.email_addresses;
this.lists[0].Id = listId;
this.contact.Lists = this.lists;
}
}
An Example call from an aspx.cs page looks like this:
ConstantContactHelper requestHelper = new ConstantContactHelper("POST", "AddContact", firstName.Text, lastName.Text, emailBox.Text, listId);
requestHelper.TryRequest();
lbTest.Text = requestHelper.jsonRequest + ", status code:" + requestHelper.status_code + ", xml:" + requestHelper.responseXml;

values to dictionary c# .net

public class Response
{
public User[] Users { get; set; }
}
public class User
{
public string Uid { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
public int Online { get; set; }
public int[] Lists { get; set; }
}
private void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
lock (this)
{
string json = e.Result;
// var response = JsonConvert.DeserializeObject(json);
var response = JObject.Parse(json);
// var COUNT = JsonConvert.DeserializeObject<List<User>>(json);
// MessageBox.Show(response.ToString());
var getcount = response["response"].Children<JObject>();
int count_friends=getcount.Cast<JToken>().Values("uid").Count();
Response rr = new Response();
for (int i = 0; i <count_friends; i++) {
//rr.Users.ToDictionary(rr.Users[i].Uid => response["response"][i]["uid"].ToString());
// rr.Users[i].First_Name = response["response"][i]["first_name"].ToString(); --DOESN'T WORKS
// Debug.WriteLine("OUT: "+(string)response["response"][i]["uid"].ToString());
//Debug.WriteLine("OUT: " + COUNT.Count());
}
Debug.WriteLine(rr.Users.ToString());
// string[] names = rr.Users.Select(d => d.First_Name).ToArray();
// string[] uids = response.Users.Select(d => d.Uid).ToArray();
// Dictionary<string,string> users = response.Users.ToDictionary(d => d.First_Name);
// Dictionary<string, string> usersById = response.Users.ToDictionary(d => d.Uid, d => d.First_Name);
}
}
I need to get acces to a dictionary like "select from Response.User all where Online==1"
But in the start how I can create a DB(linq) with classes above ?
All values stored in response["response"][i]["uid"],response["response"][i]["first_name"]...
is this what your looking for?
Dictionary<string,List<Dictionary<string,object>>>
this is vary bad design, try and rethink the problem to come up with a better solution
public struct User {
public int Uid;
public string First_Name;
public string Last_Name;
public bool isonline;
}
Than you can write values like
User[] usr= new User[count_friends];
// Response rr = new Response();
for (int i = 0; i <count_friends; i++) {
usr[i].Uid =(int) response["response"][i]["uid"];

Categories