name-value-pair string to Json - asp.net

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.

Related

How to use tempdata to return error message

I am trying to use temp data to return messages but it gives an error :
InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type
I am already using
services.AddMvc().AddSessionStateTempDataProvider();
app.UseSession()
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
Here is my shared
FlashMessages.cshtml :
#using EnduroMotors.ViewModels
#{
var errorMessages = TempData["_error_messages"] as List<FlashMessageModel>
?? new List<FlashMessageModel>();
var warningMessages = TempData["_warning_messages"] as
List<FlashMessageModel> ?? new List<FlashMessageModel>();
var successMessages = TempData["_success_messages"] as
List<FlashMessageModel> ?? new List<FlashMessageModel>();
var infoMessages = TempData["_info_messages"] as List<FlashMessageModel> ??
new List<FlashMessageModel>();
}
Here is my viewmodel :
FlashMessageModel
public class FlashMessageModel
{
public string Title { get; set; }
public string Message { get; set; }
}
And here is use in controller :
Controller
protected void ShowSuccessMessage(string message, string title =
"Success!")
{
var messages =
(List<FlashMessageModel>)TempData["_success_messages"] ?? new
List<FlashMessageModel>();
messages.Add(new FlashMessageModel
{
Title = title,
Message = message
});
TempData["_success_messages"] = messages;
}
using this with return
ShowSuccessMessage("You have completed.");
it should show success message in index with #{Html.RenderPartial("FlashMessages");} but instead it gives
InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type 'EnduroMotors.ViewModels.FlashMessageModel'.
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer.EnsureObjectCanBeSerialized(object item)
TempData serialises objects to strings for storage. It supports string, int and boolean types natively. If you want to store more complex types, you have to serialise (and deserialise) them yourself. JSON is the recommended format. The following extension methods use the JSON.NET JsonConvert static methods to do this:
public static class TempDataExtensions
{
public static void Set<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
tempData[key] = JsonConvert.SerializeObject(value);
}
public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
tempData.TryGetValue(key, out object o);
return o ?? JsonConvert.DeserializeObject<T>((string)o);
}
}
You can read more about this here: https://www.learnrazorpages.com/razor-pages/tempdata#limitations

How do I create a dynamic Linq query to fill an ASP.NET databound ListView?

I am having some trouble figuring out the right way to go about creating a dynamic query that I can use values from DropDownList controls to filter and sort/order the results of a database query to fill a ListView. I am able to hard code individual queries, which works ok, except for the fact that it takes an incredible amount of effort, and is not easily changed.
My code is as follows (using all filters):
queryResult = From product In myEntities.InventoryProducts
Where product.VendorID = ddlFilterVendor.SelectedValue And product.ItemType = ddlItemType.SelectedValue And product.LabelSize = ddlLabelSize.SelectedValue And product.PrintLabel = boolPrint And product.Edited = boolEdited
Order By product.ID Ascending
Select product
Return queryResult
Is there a better method to this? I would like to be able to select the value from each DropDownList and generate a custom WHERE clause, as well as an ORDER BY clause.
Any help would be greatly appreciated, thanks.
I can give you a simple example as to how to to proceed with your idea. I am sure if you look through StackOverflow or search via google you will get code that does a better job of dynamic expression building. The same concept can be used for order by.
void Main()
{
var ops = new List<Ops>
{
new Ops
{
OperandType = typeof(string),
OpType=OpType.Equals,
OperandName = "Name",
ValueToCompare = "MM" // in your case this will be the values from the dropdowns
},
new Ops
{
OperandType = typeof(int),
OpType=OpType.Equals,
OperandName = "ID",
ValueToCompare = 1
},
};
var testClasses = new List<TestClass>
{
new TestClass { ID =1, Name = "MM", Date = new DateTime(2014,12,1)},
new TestClass { ID =2, Name = "BB", Date = new DateTime(2014,12,2)}
};
// this will produce prop => ((prop.Name == "MM") And (prop.ID == 1))
var whereDelegate = ExpressionBuilder.BuildExpressions<TestClass>(ops);
foreach(var item in testClasses.Where(whereDelegate))
{
Console.WriteLine("ID " +item.ID);
Console.WriteLine("Name " +item.Name);
Console.WriteLine("Date" + item.Date);
}
}
// Define other methods and classes here
public enum OpType
{
Equals
}
public class Ops
{
public Type OperandType {get; set;}
public OpType OpType {get; set;}
public string OperandName {get;set;}
public object ValueToCompare {get;set;}
}
public class TestClass
{
public int ID {get;set;}
public string Name {get; set;}
public DateTime Date {get;set;}
}
public class ExpressionBuilder
{
public static Func<T,bool> BuildExpressions<T>( List<Ops> opList)
{
Expression currentExpression= null;
var parameterExpression = Expression.Parameter(typeof(T), "prop");
for(int i =0; i< opList.Count; i++)
{
var op = opList[i];
Expression innerExpression = null;
switch(op.OpType)
{
case OpType.Equals :
{
var propertyExpression = Expression.Property(parameterExpression ,
op.OperandName);
var constExpression = Expression.Constant(op.ValueToCompare);
innerExpression = Expression.Equal(propertyExpression,
constExpression);
break;
}
}
if (i >0)
{
currentExpression = Expression.And(currentExpression, innerExpression);
}
else
{
currentExpression = innerExpression;
}
}
var lambdaExpression = Expression.Lambda<Func<T,bool>>(currentExpression,
new []{parameterExpression });
Console.WriteLine(lambdaExpression);
return lambdaExpression.Compile() ;
}
}

Save and Restore an object to database

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.

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';
}

why is my query not returning 6 items?

Afternoon,
Can any one see why my query is not returning a random 6 items please?
public class GetQuestions
{
public int qId { get; set; }
public string question { get; set; }
public string answer1 { get; set; }
public string answer2 { get; set; }
public string answer3 { get; set; }
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<GetQuestions> Questions()
{
using (QuizDataContext dc = new QuizDataContext())
{
var query = from q in dc.tblquizs
orderby Guid.NewGuid()
select new GetQuestions
{
qId = q.id,
question = q.q,
answer1 = q.a1,
answer2 = q.a2,
answer3 = q.a3,
};
return query.Take(6).ToList();
}
Updated Add the GetQuestions Class
You can't get random order by using
orderby Guid.NewGuid()
You can test this by doing the following query and seeing the result:
from q in dc.tblquizs
select Guid.NewGuid()
Entity Framework 4.3.1 will translate the Guid.NewGuid() call to newid() - this would definitely be the preferred methodology if your DAL supports it. It may be, however, that whatever DAL you're using doesn't translate the call properly (in which case it may get translated to a GUID before it's sent to the database server, resulting in a static value for ordering). You should use a database profiler to see what your DAL is doing.
If the Guid.NewGuid call is not translating to newid() properly, you have two other options:
Use a sproc
Use something like the LINQ below (as a last resort)
var context = new ScratchContext();
var products = new List<Product>();
for (int i = 0; i < num; i++)
{
Product product = null;
while (product == null)
{
int randomId = r.Next(context.Products.Count());
product = context.Products.FirstOrDefault(p => p.ID == randomId);
}
products.Add(product);
}
return products.AsQueryable();
I used the following code to resolve this issue.
var qry = from q in dc.tblwhiskysprintquizs.AsEnumerable()
orderby Guid.NewGuid()
select new GetQuestions
{
qId = q.id,
question = q.q,
answer1 = q.a1,
answer2 = q.a2,
answer3 = q.a3,
};
return qry.Take(6).ToList();
It was as simple as adding .AsEnumerable to the look up.
orderby Guid.NewGuid()
generates random numbers that may not exist in your db

Resources