C# check data in json file - c#

I'm writing a plugin for a game server modification.
Basically the plugin revokes the item dropping right from players if they don't have the bypass permission.
This worked but when a player removes an already placed object from the world, the plugin shows the error message and gets in a loop giving the player the same item said player removed. ( I guess it need a break; but I'm not sure)
I tried to extend the plugin by adding excluded items. The plugin would check if the item ID the player tries to drop is listed in a .json config file. If it is, then said player drops the item. If not listed, then the item gets deleted, except if the player has the bypass permission.
The difficulty I'm have is that I don't know how to check the item IDs listed in the .json file.
Another alternative is to leave the .json file and put the allowed item IDs inside the code, but I have no idea how to do this either.
I know this is very basic and easy, but just started with c#. I'm reading one of my teacher's book about basic C#, but I would like to finish this project soon.
http://pastebin.com/RgBmtus9
Thanks in advance guys

The linked code fragment doesn't seem to be complete or to compile standalone. Reading through, your code to serialize and deserialize your Config class looks valid, though I can't actually compile and test your DropBan class.
So, is this what you want?
public class DropBan : TerrariaPlugin
{
private Config config;
bool IsExcluded(int id)
{
if (config == null)
{
ReadConfig();
}
return config != null && config.Exclusions != null && config.Exclusions.Contains(id);
}
public class Config
{
public int[] Exclusions = { 267, 188 };
}
// Rest as as shown at http://pastebin.com/RgBmtus9
}

Related

Why does any reference to Server.MapPath() kill my HttpContext Request.Params[]?

I am very much a novice in HttpHandlers. This is actually my first attempt at it.
I have this Ajax handler that responds to a jQuery ajax call in my web app front end:
public class ajaxMeetingHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
string resultsJSON = "";
string requestType = context.Request.Params["requestType"];
if (!String.IsNullOrEmpty(requestType)) {
switch (requestType) {
case "RecentMXMeetings":
resultsJSON = SerialiseRecentMeetings(context, "Maintenance");
// SerialiseRecentMeetings() is a method in the class
// that works fine and is not included for brevity.
break;
// more cases (not included for brevity)
}
}
public bool IsReusable {
get {
return false;
}
}
}
}
And this works perfectly.
However, if I add either of these two statements anywhere in the code:
var x = context.Server.MapPath("/");
var y = HttpContext.Current.Server.MapPath("/");
...my Context.Request.Params[] collection becomes null, and IsNullOrEmpty(requestType) now sees requestType as null. In fact, ALL the Request.Params[] are null.
If I comment out those statements (and completely rebuild the solution) the thing goes back to working properly.
In the meantime, I am going to move the calls to MapPath() out to a static "RunTimeEnvironment" class so I can get the path I need from there without touching MapPath() from inside this HttpHandler. Is that a viable or recommended solution?
It turns out my problem was not related to the code itself, per se, but how I was running the project.
Visual Studio, when you click on the "Start Debug" button will start the solution at it's root document (ie, index.html). That is UNLESS the current open document is of a runnable type, such as .html. If your current open window is one of your class files (ie, .cs), it will not attempt to run the class file, but will start the debug session at your root document.
However, it WILL attempt to run a Generic Handler (.ashx) all by itself if that is the document you currently have open. And, by doing so, it was not starting at the index.html page which issues my ajax calls and sends parameters to the Handler. So, my Params collection was null because it was literally null. Running the .ashx by itself supplies no parameters.
So, the reason it worked after changing my call type from GET to POST and Back to GET again is because in doing so, I opened the index.html file to make that change, and when I started my debug session again, my current document was the index.html file, not the Generic Handler .ashx file.
I should probably lose a hundred reputations points just for making this dumb of a mistake. But in case it helps others, there it is.

Parse.com Android Unity Nothing works not even the test object

I have just started using Parse.com On Unity 5.0.0fb, and after getting my application to work with Parse on Unity Editor I decided to try it on my Mobile to find nothing works. I have checked the APK and Parse is inside it but when I try anything it does not work.
I have tested this with a Test APK with nothing but parse and the test script attached to a button and it also does not work.
using UnityEngine;
using System.Collections;
using Parse;
public class ScriptTest : MonoBehaviour {
public UnityEngine.UI.Text Mytext;
string mytext;
// Use this for initialization
public void MySpecial () {
ParseObject testObject = new ParseObject("TestObject");
testObject["foo"] = "bar";
testObject.SaveAsync();
mytext = "Saved";
Mytext.text = mytext;
Debug.Log (mytext);
}
// Update is called once per frame
void Update () {
}
}
It will not do anything the button will click it will say saved on my text but when I check parse TestObject nothing will be there. Is there something im missing in my build?
I have made sure stripping is also disabled.
This works 100% in editor just not in Android I have no idea or way to test iOS.
I have the exact same problem, using Unity 5.1 and Parse Unity SDK 1.5.1. It works perfectly in the editor but not on Android.
Here's my code :
ParseObject _localPlayer = new ParseObject();
Task query = _localPlayer.SaveAsync();
while (!query.IsCompleted)
yield return null;
if (!query.IsFaulted && !query.IsCanceled)
{
Debug.Log ("Player successfully created!");
}
else
{
Debug.Log("Failed to create player...");
}
The task generated with the SaveAsync() request doesn't seem to end at all (isCompleted is never true) so it becomes an infinite loop, and the actual cloud operation is not performed (no trace on the Parse dashboard). There doesn't seem to be any exception thrown and the device log doesn't show anything.
I'm really stuck at this point and haven't be able to find any solution anywhere on the web so far. :(
Using Parse SDK 1.3.2 "fixes" the issue.
-> https://parse.com/downloads/windows/Parse/1.3.2
Looks like a big fat regression. ;)
Going back to Parse Unity SDK 1.3.2 worked for me.
LogOutAsync() had to be replaced with LogOut(), but that was the only change I had to make in my code.
The solution to this problem is to reimport project settings from their blank project. It will fix any build problems you have.
The bug report, for those who would like to be kept informed:
https://developers.facebook.com/bugs/1623483557935932/

Is it possible to initialize a ConfigurationSection from an external file?

I have a custom configuration property in my app. It looks something like this:
public class OverrideConfiguration : ConfigurationSection
{
[ConfigurationProperty(PROP_ADMIN_CONNSTR)]
public StringConfigurationElement AdminConnectionString
{
get { return base[PROP_ADMIN_CONNSTR] as StringConfigurationElement; }
set { base[PROP_ADMIN_CONNSTR] = value; }
}
// .. Various other properties, but you get the idea
}
However, what I'd like is to allow the .config file to be pointed to an external file source. Something like this:
<ServiceOverrides file="Overrides.local.config" />
Now, the built-in configSource attribute is close to what I need, but it has two major issues.
Files must exist. If the file doesn't exist, it errors out.
Files must be in the current directory or in a deeper directory. In other words, I can't point to ..\Overrides.local.config
What I want is pretty much identical to the <appSettings file="..." /> configuration element. However, that attribute seems to be something appSettings implemented, and is not part of the base ConfigurationSection class.
My Question:
Is it possible to override something in ConfigurationSection that will basically read XML data from a different location? I don't want to change any other aspect of my class or do my own XML deserialization or anything. I simply want to check if a file exists, if so, load in the XML contents from that file, otherwise load in the default XML contents.
Ok, I have a working solution. I'm not sure if it's the best approach, but it does appear to work exactly how I want.
private readonly Queue<String> externalSources = new Queue<String>();
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
var externalFile = reader.GetAttribute("File");
if(!String.IsNullOrWhiteSpace(externalFile))
{
externalSources.Enqueue(externalFile);
}
base.DeserializeElement(reader, serializeCollectionKey);
}
protected override void PostDeserialize()
{
base.PostDeserialize();
// Override data with local stuff
if (externalSources.Count == 0) return;
string file = externalSources.Dequeue();
if (System.IO.File.Exists(file))
{
var reader = XmlReader.Create(file);
base.DeserializeSection(reader);
}
}
First, I trap the DeserializeElement event, which happens when we read the <ServiceOverrides> element. We check if it has a File attribute, and if so we add it to a queue of external sources to load.
Next, we trap the PostDeserialize event, which gets called after all the local XML is parsed. If there's an external source in the queue, we dequeue it, check if it actually exists, then create an XmlReader with the contents of that file. Now we can simply call DeserializeSection again and pass in our new reader. The ConfigurationSection class is smart enough to just overwrite or append any new data to the existing configuration. What I get at the end is an aggregation of both configuration files, where the include file wins in the event of a duplicate.
Now, what's this nonsense with the queue? Well, it seems every time you call DeserializeSection, it'll call PostDeserialize again. So, if we simply trapped PostDeserialize, check the File attribute, and call DeserializeSection again, we'd get in an infinite loop. We could just use a flag to remember if we already loaded the external file, but a queue has the added benefit of allowing the include file to load more include files (not that I'd ever want to do that, but you might).
Tips: This will probably work fairly well, and is simple to understand, but if you're using it in production code, there's a few things you could improve on. First, externalSources doesn't really need to be a queue, since these calls aren't actually recursive. You can probably just use a string, and set it to null after you're done processing that file. Second, this could cause an infinite loop in the event of a circular include chain. You could create a List<T> of previously included files, then check if the include already exists in that list before adding it to the queue.
Hope this helps someone!

Is there an equivalent field to Label/Publisher in taglib-sharp?

I'm trying to update the label/publisher field using Taglib-sharp, but I can't see it anywhere in its Object Hierarchy using Object Browser.
I've searched through google and the documentation and it looks like it's a field that's not catered for.
Before I look for alternatives (can any one suggest any?) that can edit those field, I thought I'd have one last crack and ask within the StackOverflow community who is familiar with TagLib-sharp that had a more informed opinion?
Thanks in Advance,
Francis
Update : I've investigated other libraries such as mpg123 & UltraID3Lib but they seem to have the same limitations.
Well, Daniel Fuchs answer didn't work for me. But, it was a beginning.
The step by step to add a field in the TagLib-sharp code is:
Download Source
Open the File TagLib/Tag.cs and insert the following code (I inserted it below PerformersSort, line 250):
public virtual string Publisher
{
get { return ""; }
set { }
}
Open the File TagLib/Id3v2/Tag.cs and insert the following code (I inserted it below PerformersSort, line 1292):
public override string Publisher
{
get { return GetTextAsString(FrameType.TPUB); }
set { SetTextFrame(FrameType.TPUB, value); }
}
Open the File TagLib/Id3v2/FrameTypes.cs and insert the following code (I inserted it below TPOS, line 71):
public static readonly ReadOnlyByteVector TPUB = "TPUB";
Now comes the "Aha" thing. Open the File TagLib/CombinedTag.cs and insert the following code (I inserted it below PerformersSort, line 318):
public override string Publisher
{
get
{
foreach (Tag tag in tags)
{
if (tag == null)
continue;
string value = tag.Publisher;
if (value != null)
return value;
}
return null;
}
set
{
foreach (Tag tag in tags)
if (tag != null)
tag.Publisher = value;
}
}
Finally, compile the code.
IMPORTANT: I had problems compiling the code, as well. You must download the SharpZipLib dll (.NET 2.0) and include this dll in the taglib project. Also, I needed to install NUnit, which I made with Nuget. At last, I commented the GDK lib and all its errors inside the test code, since in production it won't be used.
Well TagLib# is not able to to read the publisher tag. Even the newest version (2.1.0.0) as of now won't be able to do that. As an alternative you can add this functionality yourself using the source code of TagLib#, which is freely available.
To do so, open the file TagLib/Id3v2/FrameTypes.cs and add the following line somewhere:
public static readonly ReadOnlyByteVector TPUB = "TPUB"; // Publisher field
And in the file TagLib/Id3v2/Tag.cs:
public string Publisher {
get {return GetTextAsString (FrameType.TPUB);}
set {SetTextFrame (FrameType.TPUB, value);}
}
You can then access the Publisher field using something like this
TagLib.File tf = TagLib.File.Create(...); // open file
tf.Tag.Publisher = "Label XY"; // write new Publisher
tf.Save(); // save tags
Please note, that this is an ugly hack but will work for MP3 files.
I'm not used to TagLib#, but I'm using TagLib in a Qt project, where I retrieve this information inspecting TagLib::File::properties.
Take a look at the documentation, it is just a string map with every property and values.
Hope TagLib# has this method.
Update 2019-12-30:
It looks like the main taglib project has included the publisher field, so you should just use the latest version instead. I've updated to the latest TagLib from my fork and can attest that it works as expected.
Tip : If you want to change the framework version that TagLib compiles to (at time of writing it defaults to 462 and .NET STD 2.0), you need to change the Directory.Build.Props file located in the Solutions folder.
<Project>
<PropertyGroup>
<ReleaseVersion>2.2.0.0-beta</ReleaseVersion>
<RepositoryUrl>https://github.com/mono/taglib-sharp</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<TaglibSharpTargetFramework>net472;netstandard2.0</TaglibSharpTargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
</Project>
I've pasted my version above which shows that I've changed it to compile to .NET 4.7.2 instead.

Silverlight C# - ComponentOne Spellchecker not loading dictionary

This may be a long shot, but I'm using ComponentOne's Spellchecker control for Silverlight. I made a test project, added a plain textbox and a button to it, added the references to the C1.Silverlight and C1.Silverlight.SpellChecker bits, and added the dictionary file to my project.
In the code, I called up the spellchecker on button1's click event and it worked SPLENDIDLY. The spellchecker dialog shows up, and works exactly as it should.
Since that test was successful, I then tried to implement this into my existing project. I've had no success for absolutely NO reason that I can determine, since I used the EXACT SAME code.
Here's the code I use to call the component:
using C1.Silverlight;
using C1.Silverlight.SpellChecker;
using C1.Silverlight.Resources;
public partial class MainPage : UserControl
{
C1SpellChecker spellChecker = new C1SpellChecker();
public MainPage()
{
InitializeComponent();
spellChecker.MainDictionary.LoadAsync("C1Spell_en-US.dct");
}
private void btnSpelling_Click(object sender, RoutedEventArgs e)
{
var dlg = new C1SpellDialog();
spellChecker.CheckControlAsync(txtArticle, false, dlg);
}
The references to C1.Silverlight and C1.Silverlight.Spellchecker are added to this project as well, and the dictionary as been added in the same fashion as well. The issue seems to be that for whatever reason the dictionary is not loading, because the spellChecker.Enabled method returns whether or not the main dictionary has been loaded. If I call MessageBox.Show("SpellChecker Enabled = " + spellChecker.Enabled.ToString()); it shows false, even though the call to load the dictionary is there (as you can see).
What would cause the dictionary to not load? Have I added it to my project incorrectly somehow?
EDIT: I suspect that I have added the dictionary to the project incorrectly, because the ComponentOne reference states:
If C1SpellChecker cannot find the
spelling dictionary, it will not throw
any exceptions. The Enabled property
will be set to false and the component
will not be able to spell-check any
text.
I just don't know what's wrong though because it was added in the same way that it was in the test project (Right clicked on the project.web->Add->Existing Item)
As always, thank you!
-Sootah
You could add the dictionary to the Silverlight app as an embedded resource and then load it using this code:
public MainPage()
{
InitializeComponent();
// load C1SpellChecker dictionary from embedded resource
var asm = this.GetType().Assembly;
foreach (var res in asm.GetManifestResourceNames())
{
if (res.EndsWith(".dct"))
{
using (var s = asm.GetManifestResourceStream(res))
{
sc.MainDictionary.Load(s);
break;
}
}
}
}
I think this post is duplicated in our forum as well, but will answer first here. Please try this:
1) Try to access the .dct file using your browser. If you cannot see it, it's probably because your web server is not serving that type of files. You need ton configure the web server to allow it.
2) verify the URL you are using is correct.http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/86955/241328.aspx#241328
3) Check you are setting everything correctly: http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/81924/227790.aspx#227790
Hope this helps!

Categories