I am passing an array from my SmartFoxServer extension to my Unity3d game but I am having a hard time parsing. Here is how I send it in my extension:
SFSObject resObj = new SFSObject();
ISFSArray myArray= new SFSArray();
myArray.addUtfString("some String");
myArray.addUtfString("another string");
myArray.addUtfString("more string");
resObj.putSFSArray("myArray", myArray);
send("mySentData", resObj, gameExt.getGameRoom().getUserList());
In my Unity3d C# code, I do the following:
ISFSArray myNewArray= dataObject.GetSFSArray("myArray");
But, I am not sure how to parse the array for each string. I've tried something like this:
for (int i = 0; i <= myNewArray.Size(); i++)
{
String w = cardsDealt[0];
}
But this gives an error; Any tips on how to do this:
thanks
Don't put your strings in sfsArray , put them in one sfsObject :
Server :
ISFSObject resObj = new SFSObject();
resObj.putUtfString("name1",value1);
resObj.putUtfString("name2",value2);
resObj.putUtfString("name3",value3);
send("mySentData", resObj, gameExt.getGameRoom().getUserList());
Client :
private void onExtensionResponse(BaseEvent evt)
{
string cmd = evt.Params["cmd"].ToString();
if(cmd == "mySentData")
{
ISFSObject dataObject= evt.Params["params"] as ISFSObject;
string str1 = dataObject.GetUtfString("name1");
string str2 = dataObject.GetUtfString("name2");
string str3 = dataObject.GetUtfString("name3");
}
}
Related
I hava a specific string that I want to replace
string gerneralRootPath = docTab.Rows[0]["URL"].ToString();
string documentName = docTab.Rows[0]["NAME"].ToString();
var connectNamesAndURL = new StringBuilder(gerneralRootPath);
connectNamesAndURL.Remove(30,20);
connectNamesAndURL.Insert(30, documentName);
gerneralRootPath = connectNamesAndURL.ToString();
The output of gerneralRootPath is
"Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf"
The output of is documentName is
"doc123"
My gole is to remove everything after /PDF/.. so that final string looks like this
Documents/Z_Documentation/PDF/doc123
So how can I remove everything after the /PDF/..
Try this
string gerneralRootPath = "Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf";
gerneralRootPath = gerneralRootPath.Remove(gerneralRootPath.IndexOf("PDF") + 3);
gerneralRootPath = gerneralRootPath +"/"+documentName ;
You can achieve this using String.Split() function:
string input = "Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf";
string output = input.Split(new string[] { "/PDF/" }, StringSplitOptions.None).First() + "/PDF/doc123";
using System.IO;
string result = gerneralRootPath.Replace(Path.GetFileName(gerneralRootPath), documentName);
With Path.GetFileName (from System.IO) you get your filename:
sales.2010+Implementation+Revised+Feb10.pdf
The result is:
Documents/Z_Documentation/PDF/doc123
please find the sample code
int i = gerneralRootPath.IndexOf("/PDF/");
if (i >= 0) gerneralRootPath = gerneralRootPath.Substring(0,i+5);
i hope this will help you....
This is an example:
class Program
{
static string RemoveAfterPDF(string gerneralRootPath)
{
string pdf = "PDF";
int index = gerneralRootPath.IndexOf(pdf);
return gerneralRootPath.Substring(0, index + pdf.Length);
}
public static void Main()
{
string test = RemoveAfterPDF("Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf");
}
}
Edit
This is better and much more reusable example:
class Program
{
static string RemoveAfter(string gerneralRootPath, string removeAfter)
{
string result = string.Empty;
int index = gerneralRootPath.IndexOf(removeAfter);
if (index > 0)
result = gerneralRootPath.Substring(0, index + removeAfter.Length);
return result;
}
public static void Main()
{
string test = RemoveAfterPDF("Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf", "PDF");
}
}
Having problems with this code ..
GlodalVariables.SoftID = "55";
WebClient client = new WebClient ();
Uri uri = new Uri ("http://www.example.com/CreateEntry.php");
string folder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
Android.Content.Context myContext = Android.App.Application.Context;
try{
string smsUri = System.IO.Path.Combine (folder, "SL.db");
string myjson = "";
SQLiteDatabase Mydb = SQLiteDatabase.OpenDatabase(smsUri , null, DatabaseOpenFlags.OpenReadwrite );
ICursor SMScursor = Mydb.Query ("MySMSLog", null,null, null,null, null ,"TheDate ASC");
MySMSLog test = new MySMSLog() ;
if (SMScursor.MoveToFirst ()) {
while (!SMScursor.IsAfterLast){
string number = SMScursor.GetString(SMScursor.GetColumnIndex("TheNumber"));
string name = SMScursor.GetString(SMScursor.GetColumnIndex("TheName"));
string date = SMScursor.GetString(SMScursor.GetColumnIndex("TheDate"));
string direction = SMScursor.GetString(SMScursor.GetColumnIndex("TheDirection"));
string text = SMScursor.GetString(SMScursor.GetColumnIndex("TheText"));
string id = SMScursor.GetString(SMScursor.GetColumnIndex("Id"));
test.Id = int.Parse(id);
test.TheDate = date;
test.TheDirection = direction ;
test.TheName = name;
test.TheNumber = number;
test.TheText = text;
string output = Newtonsoft.Json.JsonConvert.SerializeObject (test);
myjson = myjson + output + " ";
SMScursor.MoveToNext ();
}
}
System.Console.WriteLine (myjson );
System.Console.WriteLine();
SMScursor.Close ();
When i Copy the complete json string into a json test site (http://jsonlint.com/)
It tells me the sting is invalid ...
I'm getting all the record rows and putting them into a single json string before pushing them over to the server..
Shouldn't you get the result in an array form? So the final json should look like :
[{json1},{json2}..]
Probably if you have just {json1} {json2} this is not a valid object.
Could an alternative solution be to build a collection of "MySMSLog" objects, then serialise the collection throught JSonConvert? That way you don't need to worry about getting the structure correct through your own string manipulation.
This would most likely also future proof your code on the ridiculously outlandish chance that JSON standards change, as the NewtonSoft library would be updated as well.
I want to split the below string with given output.
Can anybody help me to do this.
Examples:
/TEST/TEST123
Output: /Test/
/TEST1/Test/Test/Test/
Output: /Test1/
/Text/12121/1212/
Output: /Text/
/121212121/asdfasdf/
Output: /121212121/
12345
Output: 12345
I have tried string.split function but it is not worked well. Is there any idea or logic that i can implement to achieve this situation.
If the answer in regular expression that would be fine for me.
You simply want the first result of Spiting by /
string output = input.Split('/')[0];
But in case that you have //TEST/ and output should be /TEST you can use regex.
string output = Regex.Matches(input, #"\/?(.+?)\/")[0].Groups[1].Value;
For your 5th case : you have to separate the logic. for example:
public static string Method(string input)
{
var split = input.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 0) return input;
return split[0];
}
Or using regex.
public static string Method(string input)
{
var matches = Regex.Matches(input, #"\/?(.+?)\/");
if (matches.Count == 0) return input;
return matches[0].Groups[1].Value;
}
Some results using method:
TEST/54/ => TEST
TEST => TEST
/TEST/ => TEST
I think this would work:
string s1 = "/TEST/TEST123";
string s2 = "/TEST1/Test/Test/Test/";
string s3 = "/Text/12121/1212/";
string s4 = "/121212121/asdfasdf/";
string s5 = "12345";
string pattern = #"\/?[a-zA-Z0-9]+\/?";
Console.WriteLine(Regex.Matches(s1, pattern)[0]);
Console.WriteLine(Regex.Matches(s2, pattern)[0]);
Console.WriteLine(Regex.Matches(s3, pattern)[0]);
Console.WriteLine(Regex.Matches(s4, pattern)[0]);
Console.WriteLine(Regex.Matches(s5, pattern)[0]);
class Program
{
static void Main(string[] args)
{
string example = "/TEST/TEST123";
var result = GetFirstItem(example);
Console.WriteLine("First in the list : {0}", result);
}
static string GetFirstItem(string value)
{
var collection = value?.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var result = collection[0];
return result;
}
}
StringSplitOptions.RemoveEmptyEntries is an enum which tells the Split function that when it has split the string into an array, if there are elements in the array that are empty strings, the function should not include the empty elements in the results. Basically you want the collection to contain only values.
public string functionName(string input)
{
if(input.Contains('/'))
{
string SplitStr = input.Split('/')[1];
return "/"+SplitStr .Substring(0, 1) +SplitStr.Substring(1).ToLower()+"/"
}
return input;
}
output = (output.Contains("/"))? '/' +input.Split('/')[1]+'/':input;
private void button1_Click(object sender, EventArgs e)
{
string test = #"/Text/12121/1212/";
int first = test.IndexOf("/");
int last = test.Substring(first+1).IndexOf("/");
string finall = test.Substring(first, last+2);
}
i try this code with all your examples and get correct output. try this.
The following method may help you.
public string getValue(string st)
{
if (st.IndexOf('/') == -1)
return st;
return "/" + st.Split('/')[1] + "/";
}
Here is a sample of my code.
Here I recieve a string variable from another page.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string newparameter = this.NavigationContext.QueryString["search"];
weareusingxml();
displayResults(newparameter);
}
private void displayResults(string search)
{
bool flag = false;
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("People.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
List<Person> data = (List<Person>)serializer.Deserialize(stream);
List<Result> results = new List<Result>();
for (int i = 0; i < data.Count; i++)
{
string temp1 = data[i].name.ToUpper();
string temp2 = "*" + search.ToUpper() + "*";
if (temp1 == temp2)
{
results.Add(new Result() {name = data[i].name, gender = data[i].gender, pronouciation = data[i].pronouciation, definition = data[i].definition, audio = data[i].audio });
flag = true;
}
}
this.listBox.ItemsSource = results;
}
catch
{
textBlock1.Text = "error loading page";
}
if(!flag)
{
textBlock1.Text = "no matching results";
}
}
Nothing is loaded into the list when the code is run, I just get the message "no matching results".
Looks like you are trying to do a contains search (my guess based on your addition of the * around the search string. You can remove the '*' and do a string.Contains match.
Try this.
string temp1 = data[i].name.ToUpper();
string temp2 = search.ToUpper()
if (temp1.Contains(temp2))
{
It looks like you are trying to check if one string contains another (ie substring match) and not if they are equal.
In C#, you do this like this:
haystack = "Applejuice box";
needle = "juice";
if (haystack.Contains(needle))
{
// Match
}
Or, in your case (and skip the * you added to the string temp2)
if (temp1.Contains(temp2))
{
// add them to the list
}
Have you checked to make sure data.Count > 0?
I have declared a class variable in here
void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
Stream responseStream = e.Result;
StreamReader responseReader = new StreamReader(responseStream);
string response = responseReader.ReadToEnd();
string[] split1 = Regex.Split(response, "},{");
List<string> pri1 = new List<string>(split1);
pri1.RemoveAt(0);
string last = pri1[pri1.Count() - 1];
pri1.Remove(last);
}
}
and I want to use the class variable str in this method
void AddPrimaryMarkerGraphics(object sender, getPrimaryListCompletedEventArgs e)
{
List<PrimaryClass> primaryList = new List<PrimaryClass>(e.Result);
PrimaryClass sc = new PrimaryClass();
for (int a = 0; a <= e.Result.Count - 1; a++)
{
string schname = e.Result.ElementAt(a).PrimarySchool;
string tophonour = e.Result.ElementAt(a).TopHonour;
string cca = e.Result.ElementAt(a).Cca;
string topstudent = e.Result.ElementAt(a).TopStudent;
string topaggregate = e.Result.ElementAt(a).TopAggregate;
string topimage = e.Result.ElementAt(a).TopImage;
foreach (string item in str)
{
string abc = "[{" + item + "}]";
byte[] buf = System.Text.Encoding.UTF8.GetBytes(abc);
MemoryStream ms = new MemoryStream(buf);
JsonArray users = (JsonArray)JsonArray.Load(ms);
var members = from member in users
//where member["SEARCHVAL"]
select member;
foreach (JsonObject member in members)
{
string schname = member["SEARCHVAL"];
string axisX = member["X"];
string axisY = member["Y"];
// Do something...
string jsonCoordinateString = "{'Coordinates':[{'X':" + axisX + ",'Y':" + axisY + "}]}";
CustomCoordinateList coordinateList = DeserializeJson<CustomCoordinateList>(jsonCoordinateString);
GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer_Primary"] as GraphicsLayer;
for (int i = 0; i < coordinateList.Coordinates.Count; i++)
{
Graphic graphic = new Graphic()
{
Geometry = new MapPoint(coordinateList.Coordinates[i].X, coordinateList.Coordinates[i].Y),
Symbol = i > 0 ? PrimarySchoolMarkerSymbol : PrimarySchoolMarkerSymbol
};
graphic.Attributes.Add("PrimarySchool", schname);
graphic.Attributes.Add("xcoord", axisX);
graphic.Attributes.Add("ycoord", axisY);
graphicsLayer.Graphics.Add(graphic);
}
}
}
}
}
That's where the error shows.
You've almost certainly declared the variable in a method (i.e. as a local variable), instead of directly in the class itself (as an instance variable). For example:
// Wrong
class Bad
{
void Method1()
{
List<string> str = new List<string>();
}
void Method2()
{
foreach (string item in str)
{
...
}
}
}
// Right
class Good
{
private List<string> str = new List<string>();
void Method1()
{
str = CreateSomeOtherList();
}
void Method2()
{
foreach (string item in str)
{
...
}
}
}
As a side-note: if you're very new to C#, I would strongly recommend that you stop working on Silverlight temporarily, and write some console apps just to get you going, and to teach you the basics. That way you can focus on C# as a language and the core framework types (text, numbers, collections, I/O for example) and then start coding GUIs later. GUI programming often involves learning a lot more things (threading, XAML, binding etc) and trying to learn everything in one go just makes things harder.
It doesn't work because str is not declared in the other variable. It's sscopong problem. Can you pass str as an input to the other function?