Save and Restore an object to database - asp.net

Lets say i have an object with this format:
public class ObjectClassSample
{
public string product { set; get; }
public string Description { set; get; }
public int Price { set; get; }
}
Im trying to same this object inside a string field in a record in my database. is it possible to this without converting this to JSON, as i was thinking what is the best way to save and restore this.

One way or another you have to convert that object to a string, I'm unsure why you don't want to use JSON, but to do it without converting to JSON, you could make your own error prone format.
Here is an example of just converting the object to a string, separating each property by a comma.
Some Extension Methods
public static class ObjectSampleExtensions
{
public static ObjectClassSample ToObjectClassSample(this string s)
{
var parts = s.Split(new [] { ','});
return new ObjectClassSample
{
product = parts[0],
Description = parts[1],
Price = int.Parse(parts[2])
};
}
public static string ConvertToString(this ObjectClassSample objectToConvertToString)
{
const string delimiter = ",";
var sb = new StringBuilder();
sb.Append(objectToConvertToString.product);
sb.Append(delimiter);
sb.Append(objectToConvertToString.Description);
sb.Append(delimiter);
sb.Append(objectToConvertToString.Price);
return sb.ToString();
}
}
Then Usage
void Main()
{
var obj = new ObjectClassSample
{
Description = "this is the description",
Price = 3,
product = "my product"
};
var s = obj.ConvertToString();
//you can now save s to the database
Db.Save(s);
//later on pretend you read 's' back from the database
s = Db.ReadAnItem();
var objectFromDb = s.ToObjectClassSample();
}
So yeah, you can serialize the data anyway you want, but I would use a common format: json, xml, csv, whatever.
I wouldn't recommend using the code above, that was just an example to show you can basically do whatever you want to convert it to a string, so long as you can convert it back. Using a json parser would be much easier though.
An example with ServiceStack.Text would look like this
var objToSerialize = new ObjectClassSample(); //fill this with data
string myObjectAsString = objToSerialize.ToJson();
//reading it back from the database
ObjectClassSample myObj = myObjectAsString.FromJson<ObjectClassSample>();
I'm sure newstonsoft.json is similar.
As you can see...much prettier.

Related

Xamarin forms: How to parse local JSON data file stored in the project?

I have a local JSON file. I need to parse data from that file and need a list with date,color and message details.
Data format in JSON file:
{"01-01-2017":{"color":"white","message":"The Octave Day of Christmas Solemnity of the Blessed Virgin Mary, the Mother of God Lectionary: 18"},"02-01-2017":{"color":"white","message":"Memorial of Saints Basil the Great and Gregory Nazianzen, Bishops and Doctors of the Church Lectionary: 205",.......}}
Model Class
public class JsonContent
{
public string date { get; set; }
public string color { get; set; }
public string message { get; set; }
}
I tried the below code:
string jsonString;
string jsonFileName = "Files.prayers.json";
var assembly = typeof(HomePage1).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new System.IO.StreamReader(stream))
{
jsonString = reader.ReadToEnd();
}
List <JsonContent> newList = new List<JsonContent>();
//I need to add all the items into the above list
How can I get the list with date,color and message details? After this I need to show the dates with color on a XamForms.Enhanced.Calendar. I know how to show special dates in calendar, but stuck on this data parsing.
docs
I'd try something like this
Dictionary<string, JsonContent> jsonData = JsonConvert.DeserializeObject<Dictionary<string, JsonContent>>(jsonString);
foreach (var item in jsonData)
{
Debug.WriteLine("Date:>>" + item.Key);
Debug.WriteLine("color:>>" + item.Value.color);
Debug.WriteLine("message:>>" + item.Value.message);
}

How to add data to associative table in asp.net core

I am new to asp.net core. I am building a web application for book management. I have a table called Author and books. Being a many to many relationships I made an associative entity that consists of the bookId and authorId. When I try to create I am able to create author and book. I successfully added the author and book to the database.
My author class looks like this
public class Author
{
private int _ID
private string _Name;
public string ID {
get { return _ID; }
set { _ID = value; }
public string Name {
get { return _Name; }
set { _Name = value; }
}
My book class is
public class Author
{
private int _ID
private string _Name;
private string _Title;
public string ID {
get { return _ID; }
set { _ID = value; }
}
public string Title {
get { return _Name; }
set { _Name = value; }
}
public string Name {
get { return _Name; }
set { _Name = value; }
}
I have a data access called db.cs to help to create the book and author in database.
public static int AddAuthor(Author A)
{
int renum = -1;
SqlConnection conn = null;
conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand comm = new SqlCommand("sproc_AuthorAdd", conn);
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#Name", A.Name);
comm.Parameters.AddWithValue("#Title", a.Title);
SqlParameter output = new SqlParameter();
output.ParameterName = "#AuthorID";
output.DbType = System.Data.DbType.Int32;
output.Direction = System.Data.ParameterDirection.Output;
comm.Parameters.Add(output);
int affect = comm.ExecuteNonQuery();
renum = affect;
c.ID = (int)output.Value;
I have done the same for books as well. I want to fill out the association table as well when the user filled out a book and author using their ID. I tried to do various things like using a cookie to pass data. But I cannot store data. Any kind of help is appreciated. Thanks in advance.
I'm not really sure I understand your last code snippet, but if you're having issues managing your many-to-many relationship between Books and Authors, have you considered just using Entity Framework Core?
Instead of writing a bunch of code that accesses your database, you just create models of your tables (similar to the classes you have defined above), and it handles the many-to-many relationship for you. The code to query for Authors and/or Books could then look as simple as:
using (var db = new dbContext())
{
var books = db.Books
.Where(b => b.ID > 1234)
.OrderBy(b => b.Title)
.ToList();
}
And creating a new Book or Author would be similarly simple:
using (var db = new dbContext())
{
var book = new Book { ID = 1234, Title = "Some Title", Name = "Some Name" };
db.Books.Add(book);
db.SaveChanges();
}
You might have to reimplement a bunch of things to take advantage of Entity Framework Core in your app, but it sounds like it would save you time in the long run.

How to dynamically use getters/setters in Dart

class User{
String firstName;
String lastName;
String email;
}
I want to be able to get and set one of the fields in user with a dynamically selected symbol or string. For example String value = u[new Symbol("firstName")];
I see that InstanceMirror has a getField method, but it doesn't seem to return the value. All I need is the value.
If you create a symbol with # you need to know the name at compile time.
I got it working this way:
library operator_lib;
import 'dart:mirrors';
void main(List<String> args) {
var x = new X();
var f = new Symbol('firstName');
var r = reflect(x);
print(r.getField(f).reflectee);
r.setField(f, "John");
print(r.getField(f).reflectee);
}
class X {
String firstName = 'Mike';
}

Load ProfileBase without HTTP Context

I'm in the process of converting user profile data that was serialized in the classic ASP.Net Membership Provider for use in SimpleMembership. I cannot figure out how to get the ProfileBase object for every user in the system.
If a specific user is logged in, I can do something like:
MyModel myModel =
(MyModel)HttpContext.Current.Profile.GetPropertyValue("MyKey");
where MyKey refers to a profile key established in web.config like this:
<add name="MyModel" type="MyNS.MyModel" serializeAs="Binary" />
However, without the benefit of an HTTP context (I'm trying to do this for all users in the system, not a logged-in user) I can't figure out how to load the profile and ultimately an instance of MyModel for each user in the system.
I have tried:
ProfileInfoCollection profiles =
ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
foreach (var profile in profiles)
{
var pi = (ProfileBase)profile;
// OOPS! Unfortunately GetAllProfiles returns
// ProfileInfo and not ProfileCommon or ProfileBase
}
and
MembershipUserCollection existingUsers = Membership.GetAllUsers();
foreach (MembershipUser mu in existingUsers)
{
mu. // OOPS! No link to the profile from the user...
}
How can I retrieve the ProfileCommon or ProfileBase instance for each profile in the system, and thus ultimately the MyModel associated with each user?
Since I could not find an answer to this question, I opted to just read the profile data directly from SQL.
It turns out that the format is straightforward. In aspnet_Profile:
PropertyNames uses a format NameOfProperty:TypeFlag:Offset:Length (repeat for all properties).
FlagType is "S" for string or "B" for binary
Offset is the offset in the appropriate data field
Length is the length of data in the appropriate data field
PropertyValuesString holds all string properties concatenated without a delimiter.
PropertyValuesBinary holds all binary properties concatenated without a delimiter.
BinaryFormatter is used to serialize binary (non-string) properties
Here's a little code I wrote to parse the data:
private class Migrate_PropNames
{
public string Name { get; set; }
public bool IsString { get; set; }
public int Offset { get; set; }
public int Length { get; set; }
}
....
Dictionary<string, Migrate_PropNames> propInfo = ParsePropInfo(propertyNames);
// Example string property
string firstName = Migrate_GetString(propInfo["FirstName"], propertyValuesString);
// Example binary property
MyType myType =
Migrate_GetBinary<MyType>(propInfo["MyTypeKey"], propertyValuesBinary));
private T Migrate_GetBinary<T>(Migrate_PropNames propNames, byte[] propertyValuesBinary)
{
byte[] data = new byte[propNames.Length];
Array.Copy(propertyValuesBinary, propNames.Offset, data, 0, propNames.Length);
var fmt = new BinaryFormatter();
using (var ms = new MemoryStream(data))
{
T original = (T)fmt.Deserialize(ms);
return original;
}
}
private string Migrate_GetString(Migrate_PropNames propNames, string propertyNames)
{
return propertyNames.Substring(propNames.Offset, propNames.Length);
}
private Dictionary<string, Migrate_PropNames> ParsePropInfo(string propertyNames)
{
Dictionary<string, Migrate_PropNames> result = new Dictionary<string,Migrate_PropNames>();
string[] parts = propertyNames.Split(new string[] { ":"}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i += 4)
{
Migrate_PropNames pn = new Migrate_PropNames();
pn.Name = parts[i];
pn.IsString = (parts[i + 1] == "S");
pn.Offset = int.Parse(parts[i + 2]);
pn.Length = int.Parse(parts[i + 3]);
result.Add(pn.Name, pn);
}
return result;
}
I hope this helps someone. I'll gladly accept a different answer that correctly shows how to use the API.
From the ProfileInfo or MemberShipUser object, you should can get a ProfileBase one using ProfileBase.Create(string username).

name-value-pair string to Json

Trying to get an object out of str1=X&str2=Y using Newtonsoft.Json
Getting: "Unexpected character encountered while parsing value: s. Line 1, position 1."
Am i way off expecting this to work?
public class MyTest
{
public string str1 { get; set; }
public string str2 { get; set; }
}
public MyTest GetJson()
{
data = "str1=X&str2=Y";
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.MissingMemberHandling = MissingMemberHandling.Error;
jss.ObjectCreationHandling = ObjectCreationHandling.Reuse;
MyTest myTest = JsonConvert.DeserializeObject<MyTest>(data, jss);
}
Yes, you're way off. json looks more like this:
{"str1":"x","str2":"y"}
See www.json.org for more information.
Edit
To convert a query string to json:
var queryString = "str1=X&str2=Y";
var queryParams = HttpUtility.ParseQueryString(queryString);
var jsonObject = new JObject(from k in queryParams.AllKeys
select new JProperty(k, queryParams[k]));
To convert a json string to an object:
MyTest test = JsonConvert.DeserializeObject<MyTest>(jsonObject.ToString());
To convert an object to json:
var test = JsonConvert.SerializeObject( new MyTest{str1 = "X", str2 = "Y"});
That's a query string, not a JSON string.
You can parse it using HttpUtility.ParseQueryString, which returns a NameValueCollection.

Resources