//Get Participant IDs of a contact
        public MpParticipant GetParticipantRecord(string token)
        {
            var results = _ministryPlatformService.GetRecordsDict("MyParticipantRecords", token);
            Dictionary <string, object> result = null;

            try
            {
                result = results.SingleOrDefault();
            }
            catch (InvalidOperationException ex)
            {
                if (ex.Message == "Sequence contains more than one element")
                {
                    throw new MultipleRecordsException("Multiple Participant records found! Only one participant allowed per Contact.");
                }
            }

            if (result == null)
            {
                return(null);
            }
            var participant = new MpParticipant
            {
                ContactId                = result.ToInt("Contact_ID"),
                ParticipantId            = result.ToInt("dp_RecordID"),
                EmailAddress             = result.ToString("Email_Address"),
                PreferredName            = result.ToString("Nickname"),
                DisplayName              = result.ToString("Display_Name"),
                ApprovedSmallGroupLeader = result.ToBool("Approved_Small_Group_Leader")
            };

            return(participant);
        }
        public async Task <string> PostBranchImage()
        {
            string finalPath = "http://localhost:51680/";
            Dictionary <string, object> dict = new Dictionary <string, object>();

            try
            {
                var httpRequest = HttpContext.Current.Request;

                foreach (string file in httpRequest.Files)
                {
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

                    var postedFile = httpRequest.Files[file];
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {
                        int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB

                        IList <string> AllowedFileExtensions = new List <string> {
                            ".jpg", ".gif", ".png"
                        };
                        var ext       = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                        var extension = ext.ToLower();
                        if (!AllowedFileExtensions.Contains(extension))
                        {
                            var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                            dict.Add("error", message);
                            return(dict.ToString());
                        }
                        else if (postedFile.ContentLength > MaxContentLength)
                        {
                            var message = string.Format("Please Upload a file upto 1 mb.");

                            dict.Add("error", message);
                            return(dict.ToString());
                        }
                        else
                        {
                            var filePath = HttpContext.Current.Server.MapPath("~/Content/BranchLogos/" + postedFile.FileName);
                            finalPath = finalPath + "/Content/BranchLogos/" + postedFile.FileName;
                            postedFile.SaveAs(filePath);
                        }
                    }

                    var message1 = finalPath;
                    return(message1);;
                }
                var res = string.Format("Please Upload a image.");
                dict.Add("error", res);
                return(dict.ToString());
            }
            catch (Exception ex)
            {
                var res = string.Format("some Message");
                dict.Add("error", res);
                return(dict.ToString());
            }
        }
Пример #3
0
        public override string ToString()
        {
            var str = map.ToString(kvp => kvp.Key.ToString() + " -> " + kvp.Value.ToString(), "\r\n");

            if (this.previous == null)
            {
                return(str);
            }

            return(str + "\r\n-----------------------\r\n" + previous.ToString());
        }
Пример #4
0
        public async Task <IHttpActionResult> TryDetection()
        {
            int            MaxContentLength      = 1024 * 1024 * 3; //Size = 3 MB
            IList <string> AllowedFileExtensions = new List <string> {
                ".jpg", ".jpeg", ".png"
            };
            string n = string.Empty;

            Dictionary <string, object> ErrorInfoDict = new Dictionary <string, object>();

            if (!Request.Content.IsMimeMultipartContent())
            {
                ErrorInfoDict.Add("content_error", "Request is not multipart typed");
                return(BadRequest(ErrorInfoDict.ToString()));
            }

            else
            {
                string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DetectionAPI", "UserImages");
                Directory.CreateDirectory(filePath);

                var multipartFormDataStreamProvider = new MultipartFormDataStreamProvider(filePath);

                Request.Content.LoadIntoBufferAsync().Wait();
                await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);

                if (ErrorInfoDict == null)
                {
                }

                foreach (var file in multipartFormDataStreamProvider.FileData)
                {
                    try
                    {
                        if (file.Headers.ContentLength > MaxContentLength)
                        {
                            ErrorInfoDict.Add("content_error", $@"A file in a request is larger, than {MaxContentLength}");
                            return(BadRequest(ErrorInfoDict.ToString()));
                        }


                        Console.WriteLine(file.Headers.ContentDisposition.FileName);
                        Console.WriteLine("Server file path: " + file.LocalFileName);
                    }
                    catch (Exception exc)
                    {
                    }
                }



                return(Ok());
            }
        }
Пример #5
0
        private IExpressionData ParseExpressionData(StringBuilder expressionCache)
        {
            Dictionary <string, IExpressionData> expressionDataCache = new Dictionary <string, IExpressionData>(10);

            while (!_parseOverRegex.IsMatch(expressionDataCache.ToString()))
            {
                foreach (OperatorAdapter operatorAdapter in _operatorAdapters)
                {
                    operatorAdapter.ParseExpression(expressionCache, expressionDataCache);
                }
            }
            return(expressionDataCache[expressionDataCache.ToString()]);
        }
Пример #6
0
    public DKOverlayData InstantiateOverlay(string name)
    {
        DKOverlayData source;

        if (!overlayDictionary.TryGetValue(name, out source))
        {
            Debug.LogError("Unable to find " + name + " in '" + overlayDictionary.ToString());
            return(null);
        }
        else
        {
            return(source.Duplicate());
        }
    }
 public bool isValidProductDetail(Dictionary <string, object> productDetail, string productType)
 {
     if (productDetail.ToString().Contains('|') && productType == product.ProductType)
     {
         return(true);
     }
     else if (productDetail.ToString().Contains(';') && productType == product.ProductType)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
        public void ReferenceAllTypesInClosedGenericParametersWithReferences(
            Tuple <IInnerInterface, InnerEventArgs, InnerDelegate> arg0,
            List <InnerEnum> innerEnums,
            InnerStruct[] innerStructs,
            Lazy <InnerStruct.InnerStructInnerEnum> innerStructInnerEnum,
            IEnumerable <InnerStruct.IInnerStructInnerInterface> innerStructInnerInterface,
            Dictionary <InnerStruct.InnerStructInnerStruct, InnerStruct.InnerStructInnerClass> innerStructInnerClassByInnerStructInnerStruct,
            Func <InnerAbstractClass, InnerAbstractClass.InnerAbstractClassInnerEnum, InnerAbstractClass.IInnerAbstractClassInnerInterface> getInnerAbstractClass,
            List <Dictionary <InnerAbstractClass.InnerAbstractClassStruct, IEnumerable <InnerImplementingClass[]> > > stuff)
        {
            string toStringHolder;

            toStringHolder = arg0.ToString();
            toStringHolder = arg0.Item1.ToString();
            toStringHolder = arg0.Item2.ToString();
            toStringHolder = arg0.Item3.ToString();
            toStringHolder = innerEnums.ToString();
            toStringHolder = innerEnums.First().ToString();
            toStringHolder = innerStructs.ToString();
            toStringHolder = innerStructs[0].ToString();
            toStringHolder = innerStructInnerEnum.ToString();
            toStringHolder = innerStructInnerEnum.Value.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Keys.First().ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Values.First().ToString();
            toStringHolder = getInnerAbstractClass.ToString();
            toStringHolder = stuff.ToString();
            toStringHolder = stuff[0].ToString();
            toStringHolder = stuff[0].Keys.First().ToString();
            toStringHolder = stuff[0].Values.First().ToString();
            toStringHolder = stuff[0].Values.First().First().ToString();
        }
        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("#");
            sb.Append(posHeads.Count);
            foreach (String key in posHeads.Keys)
            {
                sb.Append(",");
                sb.Append(posHeads[key].Count);
            }
            sb.Append(" posHeads=");
            sb.Append(posHeads.ToString());
            sb.Append("\n");
            sb.Append("#");
            sb.Append(negHeads.Count);
            foreach (String key in negHeads.Keys)
            {
                sb.Append(",");
                sb.Append(negHeads[key].Count);
            }
            sb.Append(" negHeads=");
            sb.Append(negHeads.ToString());

            return(sb.ToString());
        }
Пример #10
0
    private void onRockOnNote(SocketIOEvent e)
    {
        Debug.Log("onRockOnNote");
        string playerID = "";

        e.data.GetField(ref playerID, "player_id");
        int note_id = 0;

        e.data.GetField(ref note_id, "note_id");
        bool is_pressed = true;

        e.data.GetField(ref is_pressed, "is_pressed");

        Debug.Log("player id: " + playerID + "client_id : " + clientID);

        if (playerID == clientID)
        {
            Debug.Log("avoid echo");
            return;
        }

        Debug.Log(playerID);
        Debug.Log(players.ToString());
        Debug.Log(players [playerID].ToString());

        //Debug.Log (players [playerID].instrument);
        playNote(players [playerID].instrument, note_id, is_pressed);


        //instruments ["bongo"].playNote (note_id, is_pressed);
    }
Пример #11
0
 /// <summary>
 /// to string
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     lock (_syncRoot)
     {
         return(_pool.ToString());
     }
 }
Пример #12
0
    public void AddTransition(Transition trans, StateID id)
    {
        // Check if anyone of the args is invalid
        if (trans == Transition.eTransiton_Null)
        {
            Debug.LogError("State ERROR: eTransiton_Null is not allowed for a real transition");
            return;
        }

        if (id == StateID.eStateID_Null)
        {
            Debug.LogError("State ERROR: eStateID_Null is not allowed for a real ID");
            return;
        }

        // Since this is a Deterministic FSM,
        //   check if the current transition was already inside the map
        if (_stateMap.ContainsKey(trans))
        {
            Debug.LogError("State ERROR: State " + _stateMap.ToString() + " already has transition " + trans.ToString() +
                           "Impossible to assign to another state");
            return;
        }

        _stateMap.Add(trans, id);
    }
Пример #13
0
 private void ToStringHelper(StringBuilder buf, String indent, HashSet <Object> visited)
 {
     buf.Append(this.GetType().ToString());
     buf.Append(".").Append(id == null ? NO_ID : id);
     buf.Append(": [").Append(Count).Append("]");
     buf.Append(local == null ? "{}" : local.ToString());
     if (ancestors != null && ancestors.Count > 0)
     {
         foreach (MmdScope ancestor in ancestors)
         {
             StringBuilder ancestorStr = new StringBuilder();
             ancestorStr.Append("\n").Append(indent).Append("    -> ");
             if (visited.Contains(ancestor))
             {
                 ancestorStr.Append("(Ref: ");
                 ancestorStr.Append(ancestor.GetType().ToString());
                 ancestorStr.Append(".").Append(ancestor.Id).Append(")");
             }
             else
             {
                 visited.Add(ancestor);
                 ancestor.ToStringHelper(ancestorStr, indent + "    ", visited);
             }
             buf.Append(ancestorStr);
         }
     }
 }
Пример #14
0
        /// <summary>
        /// sql execute
        /// </summary>
        /// <param name="strSQL"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public int Execute(string strSQL, Dictionary <string, object> args = null)
        {
            logger.logger.Debug("Entering with strSQL:" + strSQL);
            if (args != null)
            {
                logger.logger.Debug("args:" + args.ToString());
            }
            int           rowsAffected;
            SqlConnection conn = GetConnection(base.strConn);

            try
            {
                SqlCommand command = StrToCommand(conn, strSQL, args);
                rowsAffected = command.ExecuteNonQuery();
                SqlDataReader dataReader = command.ExecuteReader();
            }
            catch (SqlException ex)
            {
                logger.logger.Error(ex.Errors.ToString() + "\n" + ex.ToString());
                throw (ex);
            }
            catch (Exception ex)
            {
                logger.logger.Error(ex.ToString());
                throw (ex);
            }
            finally
            {
                conn.Close();
            }
            logger.logger.Debug("Exit with rowsAffected: " + rowsAffected.ToString());
            return(rowsAffected);
        }
Пример #15
0
        public Dictionary <string, int> getTestAdminData()
        {
            Dictionary <string, int> result = new Dictionary <string, int>();

            con = new ConnectionWrapper(location);
            object response         = con.getRequest("/admins");
            JArray responseEntities = JArray.Parse(response.ToString());
            JArray patientList      = JArray.Parse(responseEntities[0].ToString());

            foreach (JObject patient in patientList)
            {
                int    id   = 0;
                string name = null;
                JToken value;
                if (patient.TryGetValue("Id", out value))
                {
                    id = value.ToObject <int>();
                }
                if (patient.TryGetValue("Name", out value))
                {
                    name = value.ToObject <string>();
                }
                result.Add(name, id);
            }
            Debug.Log(result.ToString());
            return(result);
        }
Пример #16
0
 public void OnTownBuild(Town sender)
 {
     _buildedTowns.Add(sender.gameObject);
     sender.OnActivate += new Town.OnActivateContainer(OnTownActivate);
     var cardsTypes = new Dictionary<ResourceType, int>();
     switch (sender.Type) {
         case TownType.Village:
         cardsTypes.Add(ResourceType.Brick,1);
         cardsTypes.Add(ResourceType.Hay,1);
         cardsTypes.Add(ResourceType.Wood,1);
         cardsTypes.Add(ResourceType.Wool,1);
         break;
         case TownType.Town:
         cardsTypes.Add(ResourceType.Hay,2);
         cardsTypes.Add(ResourceType.Stone,3);
         break;
     }
     Debug.Log(cardsTypes.ToString());
     var cards = playerDeck.GetComponent<PlayerDeck>().GetCards(cardsTypes);
     Debug.Log(cards.Count);
     cards.ForEach(delegate(ResourceCard card) {
         var deck = decksController.GetComponent<DecksController>().GetDeck(card.ResourceType);
         card.ReturnCardToDeck(deck);
     });
 }
Пример #17
0
        ///// <summary>
        ///// key值base64
        ///// </summary>
        ///// <param name="keyValues"></param>
        ///// <returns></returns>
        //public Dictionary<string, string> stringtoBase4(Dictionary<string, string> keyValues)
        //{

        //}

        /// <summary>
        /// 功能描述: Ascii排序 返回排序后的一个字符(去掉空值)
        /// 创建  人:周文卿
        /// 创建时间:2018-11-15
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public string AsciiDesc(Dictionary <string, string> dict)
        {
            try
            {
                Dictionary <string, string> asciiDic = new Dictionary <string, string>();
                string[] arrKeynew = dict.Keys.ToArray();
                Array.Sort(arrKeynew, string.CompareOrdinal);
                string sing = "";
                foreach (var key in arrKeynew)
                {
                    string value = dict[key];
                    if (dict[key] != null)
                    {
                        //空值不参与签名 去掉空格
                        if (dict[key].ToString().Trim() != "")
                        {
                            sing += key + "=" + dict[key].ToString().Trim() + "&";
                        }
                    }
                }
                return(sing);
            }
            catch (Exception e)
            {
                throw new InsertException(e.Message, "RulePayMethod", "AsciiDesc", dict.ToString());
            }
        }
Пример #18
0
        public AppConfig EditConfig(string filePath, Dictionary <string, string> data, AppConfig config)
        {
            /*
             * foreach (KeyValuePair<string, string> item in config.data)
             * {
             *  foreach (KeyValuePair<string, string> item2 in data)
             *  {
             *      if (item.Key == item2.Key)
             *      {
             *          config.data[item.Value] = item2.Value;
             *      }
             *  }
             * }
             */

            foreach (var pair in data)
            {
                if (!config.data.ContainsKey(pair.Key))
                {
                    config.data.Add(pair.Key, pair.Value);
                }
                else
                {
                    config.data[pair.Key] = pair.Value;
                }
            }

            appConfig = JsonConvert.DeserializeObject <AppConfig>(data.ToString());
            return(appConfig);
        }
Пример #19
0
 /// <summary>
 /// Hook for storing data members by calling the various AddMember() overloads.
 /// </summary>
 /// <param name="builder">The Jsonizer instance to use for storing data members.</param>
 public void Jsonize(Jsonizer builder)
 {
     builder.AddMember("cdrid", CDRID.ToString(), true);
     builder.AddMember("dictionary", Dictionary.ToString(), true);
     builder.AddMember("language", Language.ToString(), true);
     builder.AddMember("audience", Audience.ToString(), true);
 }
Пример #20
0
        public void RunQuestionTwo(ICharacterReader[] readers, IOutputResult output)
        {
            var wordCount = new Dictionary <string, int>();

            //   string line = "a list of word frequencies ordered by word count and then alphabetically";
            string line = readers.ToString();

            while ((line != null))
            {
                var words = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                foreach (var word in words)
                {
                    if (wordCount.ContainsKey(word))
                    {
                        wordCount[word] = wordCount[word] + 1;
                    }
                    else
                    {
                        wordCount.Add(word, 1);
                        output.AddResult(wordCount.ToString());
                    }
                }
            }
        }
Пример #21
0
        public async Task <Response <Transaction> > CreateAsync(Dictionary <string, dynamic> parameters)
        {
            var content  = new StringContent(parameters.ToString(), Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("transactions", content);

            return(Api.ConvertResponse <Transaction>(await response.Content.ReadAsStringAsync()));
        }
Пример #22
0
 public void Dispose()
 {
     scoreController.noteWasMissedEvent -= ScoreController_noteWasMissedEvent;
     scoreController.noteWasCutEvent    -= ScoreController_noteWasCutEvent;
     mapData[difficultyBeatmap]          = currentMapData;
     Plugin.log.Debug(currentMapData.ToString());
 }
        public static void AddRange <K, V, T>(this IDictionary <K, V> dictionary, IEnumerable <T> collection, Func <T, K> keySelector, Func <T, V> valueSelector, string errorContext)
        {
            Dictionary <K, List <V> > repetitions = new Dictionary <K, List <V> >();

            foreach (var item in collection)
            {
                var key = keySelector(item);
                if (dictionary.ContainsKey(key))
                {
                    repetitions.GetOrCreate(key, () => new List <V> {
                        dictionary[key]
                    }).Add(valueSelector(item));
                }
                else
                {
                    dictionary.Add(key, valueSelector(item));
                }
            }

            if (repetitions.Count > 0)
            {
                throw new ArgumentException($@"There are some repeated {errorContext}...
{repetitions.ToString(kvp => $@"Key ""{kvp.Key}"" has {kvp.Value.Count} repetitions:
{kvp.Value.Take(ErrorExampleLimit).ToString("\r\n").Indent(4)}", "\r\n")}");
            }
        }
Пример #24
0
        protected void DataAdapter_Data(ref Dictionary <string, string> dic, string Data_FilePath)
        {
            string key = "Navigate_" + dic.ToString();
            Dictionary <string, string> obj = GetDepend(key) as Dictionary <string, string>;

            if (obj == null)
            {
                dic = new Dictionary <string, string>();
                string[] data = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("/Config/" + Data_FilePath + ".config")).Split('\n');
                for (int i = 0; i < data.Length; i++)
                {
                    if (data[i].Trim() != "")
                    {
                        string[] item = data[i].Trim().Split("||".ToCharArray()); if (!dic.ContainsKey(item[0].Replace(",", ",")))
                        {
                            dic.Add(item[0].Replace(",", ","), item[1]);
                        }
                    }
                }
                SetDepend(key, obj, dependkey);
            }
            else
            {
                dic = obj;
            }
        }
        private SqlCommand StrToCommand(SqlConnection conn, string strSQL, Dictionary <string, object> args = null)
        {
            logger.logger.Debug("Entering with conn:" + conn.ToString());
            logger.logger.Debug("strSQL: " + strSQL);
            if (args != null)
            {
                logger.logger.Debug("args:" + args.ToString());
            }
            SqlCommand command;

            try
            {
                command = new SqlCommand(strSQL, conn);
                if (args != null)
                {
                    foreach (KeyValuePair <string, object> kvp in args)
                    {
                        command.Parameters.AddWithValue(kvp.Key, kvp.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.logger.Error(ex.ToString());
                throw (ex);
            }
            logger.logger.Debug("Exit with command: " + command.CommandText);
            return(command);
        }
Пример #26
0
    private void SetGdprData(Dictionary <string, string> gdprConsentData)
    {
        string gdprConsentDataAsString = gdprConsentData != null?gdprConsentData.ToString() : "null";

        this.console.Append(gdprConsentDataAsString);
        HeyzapAds.SetGdprConsentData(gdprConsentData);
    }
Пример #27
0
        public static void MakeFingerprintFromRingSystems(string dataFileIn, string dataFileOut, bool anyAtom, bool anyAtomAnyBond)
        {
            var timings = new Dictionary <string, int>();

            Console.Out.WriteLine($"Start make fingerprint from file: {dataFileIn} ...");
            using (var fin = new StreamReader(dataFileIn))
            {
                var data = MakeFingerprintsFromSdf(anyAtom, anyAtomAnyBond, timings, fin, -1);
                try
                {
                    using (var fout = new StreamWriter(dataFileOut))
                    {
                        for (int i = 0; i < data.Count; i++)
                        {
                            try
                            {
                                fout.Write(data[i].ToString());
                                fout.Write('\n');
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
                catch (Exception exc3)
                {
                    Console.Out.WriteLine($"Could not write Fingerprint in file {dataFileOut} due to: {exc3.Message}");
                }

                Console.Out.WriteLine($"\nFingerprints:{data.Count} are written...ready");
                Console.Out.WriteLine($"\nComputing time statistics:\n{timings.ToString()}");
            }
        }
Пример #28
0
    public void setInformation(StoreDetails.RootObject store, List <Texture2D> posterTextures, Dictionary <StoreDetails.Product, Texture2D> productTexture)
    {
        Debug.Log("Spawning Room");
        Debug.Log(posterTextures.ToString());
        Debug.Log(productTexture.ToString());
        Debug.Log(store.storeBannerText);

        banner.SetActive(true);
        banner.GetComponent <Text>().text = store.storeBannerText;

        banner.GetComponentInChildren <Image>().sprite = Sprite.Create(posterTextures[0], new Rect(new Vector2(0, 0), new Vector2(posterTextures[0].width, posterTextures[0].height)), new Vector2(0, 0));



        int productSize = products.Count;

        print(productSize);
        if (store.products.Count < productSize)
        {
            productSize = store.products.Count;
        }


        for (int i = 0; i < productSize; i++)
        {
            products[i].GetComponent <Text>().text = store.products[i].productName;
            products[i].GetComponent <BuyThinfs>().SetProduct(store.products[i]);
            products[i].SetActive(true);
            products[i].GetComponentInChildren <Image>().sprite = Sprite.Create(productTexture[store.products[i]], new Rect(new Vector2(0, 0), new Vector2(productTexture[store.products[i]].width, productTexture[store.products[i]].height)), new Vector2(0, 0));
        }
    }
Пример #29
0
        private string GetInformation(FieldType fieldType)
        {
            string result = string.Empty;

            switch (fieldType.Field)
            {
            case LogMessageField.SequenceNr:
                result = SequenceNr.ToString();
                break;

            case LogMessageField.LoggerName:
                result = LoggerName;
                break;

            case LogMessageField.RootLoggerName:
                result = RootLoggerName;
                break;

            case LogMessageField.Level:
                result = Level.Level.ToString();
                break;

            case LogMessageField.Message:
                result = Message;
                break;

            case LogMessageField.ThreadName:
                result = ThreadName;
                break;

            case LogMessageField.TimeStamp:
                result = TimeStamp.ToString(UserSettings.Instance.TimeStampFormatString);
                break;

            case LogMessageField.Exception:
                result = ExceptionString;
                break;

            case LogMessageField.CallSiteClass:
                result = CallSiteClass;
                break;

            case LogMessageField.CallSiteMethod:
                result = CallSiteMethod;
                break;

            case LogMessageField.SourceFileName:
                result = SourceFileName;
                break;

            case LogMessageField.SourceFileLineNr:
                result = SourceFileLineNr.ToString();
                break;

            case LogMessageField.Properties:
                result = Properties.ToString();
                break;
            }
            return(result);
        }
    public async Task RemoteConfigAsync()
    {
        await countly.RemoteConfigs.Update();

        Dictionary<string, object> config = countly.RemoteConfigs.Configs;
        Debug.Log("RemoteConfig: " + config.ToString());
    }
Пример #31
0
        /// <summary>
        /// Reads parameters from the configuration file
        /// </summary>
        private void ReadParamters()
        {
            try
            {
                var doc = new XmlDocument();

                // Read configuration file
                doc.Load(AppDomain.CurrentDomain.BaseDirectory + @"\Config\" + _paramsFileName);

                // Read all the parametes defined in the configuration file
                XmlNodeList configNodes = doc.SelectNodes(xpath: "Tradier/*");
                if (configNodes != null)
                {
                    // Extract individual attribute value
                    foreach (XmlNode node in configNodes)
                    {
                        _parameters.Add(node.Name, node.InnerText);
                    }
                }

                // Log parameters
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info(_parameters.ToString(), _type.FullName, "ReadParamters");
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "ReadParameters");
            }
        }
 public void TestDictionaryToString()
 {
     TestClass testclass = new TestClass() { ID = 5, Decimal = 3.3M, Float = 3.23423F, String = "blah, \"asdff\"" };
     testclass.Class = new TestClass() { ID = 5, Decimal = 3.3M, Float = 3.23423F, String = "blah, \"asdff\"" };
     Dictionary<int, TestClass> lst = new Dictionary<int, TestClass>();
     for (int i = 0; i < 2; i++)
     {
         lst.Add(i, testclass);
     }
     string actual = lst.ToString(',');
     Assert.AreEqual("0,\"5,\"blah, \"\"asdff\"\"\",3.3,3.23423,\"5,\"blah, \"\"asdff\"\"\",3.3,3.23423\"\"\r\n1,\"5,\"blah, \"\"asdff\"\"\",3.3,3.23423,\"5,\"blah, \"\"asdff\"\"\",3.3,3.23423\"\"\r\n", actual);
 }
Пример #33
0
 public static string RpcCall(string url, string method, Dictionary<string, string> args)
 {
     string result = string.Empty;
     try
     {
         PHPRPC_Client rpc = new PHPRPC_Client(url);
         IPhprpc p = (IPhprpc)rpc.UseService(typeof(IPhprpc));
         result = p.data(method, args);
     }
     catch(Exception ex)
     {
         string error = string.Format("Exception in RpcCall():{0}, url = {1}, method={2}, args={3}", ex.ToString(), url, method, args.ToString());
     }
     return result;
 }
Пример #34
0
        public void GetOrAdd()
        {
            var d = new Dictionary<string, StockStatus>() {
                {"AAPL", new StockStatus { Price = 530.12m, Position = "Sell" }},
                {"GOOG", new StockStatus { Price = 123.5m, Position = "Buy" }}
            };

            d.GetOrAdd("AAPL").Position = "Buy";
            d.GetOrAdd("YHOO").Price = 1.99m;
            Console.Out.WriteLine(d.ToString<string, StockStatus>());

            Assert.That(d["AAPL"].Position, Is.EqualTo("Buy"), "Incorrect position.");
            Assert.That(d.Keys, Has.Count.EqualTo(3), "Incorrect number of keys.");
            Assert.That(d["YHOO"].Price, Is.EqualTo(1.99m), "Incorrect price.");
        }
Пример #35
0
        public List<Coordinate> GetShortestPath(Coordinate start, Coordinate goal)
        {
            HashSet<Coordinate> visited = new HashSet<Coordinate>();
            Dictionary<Coordinate, Coordinate> parents = new Dictionary<Coordinate, Coordinate>();
            Dictionary<Coordinate, double> gScore = new Dictionary<Coordinate, double>();
            HeapPriorityQueue<Coordinate> fScoreQueue = new HeapPriorityQueue<Coordinate>(rows * cols);
            parents[start] = start;
            gScore.Add(start, 0);
            fScoreQueue.Enqueue(start, gScore[start] + Heuristic(start, goal));
            while (fScoreQueue.Count() != 0)
            {
                Coordinate current = fScoreQueue.Dequeue();
                Console.Out.WriteLine("");
                Console.Out.WriteLine("Current = " + current.ToString());
                Console.Out.WriteLine("Visited = " + visited.ToString());
                Console.Out.WriteLine("Parents = " + parents.ToString());
                Console.Out.WriteLine("gScore = " + gScore.ToString());
                Console.Out.WriteLine("fScoreQueue = " + fScoreQueue.ToString());
                if (current == goal)
                {
                    return ReconstructPath(parents, goal);
                }

                visited.Add(start);
                foreach (Coordinate neighbor in board[current.row,current.col].GetNeighborCoordinates())
                {
                    if (visited.Contains(neighbor)) continue;
                    double newGScore = gScore[current] + Distance(current, neighbor);
                    if (!fScoreQueue.Contains(neighbor))
                    {
                        parents[neighbor] = current;
                        gScore[neighbor] = newGScore;
                        fScoreQueue.Enqueue(neighbor, newGScore + Heuristic(neighbor, goal));
                    }
                    else if (newGScore < gScore[neighbor])
                    {
                        parents[neighbor] = current;
                        gScore[neighbor] = newGScore;
                        fScoreQueue.UpdatePriority(neighbor, newGScore + Heuristic(neighbor, goal));
                    }

                }
            }

            return null;
        }
Пример #36
0
 public static void UpdateVersionFile(Dictionary<string, string> version, string versionFilePath)
 {
     try
     {
         FileStream versionFile = new FileStream(versionFilePath, FileMode.OpenOrCreate);
         foreach (string fileName in version.Keys)
         {
             string nameHashPair = fileName + "," + version[fileName] + ";";
             versionFile.Write(System.Text.Encoding.ASCII.GetBytes(nameHashPair), 0, System.Text.Encoding.ASCII.GetByteCount(nameHashPair));
         }
         versionFile.Close();
     }
     catch (Exception e)
     {
         Utils.configLog("E", e.Message + ". UpdateVersionFile, version: " + version.ToString());
     }
 }
Пример #37
0
 public ChampionListStatic(string data,
     string format,
     JObject keys,
     string type,
     string version,
     JObject originalObject)
 {
     this.data = new Dictionary<string, ChampionStatic>();
     this.keys = new Dictionary<string, string>();
     LoadData(data);
     this.format = format;
     if (keys != null)
     {
         this.keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(keys.ToString());
     }
     this.type = type;
     this.version = version;
     this.originalObject = originalObject;
 }
        public string PostData(string url, Dictionary<string, string> data, Encoding encoding = null)
        {
            var http = CreateNewRequest(url, "POST");

            http.ContentType = "application/x-www-form-urlencoded";

            if(encoding == null) encoding = new UTF8Encoding();

            var outgoingQueryString = HttpUtility.ParseQueryString(string.Empty);

            foreach (var item in data)
            {
                outgoingQueryString.Add(item.Key, item.Value);
            }

            PostBytes(data.ToString(), encoding, http);

            return ReadResponse(http, encoding);
        }
Пример #39
0
 public SgmlDtd getDTD(String version, String DTD)
 {
     if (log.IsDebugEnabled) log.Debug("getDTD(version: " + version + ", DTD: " + DTD + ")");
     SgmlReader reader = null;
     Dictionary<String, SgmlDtd> dtd = null;
     if (this.checkAvailableVersion(DTD+version) && !this.version.ContainsKey(version)) {
         reader = new SgmlReader();
         reader.CaseFolding = Sgml.CaseFolding.ToLower;
         String sgmlArticle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.availableVersion[DTD+version]);
         if (log.IsDebugEnabled) log.Debug("sgmlArticle: " + sgmlArticle);
         reader.SystemLiteral = sgmlArticle;
         dtd = new Dictionary<String, SgmlDtd>();
         dtd.Add(DTD, reader.Dtd);
         if (log.IsDebugEnabled) log.Debug("dtd.Add(DTD: " + DTD + ", reader.Dtd: " + reader.Dtd.ToString() + ")");
         this.version.Add(version, dtd);
         if (log.IsDebugEnabled) log.Debug("this.version.Add(version: " + version + ", dtd: " + dtd.ToString() + ")");
     }
     if (log.IsDebugEnabled) log.Debug("return this.version[version: " + version + "][DTD: " + DTD + "]");
     return this.version[version][DTD];
 }
        public static void Main(string[] args)
        {
            Console.WriteLine("*****开始发送******");

            JSMSClient client = new JSMSClient(app_key, master_secret);

            // 短信验证码 API
            // API文档地址 http://docs.jiguang.cn/jsms/server/rest_api_jsms/#api_3

            Dictionary<string, string> temp_para= new Dictionary<string, string>(); ;
            temp_para.Add("codes", "1914");
            string para = temp_para.ToString();
            Console.WriteLine(para);

            SMSPayload codes = new SMSPayload("134888888888", 9890, temp_para);
            String codesjson = codes.ToJson(codes);
            Console.WriteLine(codesjson);
            client._SMSClient.sendMessages(codesjson);

            Console.ReadLine();
        }
Пример #41
0
        public Boolean dealStopRatioRule(string appDir, string fileName)//讀取逆勢動態停利規則檔
        {
            try
            {

                strategyFileName = fileName;

                strategyFilePath = appDir + "\\" + Config_Dir + "\\" + fileName;

                strategyFile = new TradeFile(strategyFilePath);

                strategyFile.prepareReader();

                stopRatio = new Dictionary<int, int>();

                int checkRange;//最高點與最低點的範圍

                int ratio;//停利或是停損的計算百分比

                String tmpLine = "";

                String[] tmpData = new String[2];

                while (strategyFile.hasNext())
                {

                    tmpLine = strategyFile.getLine();

                    tmpData = tmpLine.Split(',');

                    checkRange = int.Parse(tmpData[0]);

                    ratio = int.Parse(tmpData[1]);

                    stopRatio.Add(checkRange, ratio);


                }

                Console.WriteLine(stopRatio.ToString());

            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Source);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return false;
            }
            return true;
        }
        public void ReferenceAllTypesInClosedGenericParametersWithReferences(
            Tuple<IInnerInterface, InnerEventArgs, InnerDelegate> arg0,
            List<InnerEnum> innerEnums,
            InnerStruct[] innerStructs,
            Lazy<InnerStruct.InnerStructInnerEnum> innerStructInnerEnum,
            IEnumerable<InnerStruct.IInnerStructInnerInterface> innerStructInnerInterface,
            Dictionary<InnerStruct.InnerStructInnerStruct, InnerStruct.InnerStructInnerClass> innerStructInnerClassByInnerStructInnerStruct,
            Func<InnerAbstractClass, InnerAbstractClass.InnerAbstractClassInnerEnum, InnerAbstractClass.IInnerAbstractClassInnerInterface> getInnerAbstractClass,
            List<Dictionary<InnerAbstractClass.InnerAbstractClassStruct, IEnumerable<InnerImplementingClass[]>>> stuff)
        {
            string toStringHolder;

            toStringHolder = arg0.ToString();
            toStringHolder = arg0.Item1.ToString();
            toStringHolder = arg0.Item2.ToString();
            toStringHolder = arg0.Item3.ToString();
            toStringHolder = innerEnums.ToString();
            toStringHolder = innerEnums.First().ToString();
            toStringHolder = innerStructs.ToString();
            toStringHolder = innerStructs[0].ToString();
            toStringHolder = innerStructInnerEnum.ToString();
            toStringHolder = innerStructInnerEnum.Value.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Keys.First().ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Values.First().ToString();
            toStringHolder = getInnerAbstractClass.ToString();
            toStringHolder = stuff.ToString();
            toStringHolder = stuff[0].ToString();
            toStringHolder = stuff[0].Keys.First().ToString();
            toStringHolder = stuff[0].Values.First().ToString();
            toStringHolder = stuff[0].Values.First().First().ToString();
        }
Пример #43
0
 public override String ToString()
 {
     // poor man's toString()
     IDictionary<String, Object> bld = new Dictionary<String, Object>();
     bld["EnableNormalizingResultsHandler"] = EnableNormalizingResultsHandler;
     bld["EnableFilteredResultsHandler"] = EnableFilteredResultsHandler;
     bld["EnableCaseInsensitiveFilter"] = EnableCaseInsensitiveFilter;
     bld["EnableAttributesToGetSearchResultsHandler"] = EnableAttributesToGetSearchResultsHandler;
     return bld.ToString();
 }
Пример #44
0
        private static MyContact ParseProfileRecord(Dictionary<string, object> recordsDict)
        {
            var contact = new MyContact
            {
                Address_ID = recordsDict.ToNullableInt("Address_ID"),
                Address_Line_1 = recordsDict.ToString("Address_Line_1"),
                Address_Line_2 = recordsDict.ToString("Address_Line_2"),
                Congregation_ID = recordsDict.ToNullableInt("Congregation_ID"),
                Household_ID = recordsDict.ToInt("Household_ID"),
                Household_Name = recordsDict.ToString("Household_Name"),
                City = recordsDict.ToString("City"),
                State = recordsDict.ToString("State"),
                County = recordsDict.ToString("County"),
                Postal_Code = recordsDict.ToString("Postal_Code"),                
                Contact_ID = recordsDict.ToInt("Contact_ID"),
                Date_Of_Birth = recordsDict.ToDateAsString("Date_of_Birth"),
                Email_Address = recordsDict.ToString("Email_Address"),
                Employer_Name = recordsDict.ToString("Employer_Name"),
                First_Name = recordsDict.ToString("First_Name"),
                Foreign_Country = recordsDict.ToString("Foreign_Country"),
                Gender_ID = recordsDict.ToNullableInt("Gender_ID"),
                Home_Phone = recordsDict.ToString("Home_Phone"),
                Last_Name = recordsDict.ToString("Last_Name"),
                Maiden_Name = recordsDict.ToString("Maiden_Name"),
                Marital_Status_ID = recordsDict.ToNullableInt("Marital_Status_ID"),
                Middle_Name = recordsDict.ToString("Middle_Name"),
                Mobile_Carrier = recordsDict.ToNullableInt("Mobile_Carrier_ID"),
                Mobile_Phone = recordsDict.ToString("Mobile_Phone"),
                Nickname = recordsDict.ToString("Nickname"),
                Age = recordsDict.ToInt("Age"),
                Passport_Number = recordsDict.ToString("Passport_Number"),
                Passport_Country = recordsDict.ToString("Passport_Country"),
                Passport_Expiration = ParseExpirationDate(recordsDict.ToNullableDate("Passport_Expiration")),
                Passport_Firstname = recordsDict.ToString("Passport_Firstname"),
                Passport_Lastname = recordsDict.ToString("Passport_Lastname"),
                Passport_Middlename = recordsDict.ToString("Passport_Middlename")                
            };
            if (recordsDict.ContainsKey("Participant_Start_Date"))
            {
                contact.Participant_Start_Date = recordsDict.ToDate("Participant_Start_Date");
            }
            if (recordsDict.ContainsKey("Attendance_Start_Date"))
            {
                contact.Attendance_Start_Date = recordsDict.ToNullableDate("Attendance_Start_Date");
            }

            if (recordsDict.ContainsKey("ID_Card"))
            {
                contact.ID_Number = recordsDict.ToString("ID_Card");
            }
            return contact;
        }
        public void ReferenceAllTypesInClosedGenericVariablesWithReferences()
        {
            Tuple<IInnerInterface, InnerEventArgs, InnerDelegate> tuple =
                new Tuple<IInnerInterface, InnerEventArgs, InnerDelegate>(new InnerImplementingClass(), new InnerEventArgs(), Console.WriteLine);
            List<InnerEnum> innerEnums = new List<InnerEnum>();
            InnerStruct[] innerStructs = new InnerStruct[10];
            Lazy<InnerStruct.InnerStructInnerEnum> innerStructInnerEnum = new Lazy<InnerStruct.InnerStructInnerEnum>();
            IEnumerable<InnerStruct.IInnerStructInnerInterface> innerStructInnerInterface = new List<InnerStruct.IInnerStructInnerInterface>();
            Dictionary<InnerStruct.InnerStructInnerStruct, InnerStruct.InnerStructInnerClass> innerStructInnerClassByInnerStructInnerStruct =
                new Dictionary<InnerStruct.InnerStructInnerStruct,InnerStruct.InnerStructInnerClass>();
            Func<InnerAbstractClass, InnerAbstractClass.InnerAbstractClassInnerEnum, InnerAbstractClass.IInnerAbstractClassInnerInterface> getInnerAbstractClass =
                (InnerAbstractClass @class, InnerAbstractClass.InnerAbstractClassInnerEnum @enum) => new InnerImplementingClass();
            List<Dictionary<InnerAbstractClass.InnerAbstractClassStruct, IEnumerable<InnerImplementingClass[]>>> stuff =
                new List<Dictionary<InnerAbstractClass.InnerAbstractClassStruct,IEnumerable<InnerImplementingClass[]>>>();

            string toStringHolder;

            toStringHolder = tuple.ToString();
            toStringHolder = tuple.Item1.ToString();
            toStringHolder = tuple.Item2.ToString();
            toStringHolder = tuple.Item3.ToString();
            toStringHolder = innerEnums.ToString();
            toStringHolder = innerEnums.First().ToString();
            toStringHolder = innerStructs.ToString();
            toStringHolder = innerStructs[0].ToString();
            toStringHolder = innerStructInnerEnum.ToString();
            toStringHolder = innerStructInnerEnum.Value.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Keys.First().ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Values.First().ToString();
            toStringHolder = getInnerAbstractClass.ToString();
            toStringHolder = stuff.ToString();
            toStringHolder = stuff[0].ToString();
            toStringHolder = stuff[0].Keys.First().ToString();
            toStringHolder = stuff[0].Values.First().ToString();
            toStringHolder = stuff[0].Values.First().First().ToString();
        }
Пример #46
0
		public void ListToString_EmptyList()
		{
			Dictionary<string, int> list = new Dictionary<string, int>();
			Assert.AreEqual(string.Empty, list.ToString(Environment.NewLine, item => item.Key));
		}
Пример #47
0
        public Dictionary<string, string> getFileData(string path)
        {
            Process ffprobe = new Process();
            //Run the thing.
            ffprobe.StartInfo.FileName = "ffprobe.exe";
            ffprobe.StartInfo.UseShellExecute = false;
            ffprobe.StartInfo.RedirectStandardOutput = true;
            ffprobe.StartInfo.RedirectStandardError = true;
            ffprobe.StartInfo.CreateNoWindow = true;
            ffprobe.StartInfo.Arguments = "-v quiet -print_format compact=p=0 -show_format " + "\"" + Path.GetFullPath(path) + "\"";

            Dictionary<string, string> output = new Dictionary<string, string>();

            ffprobe.Start();

            using (StreamReader reader = ffprobe.StandardOutput)
            {
                string result = reader.ReadToEnd();
                //result = result.Substring(result.IndexOf("Duration: "));

                //Split the output.
                string[] splits = result.Split('|');

                foreach(string s in splits)
                {
                    string[] items = s.Split('=');
                    output.Add(items[0], items[1]);
                }

                Console.WriteLine(output.ToString());

                //TODO: Move this to it's own setup method with the rest of them.
                //Put the info in the box. WHY NOT?
                infoList.Text = result.Replace('|', '\n');

                runtime = TimeSpan.FromSeconds((Double.Parse(output["duration"])));
                fileRuntime.Text = runtime.ToString().TrimEnd('0');

                numHour.Maximum = runtime.Hours; //TODO: Sanity check for start time.
            }

            return output;
        }
Пример #48
0
 public override String ToString()
 {
     // poor man's toString()
     IDictionary<String, Object> bld = new Dictionary<String, Object>();
     bld["MaxObjects"] = MaxObjects;
     bld["MaxIdle"] = MaxIdle;
     bld["MaxWait"] = MaxWait;
     bld["MinEvictableIdleTimeMillis"] = MinEvictableIdleTimeMillis;
     bld["MinIdle"] = MinIdle;
     return bld.ToString();
 }
Пример #49
0
 private void UpdateCurrentVersionFile(Dictionary<string, string> version)
 {
     try
     {
         Utils.DeleteFile(logger, Settings.ConfigDir + "\\" + CurrentVersionFileName);
         FileStream versionFile = new FileStream(Settings.ConfigDir + "\\" + CurrentVersionFileName, FileMode.OpenOrCreate);
         foreach (string fileName in version.Keys)
         {
             string nameHashPair = fileName + "," + version[fileName] + ";";
             versionFile.Write(System.Text.Encoding.ASCII.GetBytes(nameHashPair), 0, System.Text.Encoding.ASCII.GetByteCount(nameHashPair));
         }
         versionFile.Close();
     }
     catch (Exception e)
     {
         Utils.structuredLog(logger, "E", e.Message + ". UpdateCurrentVersionFile, version: " + version.ToString());
     }
 }
Пример #50
0
 public BasicDataStatic(string colloq,
     bool? consumeOnFull,
     bool? consumed,
     int? depth,
     string description,
     JArray fromA,
     JObject goldO,
     string group,
     bool? hideFromAll,
     int id,
     JObject imageO,
     bool? inStore,
     JArray intoA,
     JObject maps,
     string name,
     string plainText,
     string requiredChampion,
     JObject runeO,
     string sanitizedDescription,
     int? specialRecipe,
     int? stacks,
     JObject statsO,
     JArray tagsA)
 {
     from = new List<string>();
     into = new List<string>();
     this.maps = new Dictionary<string, bool>();
     tags = new List<string>();
     this.colloq = colloq;
     this.consumeOnFull = consumeOnFull;
     this.consumed = consumed;
     this.depth = depth;
     this.description = description;
     if (fromA != null)
     {
         this.from = HelperMethods.LoadStrings(fromA);
     }
     if (goldO != null)
     {
         LoadGold(goldO);
     }
     this.group = group;
     this.hideFromAll = hideFromAll;
     this.id = id;
     if (imageO != null)
     {
         this.image = HelperMethods.LoadImageStatic(imageO);
     }
     this.inStore = inStore;
     if (intoA != null)
     {
         this.into = HelperMethods.LoadStrings(intoA);
     }
     if (maps != null)
     {
         this.maps = JsonConvert.DeserializeObject<Dictionary<string, bool>>(maps.ToString());
     }
     this.name = name;
     this.plainText = plainText;
     this.requiredChampion = requiredChampion;
     if (runeO != null)
     {
         this.rune = HelperMethods.LoadMetaDataStatic(runeO);
     }
     this.sanitizedDescription = sanitizedDescription;
     this.stacks = stacks;
     if (statsO != null)
     {
         LoadBasicDataStats(statsO);
     }
     if (tagsA != null)
     {
         this.tags = HelperMethods.LoadStrings(tagsA);
     }
 }
    void Update()
    {
        // Connect the socket to the remote endpoint. Catch any errors.
        try
        {
            /*// Encode the data string into a byte array.
            byte[] msg2 = Encoding.ASCII.GetBytes("Connected.");

            // Send the data through the socket.
            int bytesSent = socket.Send(msg2);*/

            // Receive the response from the remote device.
            int bytesRec;

            string fullMsg = "";
            while ((bytesRec = socket.Receive(bytes)) > 0)
            {
                fullMsg += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                if (fullMsg.EndsWith(";"))
                {
                    //We have a full message
                    MatchCollection matches = Regex.Matches(fullMsg, @"([^\{\w\d\s]?)([\w\d]+)(\s+)?(=>)(\s+)?([\w\d+-]+)");
                    var messageRecieved = new Dictionary<String, String>();

                    foreach (Match match in matches)
                    {
                        String leftSideRegex = @"[\w\d]+(?=(\s+(=>)))";
                        String rightSideRegex = @"(?<=(=>(\s+)))[\+\-\d\w]+";

                        messageRecieved[Regex.Match(match.Value, leftSideRegex).Value.ToLower()] = Regex.Match(match.Value, rightSideRegex).Value.ToLower();
                    }

                    switch (messageRecieved["type"])
                    {
                        case "command":
                            switch (messageRecieved["command"])
                            {
                                case "let_there_be":
                                    Debug.Log(messageRecieved.ToString());
                                    string objectToCreate = messageRecieved["object"];
                                    float radius = float.Parse(messageRecieved["radius"]);
                                    float angleXY = float.Parse(messageRecieved["anglexy"]);
                                    float angleYZ = float.Parse(messageRecieved["angleyz"]);
                                    int orbits = int.Parse(messageRecieved["orbits"]);
                                    int idOfObject = int.Parse(messageRecieved["createdid"]);

                                    GameObject newGameObject = createGameObject(objectToCreate, radius, angleXY, angleYZ);
                                    Orbit orbitComponent = newGameObject.AddComponent<Orbit>();
                                    if (orbits != -1)
                                    {
                                        newGameObject.transform.position += idMap[orbits].transform.position;
                                        orbitComponent.orbitCenter = idMap[orbits];
                                    }
                                    else orbitComponent.orbitCenter = Camera.main.gameObject;

                                    orbitComponent.setupAxis(angleXY, angleYZ);
                                    orbitComponent.orbitPeriod = UnityEngine.Random.Range(30, 60);

                                    idMap[idOfObject] = newGameObject;

                                    break;
                            }

                            break;
                    }

                    //Reset stuff for next msg
                    bytes = new byte[1024];
                    fullMsg = "";
                }
            }
        }
        catch (ArgumentNullException ane)
        {
            Debug.Log("ArgumentNullException : {0}" + ane.ToString());
        }
        catch (SocketException se)
        {
            //Debug.Log("SocketException : {0}" + se.ToString());
        }
        catch (Exception e)
        {
            Debug.Log("Unexpected exception : {0}" + e.ToString());
        }
    }
Пример #52
0
        public void ParseTemp(String filename)
        {
            LinkedList<string>  current_parent = new LinkedList<string>();
            int level = 0;
            Dictionary<string, List<string>> parents = new Dictionary<string, List<string>>();
            List<Sample> samples = new List<Sample>();
            Sample  s = null;
            bool new_level = false;
            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read ))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using(StreamReader sr = new StreamReader(bs))
                    {
                        String line = sr.ReadLine();
                        while(line != null){
                            if(line.StartsWith("4-"))
                            {
                                if(s != null)
                                {
                                    samples.Add(s);
                                }
                                s = new Sample();
                                //Is Tree Parent

                                line = sr.ReadLine();
                                if(line.StartsWith("3-"))
                                {
                                    line =  line.Replace("3- ", "");
                                    if(String.IsNullOrWhiteSpace(line))
                                    {
                                        //First of tree pivot
                                        line = sr.ReadLine();
                                        line =  line.Replace("3- ", "");
                                        s.Name = line;
                                        s.Text = line;
                                        s.Description = line;
                                        if(current_parent.Count > 0){
                                            //s.Parent = current_parent.First.Value;
                                            s.Parent = Parents( current_parent);
                                        }else{
                                            s.Parent = "";
                                        }
                                        samples.Add(s);
                                        s = null;
                                        current_parent.AddFirst(line);
                                    }else{
                                        current_parent.RemoveFirst();
                                        s.Name = line;
                                        s.Text = line;
                                        s.Description = line;
                                        //s.Parent = Parents( current_parent.First.Value;
                                        s.Parent = Parents( current_parent);
                                        samples.Add(s);
                                        s = null;
                                        current_parent.AddFirst(line);
                                    }
                                }
                            }
                            else if(line.StartsWith("3-") )
                            {
                                if(s != null)
                                {
                                    samples.Add(s);
                                }
                                s = new Sample();
                                line =  line.Replace("3- ", "");
                                if(String.IsNullOrWhiteSpace(line))
                                {
                                    //First of tree pivot
                                    line = sr.ReadLine();
                                    while(!String.IsNullOrWhiteSpace(line))
                                    {
                                        if(line.StartsWith("3-"))
                                        {
                                            line = line.Replace("3-", "");
                                            break;
                                        }
                                        if(line.StartsWith("2-"))
                                        {
                                            line = line.Replace("2-", "");
                                            break;
                                        }
                                        line = sr.ReadLine();
                                    }
                                }
                                line = line.Trim();
                                s.Name = line;
                                s.Description = line;
                                //s.Parent = current_parent.First.Value;
                                s.Parent = Parents( current_parent);
                                sr.ReadLine();
                                sr.ReadLine();
                                sr.ReadLine();
                                sr.ReadLine();
                            }
                            else if(line.StartsWith("2-"))
                            {
                                if(s != null)
                                {
                                    samples.Add(s);
                                }
                                s = new Sample();
                                line =  line.Replace("2- ", "");
                                if(String.IsNullOrWhiteSpace(line))
                                {
                                    //First of tree pivot
                                    line = sr.ReadLine();
                                    while(!String.IsNullOrWhiteSpace(line))
                                    {
                                        if(line.StartsWith("3-"))
                                        {
                                            line = line.Replace("3-", "");
                                            break;
                                        }
                                        if(line.StartsWith("2-"))
                                        {
                                            line = line.Replace("2-", "");
                                            break;
                                        }
                                        line = sr.ReadLine();
                                    }
                                }
                                line = line.Trim();
                                s.Name = line;
                                s.Description = line;
                                //s.Parent = current_parent.First.Value;
                                s.Parent = Parents( current_parent);
                                sr.ReadLine();
                                sr.ReadLine();
                                sr.ReadLine();
                                sr.ReadLine();

                            }else{
                                if(s != null)
                                {
                                    s.Text += line;
                                    s.Text += System.Environment.NewLine;
                                }
                            }
                            line = sr.ReadLine();
                        }
                    }
                }
            }
            if(s != null)
            {
                samples.Add(s);
            }
            foreach(Sample ss in samples)
            {
                ss.Update(true);
            }
            parents.ToString();
        }
Пример #53
0
        public void GetParam_Tuple(object param)
        {
            WriteXmlAndXslFiles();

            object t = null;
            switch ((int)param)
            {
                case 1: t = Tuple.Create(1, "Melitta", 7.5); break;
                case 2: t = new TestDynamicObject(); break;
                case 3: t = new Guid(); break;
                case 4: t = new Dictionary<string, object>(); break;
            }
            _output.WriteLine(t.ToString());

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load("type.xsl");

            XsltArgumentList xslArg = new XsltArgumentList();
            xslArg.AddParam("param", "", t);
            xslArg.AddExtensionObject("", t);

            try
            {
                xslt.Transform("type.xml", xslArg, new StringWriter());
            }
            catch (Exception e)
            {
                _output.WriteLine(e.Message);
                return;
            }
            Assert.True(false);
        }
Пример #54
0
        public void var_types(int param)
        {
            WriteXmlAndXslFiles();

            object t = null;
            switch (param)
            {
                case 1: t = Tuple.Create(1, "Melitta", 7.5); break;
                //case 2: t = new TestDynamicObject(); break;
                case 3: t = new Guid(); break;
                case 4: t = new Dictionary<string, object>(); break;
            }
            _output.WriteLine(t.ToString());

#pragma warning disable 0618
            XslTransform xslt = new XslTransform();
#pragma warning restore 0618
            xslt.Load("type.xsl");

            XsltArgumentList xslArg = new XsltArgumentList();
            xslArg.AddParam("param", "", t);
            xslArg.AddExtensionObject("", t);

            XPathDocument xpathDom = new XPathDocument("type.xml");
            using (StringWriter sw = new StringWriter())
            {
                xslt.Transform(xpathDom, xslArg, sw);
                _output.WriteLine(sw.ToString());
            }
            return;
        }
    public void OnIgniteLeaderBoard( Dictionary<string,object> leaderBoardDict )
    {
        Debug.Log( "FuelSDKGrooveIntegration - OnIgniteLeaderBoard called." );
        if( leaderBoardDict.ContainsKey( "id" ) ) {
            string id = Convert.ToString( leaderBoardDict["id"] );
            events[id].LoadActivityData( leaderBoardDict );

            Debug.Log ("FuelSDKGrooveIntegration - LD = " + leaderBoardDict.ToString ());
        }
    }
    public override string UpdateRow()
    {
        LogCallMethod(true);
        string returnID = string.Empty;
        using (SqlConnection con = new SqlConnection(DataServices.ConnectString))
        {
            con.Open();
            SqlTransaction sqlTran = con.BeginTransaction();
            try
            {
                Dictionary<string, object> SALE_movingValues = new Dictionary<string, object>
                {
                        {"stockMovingNo", ctrlMa.Text},
                        {"fromStockID",cmbfromStock.Value},
                        {"toStockID",cmbtoStock.Value},
                        {"fromStockStaffID",cmbfromStaff.Value},
                        {"toStockStaffID",cmbtoStaff.Value},
                        {"notes", txtNotes.Text},
                        {"quantity",CU.GetSpinValue(totalQuantity)},
                        {"dateMoved", CU.GetDateEditValue(dtorderdate)}
                };
                //lay invoiceID cua SALE_invoice
                var stockMovingKey = new Dictionary<string, object>
                {
                    {"stockMovingID",globalID}
                };

                EU.updateTblScript(sqlTran, "SM_moving", SALE_movingValues, stockMovingKey);

                var movingWheres = new Dictionary<string, object>
                {
                    {"sessionKey", globalSessionKey},
                };
                var mappingSALE_temptoSM_moving_details = new Dictionary<string, object>
                {       //Details ====== temp
                        {"productID", "productID"},
                        {"currentPrice", "currentPrice"},
                        {"quantity", "quantity"},

                        {"note","notes"},
                        {"orderNum", "oderNumber"},

                        {"boID", "boID"},
                        {"userID", "userID"},
                        {"dateCreated", "dateCreated"},
                        {"sessionKey", "sessionKey"}
                };
                EU.MovingTableTemToDetails(sqlTran, "SM_moving_details", "SALE_temp", stockMovingKey, mappingSALE_temptoSM_moving_details, movingWheres, true);
                sqlTran.Commit();
                returnID = stockMovingKey.ToString();
            }
            catch (Exception ex)
            {
                sqlTran.Rollback();
                LogAction(0, ex.ToString());
                returnID = "error - " + ex.ToString();
            }
        }
        LogCallMethod(false);
        return returnID;
    }
Пример #57
0
 public override string ToString()
 {
     StringBuilder bld = new StringBuilder();
     bld.Append("ScriptContext: ");
     // poor man's to string method.
     IDictionary<string, object> map = new Dictionary<string, object>();
     map["Language"] = ScriptLanguage;
     map["Text"] = ScriptText;
     map["Arguments"] = ScriptArguments;
     bld.Append(map.ToString());
     return bld.ToString();
 }
Пример #58
0
        public Dictionary<string, object> Decrypt(Dictionary<string, object> msg)
        {
            if (msg == null)
            {
                throw new ArgumentNullException("msg");
            }

            if (msg["session_id"] == null)
            {
                Logger.Info("Missing session ID in {0}", msg.ToString());
                return null;
            }

            if (msg["encrypted_data"] == null)
            {
                Logger.Info("Missing encrypted data in {0}", msg.ToString());
                return null;
            }

            string messageSessionId = msg["session_id"] as string;
            string replyTo = msg["reply_to"] as string;

            EncryptionHandler encryptionHandler = LookupEncryptionHandler(new Dictionary<string, string>() { { "session_id", messageSessionId } });

            // save message handler for the reply
            this.SessionReplyMap[replyTo] = encryptionHandler;

            // Log exceptions from the EncryptionHandler, but stay quiet on the wire.
            try
            {
                msg = encryptionHandler.Decrypt(msg["encrypted_data"]);
            }
            catch (Exception ex)
            {
                LogEncryptionError(ex);
                return null;
            }

            msg["reply_to"] = replyTo;

            Logger.Info("Decrypted Message: #{msg}");
            return msg;
        }
Пример #59
0
		public void ProcessPushNotification(Dictionary <string, string> data)
		{
			System.Diagnostics.Debug.WriteLine ("Received a push notification " + data.ToString());
			MessagingCenter.Send<Xamarin.Forms.Application> (App.Current, "refresh_menu");
		}
Пример #60
0
 public override String ToString()
 {
     IDictionary<String, Object> values = new Dictionary<String, Object>();
     values["Token"] = _token;
     values["DeltaType"] = _deltaType;
     values["PreviousUid"] = _previousUid;
     values["ObjectClass"] = _objectClass;
     values["Uid"] = _uid;
     values["Object"] = _object;
     return values.ToString();
 }