How to log results to console with MongoDB 3.0 c# driver - c#

I am writing the simple c# console program to connect mongodb db instance and get the value from the mongodb and need to display console window. I am using mongodb version 3.0.
I am getting date but not able display console. I am getting struck with syntax.
Any one please help me, I have shared my sample code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Linq;
namespace MongoCHash
{
class Program
{
static void Main(string[] args)
{
var mongod = new MongoClient();
var db=mongod.GetDatabase("MyDB");
var movies = db.GetCollection<Movie>("movie");
}
}
public class Movie
{
public ObjectId Id { get; set; }
public string name { get; set; }
}
}

You have got a Movie object collection you need to iterate over the collection and the do a Console.Log() of what ever property of the movie object you want including date. If you want I can post an example.

Related

MemoryPack.MemoryPackSerializationException : <class> is not registered in this provider

I would like to test MemoryPack serializer, but obtain following exception on "MemoryPackSerializer.Serialize()" call.
Unhandled exception. MemoryPack.MemoryPackSerializationException: console_memorypack1.Person is not registered in this provider.
This is a basic .net6 console app :
Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MemoryPack;
namespace console_memorypack1
{
[MemoryPackable]
public partial class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
Program.cs
// See https://aka.ms/new-console-template for more information
using console_memorypack1;
using MemoryPack;
Console.WriteLine("Hello, World!");
var v = new Person { Age = 40, Name = "John" };
var bin = MemoryPackSerializer.Serialize(v);
var val = MemoryPackSerializer.Deserialize<Person>(bin);
Read doc and googled error without success.
I cannot see what is missing.
Many thanks
Update : Problem solved by using "MemoryPack" package and not "MemoryPack.Core"
Solution by package author

Parsing JSON data array in Unity from a web API using SimpleJSON

Hi thanks for taking time to look at my issue.
I am using SimpleJSON to parse a stream of data coming from https://api.thingspeak.com/channels/1327025/fields/1.json?results=1
specifically trying to get to "field1" which is inside "feeds".
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
using SimpleJSON;
using TMPro;
public class onLoad : MonoBehaviour
{
public TMP_Text temperatureData;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
using SimpleJSON;
using TMPro;
public class onLoad : MonoBehaviour
{
public TMP_Text temperatureData;
public void GetJsonData()
{
StartCoroutine(RequestWebService());
Debug.Log("test");
}
IEnumerator RequestWebService()
{
string jsonString = "https://api.thingspeak.com/channels/1327025/fields/1.json?results=1";
Debug.Log(jsonString);
using (UnityWebRequest webData = UnityWebRequest.Get(jsonString))
{
yield return webData.SendWebRequest();
if (webData.isNetworkError || webData.isHttpError)
{
print("---------------- ERROR ----------------");
print(webData.error);
}
else
{
if (webData.isDone)
{
JSONNode jsonData = JSON.Parse(System.Text.Encoding.UTF8.GetString(webData.downloadHandler.data));
if (jsonData == null)
{
print("---------------- NO DATA ----------------");
}
else
{
print("---------------- JSON DATA ----------------");
print("jsonData.Count:" + jsonData.Count);
temperatureData.text = jsonData["feeds\field1"];
Debug.Log(temperatureData.text);
}
}
}}}}
My code seems to work fine, as in I get the "jsonData.Count" to work (which comes up as 2). I am assuming that its reading the "channel" and "feeds". But it pops out as null.
How do I place the key and item inside jsonData to get to field1 ?
Thanks
The simple JSON basically works like a dictionary with single keywords ... you can't just pass a path to it.
What you want is
first accessing the feeds
it is an array so get an element .. probably the first one?
of that element finally access the field1
So something like
temperatureData.text = jsonData["feeds"][0]["field1"].Value;

Getting error in Asp.net core when implementing TodoList service

I'm following on some tutorial which creates TodoList and uses multiple layer structure to handle different business logic. When I copy code from the book it shows me an error when I fire dotnet run command in windows cmd. The error I get is displayed bellow so I can specify where lies the problem but don't know how to fix this. What can I do to make this work ? I'm using dotnet 3.0.100 version.
Services\FakeTodoItemService.cs(21,17): error CS0117: 'FakeTodoItemService' does
not contain a definition for 'Title' [C:\dotnetproject\AspNetCoreTodo\AspNetCor
eTodo\AspNetCoreTodo.csproj]Services\FakeTodoItemService.cs(22,17): error CS0117: 'FakeTodoItemService' doesn not contain a definition for 'DueAt' [C:\dotnetproject\AspNetCoreTodo\AspNetCor
eTodo\AspNetCoreTodo.csproj]
And here is a code which I think may be responsible for this error. Basically I have a service that implements interface which uses a model.
FakeTodoItemService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreTodo.Data;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public class FakeTodoItemService : ITodoItemService
{
public Task<TodoItem[]> GetIncompleteItemsAsync()
{
var item1 = new TodoItem
{
Title = "Learn ASP.NET Core",
DueAt = DateTimeOffset.Now.AddDays(1)
};
var item2 = new FakeTodoItemService
{
Title = "Build awesome apps",
DueAt = DateTimeOffset.Now.AddDays(2)
};
return Task.FromResult(new[] {item1, item2});
}
}
}
TodoItem.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace AspNetCoreTodo.Models
{
public class TodoItem
{
public Guid Id {get; set;}
public bool IsDone {get; set;}
[Required]
public string Title {get; set;}
public DateTimeOffset? DueAt {get; set;}
}
}
ITodoItemService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public interface ITodoItemService
{
Task<TodoItem[]> GetIncompleteItemsAsync();
}
}
In FakeTodoItemService.GetIncompleteItemsAsync you have this line var item2 = new FakeTodoItemService. FakeTodoItemService should be TodoItem.

How to read a json file stored online and change image to url when found

I am making an app in unity and i need the user to search for a keyword and it will return all the imageurls stored in an online json file that relate to that keyword (slug)
My colleague wrote me the below code, as she has way more knowledge with the language than me, but she doesnt use unity and i dont know if its suitable for unity or changing the texture of the image, as i cant seem to trigger it. The json file is currently stored in the project, but i would prefer it to read something that is online.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class UrlOpener : MonoBehaviour
{
public string imageaddress;
public void Open()
{
using (StreamReader r = new StreamReader("Assets/document.json"))
{
string json = r.ReadToEnd();
var img= JsonUtility.FromJson<ArtImage>(json);
imageaddress = img.imageurl;
}
}
}
[Serializable]
class ArtImage
{
public string name { get; set; }
public string imageurl { get; set; }
}
You can use WebClient to download content of remote file:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEngine;
public class UrlOpener : MonoBehaviour
{
public string imageaddress;
public void Open()
{
using (var client = new WebClient())
{
string json = client.DownloadString("http://www.example.com/some.json");
var img= JsonUtility.FromJson<ArtImage>(json);
imageaddress = img.imageurl;
}
}
}
Note that depending on .NET profile you are using, you may need to add assembly references for System.Net.WebClient.dll and System.Net.dll. You can find more details on how to add assembly references here.

I get an error in C# "The type or namespace name does not exist in namespace"

I get an error in C# "The type or namespace name does not exist in namespace". I checked everywhere but it didn't solve my problem here is the main program
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
class Program
{
static void Main(string[] args)
{
var startTime = DateTime.Now;
BlockChainMySelf.BlockChain StepCoin = new BlockChain();
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 10));
StepCoin.CreateTransaction(new Transaction("lkjsdf", "MaADLKHesh", 15));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 20));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 60));
StepCoin.ProcessPendingTransactions("Bill");
And here is the class that I want to call
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
public class BlockChain
{
IList<Transaction> PendingTransactions = new List<Transaction>();
public IList<Block> Chain { set; get; }
public int Difficulty { set; get; } = 2;
Here are the Screendhots
Main
Class
answerquestion
answerquestion2
The second screenshot in an earlier edit of your question clearly shows the BlockChain class as being 'Miscellaneous Files' in Visual Studio:
The MSDN page for the Miscellaneous Files Project says (emphasis mine):
When a user opens project items, the IDE assigns to the Miscellaneous Files project any items that are not members of any projects in a solution.
Presumably you were in the middle of trying to fix the issue, so you put static in - but that won't work because then you can't create an instance of a BlockChain.
Your question is a duplicate of Visual Studio - project shows up as “Miscellaneous Files”.
The/a solution is to right-click on the bad file in Solution Explorer, remove it from the project, then re-add it, e.g. this answer.
I had this issue... however, I had two classes under the same namespace but in different projects. All I had to do to fix this was to add a reference to the project directly.

Categories

Resources