I've searched alot but I can't find a solution for my problem:
I'm writing an Windows 8.1 App and I've a Class, which I want to Serialize, because I want to store the Data from this Class.
But I can't access the File-Class, Visual Studio still cannot recognize File as a class name.
Here's my Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Windows.Storage;
namespace Password.Data
{
class DataContainer
{
SortedDictionary<int, PasswordBox> Data { get; set; }
public int Key { get; set; }
public void Save(DataContainer a, string filename)
{
XmlSerializer ser = new XmlSerializer(typeof(DataContainer));
using (Stream s = File.OpenWrite(filename))
{
ser.Serialize(s, a);
}
}
}
}
How can I use the File-Class in this case? Or are there new Classes in order to tell my Stream that he has to write the data to file xy.
Or are there other ways to save a Dictionary?
Related
I'm implementing various classes in a common folder and namespace all of which need to be able to deserialize JSON, so all the classes need the
using using System.Globalization;
using System.Text.Json.Serialization;
directives. I was wondering if there is a way to make them all use said libraries rather than pasting it into every new class .cs file or writing all the classes in the same .cs file. I've tried putting the using directives inside the namespace but it doesn't carry over to the other .cs files. It might be worth mentioning I'm working on a wpf C# .net framework desktop application.
Sample class without the using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MLaRealERP.Models
{
internal class ClienteP
{
[JsonPropertyName("dni")]
public string DNI { get; set; }
[JsonPropertyName("ruc")]
public string RUC { get; set; }
[JsonPropertyName("nombres")]
public string Nombres { get; set; }
[JsonPropertyName("apellidos")]
public string Apellidos { get; set; }
[JsonPropertyName("celular")]
public string Celular { get; set; }
}
If you're using C# 10 you can use the global modifier on the using directive but this is equivalent to adding it to every file in the project. See the docs here.
If you're on an earlier version, short answer is no.
I have begun writing an ASP.NET Web API for an app that I am building. I have set up a MongoCRUD.cs class to save data from POST requests made by the app to a MongoDB database (and other CRUD actions).
I (following a beginner tutorial), also set up a Submission.cs model class to act as a blueprint for the objects I wanted to save to the database. However, now that I have implemented the InsertRecord() method in MongoCRUD.cs, I cannot see a use for this model.
MongoCRUD.cs:
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPI.Services
{
public class MongoCRUD
{
private IMongoDatabase db;
public MongoCRUD(string database)
{
var client = new MongoClient();
db = client.GetDatabase(database);
}
public void InsertRecord<T>(string table, T record)
{
var collection = db.GetCollection<T>(table);
collection.InsertOne(record);
}
}
}
Submission.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Web;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace WebAPI.Models
{
public class Submission
{
[BsonId]
public string SubId { get; set; }
public string Url { get; set; }
public string Text { get; set; }
}
}
SubmissionsController.cs:
using WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Services;
using System.IO;
using System.Web.Script.Serialization;
namespace WebAPI.Controllers
{
public class SubmissionsController : ApiController
{
MongoCRUD db = new MongoCRUD("myDb");
Submission[] submission = new Submission[] {
new Submission { SubId = "test", Url = "test", Text = "test" };
};
public IEnumerable<Submission> GetAllSubmissions()
{
//add MongoCRUD functionality for load record
return submission;
}
public IHttpActionResult GetSubmission(string id)
{
//add MongoCRUD functionality for load record
return Ok();
}
public IHttpActionResult PostSubmission(object body)
{
//validate body
db.InsertRecord("Submissions", body);
return Ok();
}
}
}
As you can see at PostSubmission(), the body of the POST request can be saved to the database directly, so my question is what is the benefit of using a model such as Submission.cs instead of just using the object type?
I'm having some trouble traversing the body object to access its values (for carrying out validation etc), so my only guess is that using a model makes it easier to access values?
object is the base type for all classes (See - https://learn.microsoft.com/en-us/dotnet/api/system.object?view=netcore-3.1).
C# is an object-orientated language so we try to model classes based on our business domain, this makes it easier to reason about the code.
Like you said you can have models that can be used to validate the incoming data into the controller, also you might want to add extra methods on the models that related to your business domain.
For example
class CreditCard
{
string CardNumber { get;set; }
string Csv { get;set; }
bool ValidateChecksum()
{ }
}
HI I have following entity class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace myspace
{
class aList
{
public int Id { get; set; }
[Index("atIdIndex", IsUnique=true)]
public int atId { get; set; }
public string description { get; set; }
}
}
In visual studio on [Index("atIdIndex", IsUnique=true)] I get red line under Index and it says that
Type or namespace Index couldnot be found.
Please let me know how i can fix it Thanks
'
You need to add:
using System.ComponentModel.DataAnnotations.Schema;
Had to re install EF it worked fine after that. Thanks
I'm very new to working with TFS(of course not with Visual Studio). I have 6 projects in same solution and one of the projects has a folder with 6 c-sharp classes in it. When i try to access these classes from inside of other projects ( which all are in the same solution) except one class other five classes don't appear in the intellisense.
I have manually added reference to this project in other project. Which is why I'm able to access one class but my confusion is why not other classes are accessible through intellisense.
Did I do something wrong. I did check-in whatever pending changes were there in the entire solution still no luck.
Your help will be highly appreciated
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NS.GIS.PTC.Core.Entities;
namespace NS.GIS.PTC.WebServices.DataManagement.Model.Dtos
{
public class FieldDescriptionDto
{
public string Name
{
get;
set;
}
public string Type
{
get;
set;
}
public string Alias
{
get;
set;
}
public int Length
{
get;
set;
}
public bool IsSystem
{
get;
set;
}
public Domain Domain
{
get;
set;
}
}
}
here is the code and below is the code that is using it I have written it forcibly coz as u know its not appearing in intellisense
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NS.GIS.PTC.Core.Entities;
using NS.GIS.PTC.WebService.DataManagement.Model.Dtos;
namespace NS.GIS.PTC.WebService.DataManagement.API.Model
{
internal static class FieldDescriptionExtension
{
internal static FieldDescriptionDto ToFieldDescriptionDto(this FieldDescription fieldDescription)
{
return new FieldDescriptionDto
{
Name = fieldDescription.Name,
Type = fieldDescription.Type,
Alias= fieldDescription.Alias,
};
}
}
}
Please check if all the classes are marked Public.
Check if their namespaces have been included.
Restart VS and try.
Forcibly use them and see if you get a squiggle to auto-include namespace etc.
Where do I start?
in my current solution I have models like this:
public class MyAwesomeModel
{
....
}
I want to take the roslyn code project to parse the source files and go over the syntax trees to generate new code files. Take those source files and add them to a c# project file to import in my solution again in visual studio.
Where do I start. Cloning roslyn and just write a console app that reference all of roslyn and start digging into roslyn to find out how, or is there any blogs,documentatino that shows something like this.
It was somewhat easy to do.
Create a console app and add reference to Microsoft.CodeAnalysis.CSharp in your project.
Here is the program that visited all properties in a source text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
class ModelCollector : CSharpSyntaxWalker
{
public Dictionary<string, List<string>> Models { get; } = new Dictionary<string, List<string>>();
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node)
{
var classnode = node.Parent as ClassDeclarationSyntax;
if (!Models.ContainsKey(classnode.Identifier.ValueText))
{
Models.Add(classnode.Identifier.ValueText, new List<string>());
}
Models[classnode.Identifier.ValueText].Add(node.Identifier.ValueText);
}
}
class Program
{
static void Main()
{
var code = #"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
public class MyAwesomeModel
{
public string MyProperty {get;set;}
public int MyProperty1 {get;set;}
}
}";
var tree = CSharpSyntaxTree.ParseText(code);
var root = (CompilationUnitSyntax)tree.GetRoot();
var modelCollector = new ModelCollector();
modelCollector.Visit(root);
Console.WriteLine(JsonSerializer.Serialize(modelCollector.Models));
}
}