I have this code , and i want to store values of parameters left, top in static dictionary. and after storing this values i want to access them in Jquery.Thanks For your Help.
my code
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.MoveShape
{
public class MoveShapeHub : Hub
{
public void calculate(string left, string top)
{
Clients.Others.updateshape(left, top);
}
}
}
jQuery operates client-side, so you can't talk to it directly. You have two options, then:
request the value via http (perhaps using SignalR as a messaging layer, since you are referencing that)
serialize the dictionary as JSON into the request
Fortunately, the latter is fairly trivial for most common types - here using Json.NET:
var data = new Dictionary<string, object>
{
{"foo", 123},
{"bar", "abc"},
{"blap", true}
};
var json = JsonConvert.SerializeObject(data);
which gives us the JSON:
{"foo":123,"bar":"abc","blap":true}
If you assign that into a variable in the <script>, then values can be referenced either as obj.bar or as obj['bar']. However: keep in mind that all values will be serialized if you do this - you may want to be more restrictive in terms of tracking which the client actually cares about (or should be allowed to know about).
Important point, though: if your "static dictionary" is actually a static dictionary, then please consider very carefully the impact of multiple users. static is a really good way to write a web-site that only scales to a single user.
Related
I am trying to get around that C# prefers to have classes generated (I know they are easy to generate, but currently my format and parameters are changing a lot due to development in both client and server end).
Example of what I most often find when I try to find out to deserialize is that you first have to know the exact structure - then build a class - and then you can refer to it later on (it's fine, but it's just not what I would like to do):
Json format 1:
[{"FirstName":"Bob","LastName":"Johnson"},{"FirstName":"Dan","LastName":"Rather"}]
public class People
{
public string FirstName { get; set; }
public string LastName { get; set;}
}
public List<People> peopleList;
. . . // (same as first example)
//Change the deserialize code to type <List<Class>>
peopleList = deserial.Deserialize<List<People>>(response);
That of course is easy as long as the reply doesn't change format, if for example the reply changes to a nested field :
Json format 2:
[{"FirstName":"Bob","LastName":"Johnson"},{"data":{"nestedfield1"
:"ewr"} }]
I would of course have to change the class to represent that, but at the moment we are moving back and forth in formats and I would somehow like if there was a way where I could try to access json elements directly in the string?
For example, like I can do in Python:
mystring1 = reply ["firstName"] mystring2 = reply ["data"]["nestedfield1"]
Is there any way to achieve this in C#? It would speed up development rapidly if there was a way of accessing it without first referencing the output in the code to then once again reference the class variable that was created when referencing it.
And note it's for rapid development, not necessarily for the final implementation where I can see advantages by doing the class approach.
Another way of asking was maybe can it serialize taking any format (as long as its JSON) and dynamically build up a struct where I can access it with named keys and not as class variables?
to deserialize json without using classes you can use using Newtonsoft.Json
here's the code:
using System;
using Newtonsoft.Json;
using System.Text;
public class Program
{
public static void Main()
{
var myJSONString = "[{\"FirstName\":\"Bob\",\"LastName\":\"Johnson\"},{\"FirstName\":\"Dan\",\"LastName\":\"Rather\"}]";
dynamic obj = JsonConvert.DeserializeObject<dynamic>(myJSONString);
Console.WriteLine(obj[0].FirstName);
}
}
The obj will perform the same way you use when generating classes,
it can take any json string and deserialize into dynamic object regardless of structure of the json. Keep in mind that you won't get VS intellisense support.
UPDATE
Here's fiddle:
https://dotnetfiddle.net/xeLDpK
I'm looking for an answer in either C# or VB.net.
I'm getting a string like this:
{"1":{"pump":1,"name":"Pump 1","type":"VS","time":"2:10 PM","run":10,"mode":0,"drivestate":0,"watts":1656,"rpm":2850,"gpm":0,"ppc":0,"err":0,"timer":1,"duration":"durationnotset","currentrunning":{"mode":"off","value":0,"remainingduration":-1},"externalProgram":{"1":-1,"2":-1,"3":-1,"4":-1},"remotecontrol":1,"power":1,"friendlyName":"Pump 1"},"2":{"pump":2,"name":"Pump 2","type":"None","time":"timenotset","run":"runnotset","mode":"modenotset","drivestate":"drivestatenotset","watts":"wattsnotset","rpm":"rpmnotset","gpm":"gpmnotset","ppc":"ppcnotset","err":"errnotset","timer":"timernotset","duration":"durationnotset","currentrunning":{"mode":"off","value":0,"remainingduration":-1},"externalProgram":{"1":-1,"2":-1,"3":-1,"4":-1},"remotecontrol":"remotecontrolnotset","power":"powernotset","friendlyName":"Pump 2"}}
So, just two records. I just need to pull "name", "watts" and "rpm" from each. I don't need to store the entire record in an array or list as I'll just dispose of row anyway.
How can I do this?
You can use Newtonsoft.Json to do this, just find it in on Nuget.
You COULD use it like this, though it's a little dirty...
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText("TextFile1.txt");
JObject jsonObject= (JsonConvert.DeserializeObject(json) as JObject);
string name = jsonObject.Value<JObject>("1").Value<string>("name");
}
}
}
I tested it with your json string in the TextFile1, and it works well. You'd be better off making a custom type for it to deserialise into.
The key parts are the JsonConvert.DeserializeObject(json) which converts the json string into CLR objects, namely a JObject. Then there's the .Value<JObject>("1") bit, which is just using the newtonsoft api.
p.s. I notice you've got a json.net tag on there, their website pretty much says it: https://www.newtonsoft.com/json
I am using Roslyn to create an analyzer that warns users if a particular class exposes its fields in an unsynchronized manner, to help prevent race conditions.
The Problem:
I currently have working code that checks to make sure a field is private. I’m having trouble with the last piece of the puzzle: figuring out a way to make sure that all fields are only accessed inside a lock block, so they’re (ostensibly) synchronized.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FindSymbols;
namespace RaceConditions
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UnsynchronizedMemberAccess : DiagnosticAnalyzer
{
public const string DiagnosticId = "UnsynchronizedMemberAccess";
internal static readonly LocalizableString Title = "UnsynchronizedMemberAccess Title";
private static readonly LocalizableString MessageFormat = "Unsychronized fields are not thread-safe";
private static readonly LocalizableString Description = "Accessing fields without a get/set methods synchronized with each other and the constructor may lead to race conditions";
internal const string Category = "Race Conditions";
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
//meant to stop other classes and itself from accessing members in an unsychronized fashion.
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterSemanticModelAction((context) =>
{
var model = context.SemanticModel;
var root = model.SyntaxTree.GetRoot();
var nodes = model.SyntaxTree.GetRoot().DescendantNodes();
var fields = nodes.OfType<VariableDeclaratorSyntax>()
.Where(v => v.Ancestors().OfType<FieldDeclarationSyntax>().Any());
//since (it appears) that you can't read/write to a an initialized field,
//I think it means you can only read/write inside a block
foreach (BlockSyntax b in nodes.OfType<BlockSyntax>())
{
//where I plan to put code to check references to the fields
}
});
}
}
}
More specifically, I’d like to be able to ensure everything highlighted by the reference highlighter (at least that’s what Microsoft seems to call it) is inside a lock block, while overloaded parameters do not have to.
using System;
using System.Linq;
using System.Activities;
using System.Activities.Statements;
using System.Data.SqlClient;
namespace Sandbox
{
partial class Program
{
private int xe = 0, y = 0;
public Program(int xe)
{
this.xe = xe;
}
void bleh()
{
if (xe == 0)
{
xe = xe + 1;
}
}
static void Main(string[] args)
{
Program p0 = new Program(5),
p1 = new Program(p0),
p2 = new Program(p0.xe);
Console.WriteLine(p1.xe);
Console.Read();
}
}
partial class Program
{
public Program(Program p) : this(p.xe) { }
}
}
The Research:
Here, Josh Varty [1] suggests I use SymbolFinder.FindReferencesAsync, which requires a Solution object. Jason Malinowski [2] says that I shouldn’t use do this in an analyzer, since making a MSBuildWorkspace to get a Solution object is too slow, while this person [3] offers an incomplete/missing workaround to the slowness issue (the link to ReferenceResolver seems to be broken).
I have also looked into DataFlowAnalysis (SemanticModel.AnalyzeDataFlow()), but I can’t find any particular methods there that obviously let me guarantee that I’m referencing the field xe, and not the local variable xe.
The Question:
I do feel like there is something monumentally obvious I’m missing. Is there some elegant way to implement this that I’ve overlooked? It’d be preferable if the answer uses the semantic model, since I expect I have to use it in other analyzers to figure out where data/references come from, but I realize there are limitations, so any answers without the semantic model are also fine.
Notes:
Apparently, this issue was also encountered at Github [4], but apparently it’s still being tracked there, and they don’t know if the analyzer should analyze on the project level or not. It still hasn’t been resolved. For the purposes of this analyzer, I will assume that the entire class contained in a single .cs file. Small steps first, eh?
I also searched through John Koerner's website [5] and Josh Varty's website [6], and couldn’t find anything relevant to both analyzers and DataFlowAnalysis.
The trick is to invert how you're asking the question. Go from:
How do I find all the references to this symbol that I want to ensure is synchronized?
but instead
How, upon looking at the use of a symbol, determine if this should be inside of a lock statement?
Because this offers a course of action: your analyzer should instead look at each identifier in a method body that's not in a lock statement, call SemanticModel.GetSymbolInfo(), get the symbol that's being referenced, and then check if that field is one that's "synchronized" via your logic (private, etc.). At that point, then since you're looking at the use, you can flag that particular use.
This inversion is how we expect analyzers to be written, and it's not an accident. The reason is largely performance. Imagine your analyzer is running inside Visual Studio, and you delete a line of code. If analyzers were written in the model of "look at a symbol, now ask for all uses", it means any and all analyzers that did that potentially have to rerun from scratch. That's not great for your CPU or battery life. When the question is inverted like this, it means we only have to reanalyze that specific file, since you're not expanding to "give me everything".
I am using ASP.NET Web Forms/C#.I am having a page Customer.aspx.I have created CustomerBLL class in which I plan to use Linq To SQL queries to perform all database related tasks.
Consider this example.Here is a method called GetDateFormat() in my CustomerBLL class which returns Date format from database.Here is the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace CwizBankApp
{
public class CustomerBLL
{
public string GetDateFormat()
{
using (var db = new DataClasses1DataContext())
{
var format = db.CODEs.Where(code => code.NAME.Equals("dateformat")).SingleOrDefault();
return format.DRNAME;
}
}
}
}
From code behind I am calling this function inside of another function like this.
public void RetrieveDateFormat()
{
//In this function we retrieve the date format
//from the database to identify if it is british or american
var format = CustomerBLL.GetDateFormat();
//The global variable gDateFormat stores the format
if (format != null)
{
Global.DateFormat = format;
}
I am calling the function and storing the result first and then checking if it is null or not.Should I be doing this way or Should I check if it is null or not in the CustomerBLL.cs file itself?
What is better way to do this.Is my way of calling the function GetDateFormat() feasible.
Also is this approach of maintaining Linq queries in such class files and then calling them from code behind considered to be a good practice?
Can somebody tell me if I am heading in the right direction or not?
Any suggestions are welcome.
Your way of calling the function is ok. However, you should check for null within CustomerBLL.cs.
here are couple of good examples of how to use repository pastern with web-forms
http://msdn.microsoft.com/en-us/library/ff649690.aspx
http://forums.asp.net/t/1808905.aspx/1?Repository+Architecture+Using+WebForm+in+C+With+N+Tier+Architechure
http://code.google.com/p/nhibernate-repository-example/
http://www.expertbloggingon.net/post/2011/11/23/CSharp-Repository-Pattern-Design-Patterns-in-Action.aspx
One particular aspect of some code I've written is causing me minor headaches, I can't pinpoint the reason - all the type checking and casting is making me feel uneasy. The code works as it is right now. I'd like to know wether or not there's a better way to handle the type-specific aspects of the code.
I'm using a non-generified, object-returning JSON parser which makes me go through various incantations in my generified code.
The signature of the parse method is public static object JsonDecode(string json) The runtime type of the object it returns can be ArrayList, Hashtable, double or string. I'm calling the JsonDecode method on a Twitter Search response, which returns the result tweets as a top level object of the form:
{"results":[
{"text":"#twitterapi http:\/\/tinyurl.com\/ctrefg",
"to_user_id":396524,
"to_user":"TwitterAPI",
"from_user":"jkoum",
"metadata":
{
"result_type":"popular",
"recent_retweets": 109
}, ... MORE-DATA ...}
The context in which I'm using the JsonDecode(string json) method is
private IList<Tweet> searchResult = new List<Tweet>();
var jsonDecoded = JSON.JsonDecode(responseString);
IList rawTweets =
(IList)((Hashtable)jsonDecoded)["results"];
foreach (var rawTweet in rawTweets)
{
searchResult.Add(new Tweet((Hashtable) rawTweet));
}
The Tweet class does its own type checking and casting
class Tweet : DynamicObject
{
private IDictionary<string, string> stringValues =
new Dictionary<string, string>();
private IDictionary<string, double> numberValues =
new Dictionary<string, double>();
public Tweet(Hashtable rawTweet)
{
FlattenJSON(rawTweet);
}
//flatten input and assign to correct map/dictionary based on JSON value type
private void FlattenJSON(Hashtable table)
{
foreach (DictionaryEntry entry in table)
{
//this code is not handling the case, that the Tweet contains a JSON array
//not necessary as of now: this code is intended for demo purposes in a talk
//I'm giving on Friday 2010-06-25
if (entry.Value is String)
stringValues.Add((string)entry.Key, (string)entry.Value);
else if (entry.Value is Double)
numberValues.Add((string)entry.Key, (double)entry.Value);
else if (entry.Value is Hashtable)
FlattenJSON((Hashtable)entry.Value);
}
}
...
}
Am I handling the type checks in the FlattenJSON method correctly? What about the casts in the code snippet building the IList and constructing the searchResult IList<Tweet>? Would you have written the code in a different way?
As a side note, the complete code is available via http://github.com/codesurgeon/pop-tweets The code is intended for a demo in a talk that I'll be giving on selected .NET features. The Tweet class is a DynamicObject and it overrides TryGetMember, see full listing on github.
Thank you ;)
P.S.: [FYI] This is a more specific version of my previous post, requesting a general code review https://stackoverflow.com/questions/3113293/how-to-be-a-good-c-citizen-review-requested-for-c-4-0-dynamic-sample-code
A few things stand out to me:
First, you should so some argument validation. Check to see if "table" is null before you start using it. Otherwise, you will get an unhandled NullReferenceException and it will confuse your consumer.
Next, does this actually work? The "is" keyword (I thought) only worked with reference types, and double is a value type. I would assume that this wouldn't work and you'd need to instead do a double.TryParse().
Lastly, there is a lot of casting on-the-fly. When you are interacting with a 3rd-party API, I would argue that you should have an interface where you convert from "their weird stuff" to "your clean stuff". So even if the API is messy and difficult, clean it up and present it to your consumer in the proper way. Don't propogate the bad design. In other words, as a consuming developer, I would want some obvious and clean data structures to work with. Like: foreach(Tweet tweet in Twitter.GetTweets()) or something. I don't care that you happen to use json right now. That implementation should be be invisible to me.
Hope that helps...
I would not do it like that.
First of all, your tweet class is not a real object, it's a data container. You could just continue to work with the jsonDecoded variable, since your tweet class doesn't add any functionality or abstraction (other than abstracting away the JSON decoder).
How I would do it:
Create POCOs which holds the information: Tweet and a Metadata class.
Create a serializer which takes the JSON string and returns the Tweet class
By dividing it into two steps and also creating real classes you will have it much easier in the future. Please read about Single Responsibility.