public void PackInclude_is_null_when_it_is_not_set_in_the_ProjectJson()
        {
            var json = new JObject();
            var project = GetProject(json);

            project.PackOptions.PackInclude.Should().BeNull();
        }
        internal static XbmcAlbum FromJson(JObject obj)
        {
            if (obj == null)
            {
                return null;
            }

            try
            {
                return new XbmcAlbum(JsonRpcClient.GetField<int>(obj, "albumid"),
                                     JsonRpcClient.GetField<string>(obj, "thumbnail"),
                                     JsonRpcClient.GetField<string>(obj, "fanart"),
                                     JsonRpcClient.GetField<string>(obj, "album_title"),
                                     JsonRpcClient.GetField<string>(obj, "album_artist"),
                                     JsonRpcClient.GetField<int>(obj, "year"),
                                     JsonRpcClient.GetField<int>(obj, "album_rating"),
                                     JsonRpcClient.GetField<string>(obj, "album_genre", string.Empty),
                                     JsonRpcClient.GetField<string>(obj, "album_mood", string.Empty),
                                     JsonRpcClient.GetField<string>(obj, "album_theme", string.Empty),
                                     JsonRpcClient.GetField<string>(obj, "album_style", string.Empty),
                                     JsonRpcClient.GetField<string>(obj, "album_type", string.Empty),
                                     JsonRpcClient.GetField<string>(obj, "album_label", string.Empty),
                                     JsonRpcClient.GetField<string>(obj, "album_description", string.Empty));
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Example #3
1
        public static JObject ToJSON(this QueryResult myQueryResult)
        {
            // root element...
            var _Query = new JObject();

            // query --------------------------------
            _Query.Add(new JProperty("query", myQueryResult.Query));

            // result -------------------------------
            _Query.Add(new JProperty("result", myQueryResult.ResultType.ToString()));

            // duration -----------------------------
            _Query.Add(new JProperty("duration", new JArray(myQueryResult.Duration, "ms")));

            // warnings -----------------------------
            _Query.Add(new JProperty("warnings", new JArray(
                from _Warning in myQueryResult.Warnings
                select new JObject(
                         new JProperty("code", _Warning.GetType().ToString()),
                         new JProperty("description", _Warning.ToString())
                       ))));

            // errors -------------------------------
            _Query.Add(new JProperty("errors", new JArray(
                from _Error in myQueryResult.Errors
                select new JObject(
                         new JProperty("code", _Error.GetType().ToString()),
                         new JProperty("description", _Error.ToString())
                       ))));

            // results ------------------------------
            _Query.Add(new JProperty("results", new JArray(GetJObjectsFromResult(myQueryResult.Vertices))));

            return _Query;
        }
Example #4
1
        public JObject CreateEDDNMessage(JournalFSDJump journal)
        {
            if (!journal.HasCoordinate)
                return null;

            JObject msg = new JObject();

            msg["header"] = Header();
            msg["$schemaRef"] = "http://schemas.elite-markets.net/eddn/journal/1/test";

            JObject message = new JObject();

            message["StarSystem"] = journal.StarSystem;
            message["Government"] = journal.Government;
            message["timestamp"] = journal.EventTimeUTC.ToString("yyyy-MM-ddTHH:mm:ssZ");
            message["Faction"] = journal.Faction;
            message["Allegiance"] = journal.Allegiance;
            message["StarPos"] = new JArray(new float[] { journal.StarPos.X, journal.StarPos.Y, journal.StarPos.Z });
            message["Security"] = journal.Security;
            message["event"] = journal.EventTypeStr;
            message["Economy"] = journal.Economy;

            msg["message"] = message;
            return msg;
        }
        public IEnumerable<JObject> ReadElement(IAixmConverter converter, JObject currentObject, XElement element)
        {
            currentObject.AddToProperties("elevation", JObject.FromObject(element));

            //If not a feature return null;
            return Enumerable.Empty<JObject>();
        }
		private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer)
		{
			JToken typeToken;
			serializer.TypeNameHandling = TypeNameHandling.None;
			if (po.TryGetValue("type", out typeToken))
			{
				var type = typeToken.Value<string>().ToLowerInvariant();
				switch (type)
				{
					case "string":
						return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
					case "float":
					case "double":
					case "byte":
					case "short":
					case "integer":
					case "long":
						return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
					case "date":
						return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
					case "boolean":
						return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
					case "binary":
						return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
				}
			}
			return null;
		}
Example #7
1
 public ItemListStatic(JObject basicO,
     JObject dataO,
     JArray groupsA,
     JArray treeA,
     string type,
     string version,
     JObject originalObject)
 {
     data = new Dictionary<string, ItemStatic>();
     groups = new List<GroupStatic>();
     tree = new List<ItemTreeStatic>();
     if (basicO != null)
     {
         basic = HelperMethods.LoadBasicDataStatic(basicO);
     }
     if (dataO != null)
     {
         LoadData(dataO.ToString());
     }
     if (groupsA != null)
     {
         LoadGroups(groupsA);
     }
     if (treeA != null)
     {
         LoadTree(treeA);
     }
     this.type = type;
     this.version = version;
     this.originalObject = originalObject;
 }
Example #8
1
 private static bool HasRed(JObject jObject)
 {
     return jObject.Properties()
         .Select(x => x.Value)
         .OfType<JValue>()
         .Any(x => x.Value<string>() == "red");
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     Response.Clear();
     var obj = new JObject(new JProperty("machineName", ServerManager.MachineName), new JProperty("servers", JArray.FromObject(ServerManager.GetActiveServerList())));
     Response.BinaryWrite(Encoding.UTF8.GetBytes(obj.ToString()));
     Response.End();
 }
		public static int BetRequest(JObject jsonState)
		{
			int bet = 0;
			var gameState = JsonConvert.DeserializeObject<GameState>(jsonState.ToString());
            try
			{
				string actualDecision = "none";
				Logger.LogHelper.Log("type=bet_begin action=bet_request request_id={0} game_id={1}", requestId, gameState.GameId);

				foreach (IDecisionLogic decisionLogic in Decisions.DecisionFactory.GetDecisions())
                {
                    //végigpróbáljuk a lehetőségeket
                    int? possibleBet = decisionLogic.MakeADecision(gameState);
                    if (possibleBet.HasValue)
                    {
                        bet = possibleBet.Value;
						actualDecision = decisionLogic.GetName();
                        break;
                    }
				}

				string cards = String.Join(",", gameState.OwnCards);
				Logger.LogHelper.Log("type=bet action=bet_request request_id={0} game_id={1} bet={2} cards={3} decision={4}",
					requestId, gameState.GameId, bet, cards, actualDecision);
            }
            catch (Exception ex)
            {
				Logger.LogHelper.Error("type=error action=bet_request request_id={0} game_id={1} error_message={2}",requestId, gameState.GameId, ex);
            }

			return bet;
		}
Example #11
0
 JObject newCategory(string _category)
 {
     JObject category = new JObject(
         new JProperty("name",_category)
         );
     return category;
 }
Example #12
0
        private static JObject CreateCaseNote(string caseGuidId, string text)
        {
            var caseNoteData = new JObject { { "CaseGuidId", caseGuidId }, { "Text", text } };
            var createCase = new JObject { { "at", "-0.0:0:0.0" }, { "name", "CreateCaseNote" }, { "value", caseNoteData } };

            return createCase;
        }
Example #13
0
        /// <summary>
        /// Validation logic for registered claim: JWT ID.
        /// Successful if claim is present and resolves to true when passed through the provided validator.
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="variables"></param>
        /// <returns></returns>
        public bool Check(JObject claims, ClaimsCheckerVariables variables)
        {
            var jsonJti = claims[RegisteredClaimNames.JwtId];
            if (jsonJti == null) return false;

            return JwtIdValidator(jsonJti.ToString());
        }
Example #14
0
 JObject newLegend(string[] _legend)
 {
     JObject legend = new JObject(
         new JProperty("data", _legend)
         );
     return legend;
 }
        public HttpResponseMessage AddMasterFieldToDataset(JObject jsonData)
        {
            var db = ServicesContext.Current;
            dynamic json = jsonData;

            int DatasetId = json.DatasetId.ToObject<int>();
            var dataset = db.Datasets.Find(DatasetId);

            int FieldId = json.FieldId.ToObject<int>();
            var field = db.Fields.Find(FieldId);

            DatasetField df = new DatasetField();

            df.DatasetId = dataset.Id;
            df.FieldId = field.Id;
            df.FieldRoleId = FieldRole.DETAIL;
            df.CreateDateTime = DateTime.Now;
            df.Label = field.Name;
            df.DbColumnName = field.DbColumnName;
            df.SourceId = 1;
            df.ControlType = field.ControlType;

            db.DatasetFields.Add(df);
            db.SaveChanges();

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        public async Task UpdateAsync(JObject instance)
        {
            string id = EnsureIdIsString(instance);
            instance = RemoveSystemPropertiesKeepVersion(instance);

            await this.syncContext.UpdateAsync(this.TableName, this.Kind, id, instance);
        }
Example #17
0
        public async Task ApplyConfiguration(JToken configJson)
        {
            var config = new ConfigurationDataBasicLogin();
            config.LoadValuesFromJson(configJson);
           
            var pairs = new Dictionary<string, string> {
				{ "username", config.Username.Value },
				{ "password", config.Password.Value }
			};

            var content = new FormUrlEncodedContent(pairs);

            var response = await client.PostAsync(LoginUrl, content);
            var responseContent = await response.Content.ReadAsStringAsync();

            if (!responseContent.Contains("logout.php"))
            {
                CQ dom = responseContent;
                var errorMessage = dom["td.text"].Text().Trim();
                throw new ExceptionWithConfigData(errorMessage, (ConfigurationData)config);
            }
            else
            {
                var configSaveData = new JObject();
                cookies.DumpToJson(SiteLink, configSaveData);
                SaveConfig(configSaveData);
                IsConfigured = true;
            }
        }
        public int TotalSize { protected set; get; } // set during fetch

        /// <summary>
        ///     Build SyncTarget from json
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static SyncDownTarget FromJson(JObject target)
        {
            if (target == null) return null;
            JToken impl;
            if (target.TryGetValue(WindowsImpl, out impl))
            {
                JToken implType;
                if (target.TryGetValue(WindowsImplType, out implType))
                {
                    try
                    {
                        Assembly assembly = Assembly.Load(new AssemblyName(impl.ToObject<string>()));
                        Type type = assembly.GetType(implType.ToObject<string>());
                        if (type.GetTypeInfo().IsSubclassOf(typeof(SyncTarget)))
                        {
                            MethodInfo method = type.GetTypeInfo().GetDeclaredMethod("FromJson");
                            return (SyncDownTarget)method.Invoke(type, new object[] { target });
                        }
                    }
                    catch (Exception)
                    {
                        throw new SmartStoreException("Invalid SyncDownTarget");
                    }
                }
            }
            throw new SmartStoreException("Could not generate SyncDownTarget from json target");
        }
 public ContentTypeDefinition(string name, string displayName, IEnumerable<ContentTypePartDefinition> parts, JObject settings)
 {
     Name = name;
     DisplayName = displayName;
     Parts = parts.ToList();
     Settings = settings;
 }
Example #20
0
        public async Task<HttpResponseMessage> PutComment(Comment comment)
        {
            JObject result = new JObject();
            if (!ModelState.IsValid)
            {                
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
            }

            db.Entry(comment).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CommentExists(comment.Id))
                {
                    result = Methods.CustomResponseMessage(0, "Comment isn't exists!");
                    return Request.CreateResponse(HttpStatusCode.NotFound, result);
                }
                else
                {
                    throw;
                }
            }

            result = Methods.CustomResponseMessage(0, "Update Comment is successful!");
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
Example #21
0
 internal override void parseJObject(JObject obj)
 {
     base.parseJObject(obj);
     JToken token = obj.GetValue("PredefinedType", StringComparison.InvariantCultureIgnoreCase);
     if (token != null)
         Enum.TryParse<IfcAirTerminalTypeEnum>(token.Value<string>(), true, out mPredefinedType);
 }
Example #22
0
        public async static Task<bool> Ping(ConnectionItem connectionItem)
        {
            JObject requestObject = new JObject(
                new JProperty("jsonrpc", "2.0"),
                new JProperty("id", 234),
                new JProperty("method", "JSONRPC.ping"));
                
            string requestData = requestObject.ToString();

            HttpClientHandler handler = new HttpClientHandler();
            HttpClient httpClient = new HttpClient(handler);
            string uriString = "http://" + connectionItem.IpAddress + ":" + connectionItem.Port.ToString() + "/jsonrpc?request=";
            httpClient.BaseAddress = new Uri(uriString);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");

            request.Content = new StringContent(requestData);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //Required to be recognized as valid JSON request.

            HttpResponseMessage response = await httpClient.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();
            if (responseString.Length == 0)
                return false;
            dynamic responseObject = JObject.Parse(responseString);
            bool isSuccessful = responseObject.result == "pong";
            return isSuccessful;
        }
 public void LoadFromJson(JObject jsonData)
 {
     string tempTriggerKey = (string)jsonData["trigger key"];         // Load String from json
     VirtualKeyCode vkCode = KeyTranslater.GetKeyCode(tempTriggerKey); // Convert the string to a keycode using the Keytranslator
     triggerKey = (Keys)vkCode;                                        // Cast the Vkeycode to a key and save to the class
     commandWord = (string)jsonData["command word"];
 }
 public Event(int appId, string @event, string entityId, string entityType, string targetEntityId, string targetEntityType, Dictionary<string, object> properties)
 {
     this[Constants.AppId] = appId;
     this[Constants.Event] = @event;
     this[Constants.EntityType] = entityType;
     this[Constants.EntityId] = entityId;
     if (!string.IsNullOrWhiteSpace(targetEntityId))
     {
         this[Constants.TargetEntityId] = targetEntityId;
     }
     if (!string.IsNullOrWhiteSpace(targetEntityType))
     {
         this[Constants.TargetEntityType] = targetEntityType;
     }
     if (properties != null)
     {
         var jProperties = new JObject();
         foreach (var property in properties)
         {
             jProperties[property.Key] = JToken.FromObject(property.Value);
         }
         this[Constants.Properties] = jProperties;
     }
     this[Constants.EventTime] = new DateTimeAdapter().Serialize(DateTime.UtcNow);
 }
 public override void Load(JObject state)
 {
     base.Load(state);
     _value = (float)state.GetValue("Value");
     if (this._tracker != null)
         ((ConditionFloatTracker)_tracker).SetValue(_value, false);
 }
 public AuthenticationMessage(JObject jobject)
 {
     JObject contents = JObject.Parse(jobject.GetValue(MESSAGE_TYPE).ToString());
     this.username = contents.GetValue(USERNAME_KEY).ToString();
     this.password = contents.GetValue(PASSWORD_KEY).ToString();
     this.authenticated = Convert.ToBoolean(contents.GetValue(AUTHENTICATED_KEY).ToString());
 }
 public ContentTypeDefinition(string name, string displayName)
 {
     Name = name;
     DisplayName = displayName;
     Parts = Enumerable.Empty<ContentTypePartDefinition>();
     Settings = new JObject();
 }
 private IConnectionRequest Build(String typeName, JObject json, out Type type)
 {
     switch (typeName)
     {
         case "CreateTerminalRequest":
             type = typeof(CreateTerminalRequest);
             return new CreateTerminalRequest() {
                 TerminalType = json.Property("terminalType").Value.ToString(), 
                 CorrelationId = json.Property("correlationId").Value.ToString()
             };
         case "TerminalInputRequest":
             type = typeof(TerminalInputRequest);
             return new TerminalInputRequest()
             {
                 TerminalId = Guid.Parse(json.Property("terminalId").Value.ToString()),
                 Input = json.Property("input").Value.ToString(),
                 CorrelationId = Int32.Parse(json.Property("correlationId").Value.ToString())
             };
         case "CloseTerminalRequest":
             type = typeof(CloseTerminalRequest);
             return new CloseTerminalRequest()
             {
                 TerminalId = Guid.Parse(json.Property("terminalId").Value.ToString())
             };
     }
     type = null;
     throw new IOException("There is no suitable deserialization for this object");
 }
        public IHttpActionResult Post(JObject data)
        {
            dynamic json = data;
            var result = Captcha.Check((string)json.Captcha);

            if (json.bank == "" || json.fio == "" || json.email == "" || json.mailAddress == "" || json.phone == "" || json.position == "" || json.materials.Count == 0)
            {
                return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Заполните обязательные поля!"));
            }
            else
            {
                if (result == true)
                {
                    IList<Material> materials = json.materials.ToObject<IList<Material>>();

                    ApplicationMaterials application = new ApplicationMaterials()
                    {
                        Bank = json.bank,
                        FIO = json.fio,
                        MailAddress = json.mailAddress,
                        Phone = json.phone,
                        Position = json.position,
                        Materials = materials,
                        Email = json.email
                    };
                    Emailer.OrderMaterialsNotificate(application);
                    return Ok("Спасибо! Ваша заявка успешно отправлена.");
                }
                else
                {
                    return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Заполните капчу!"));
                }

            }
        }
Example #30
0
        public static void OnNotification(Newtonsoft.Json.Linq.JObject values)
        {
            string operazione = "";

            if (values["operazione"] != null)
            {
                operazione = values["operazione"].ToString();
            }

            switch (operazione)
            {
            case "attivaDispositivo":
                App.AttivaDispositivo();
                break;

            case "disattivaDispositivo":
                App.DisattivaDispositivo();
                break;
            }
        }
 public void ValuesToObjects_UnitTest()
 {
     Newtonsoft.Json.Linq.JObject jObject = default(Newtonsoft.Json.Linq.JObject);
     System.Func <Newtonsoft.Json.Linq.JToken, T> creator = default(System.Func <Newtonsoft.Json.Linq.JToken, T>);
     System.Collections.Generic.IReadOnlyList <T> _retVal = default(System.Collections.Generic.IReadOnlyList <T>);
     ExecuteMethod(
         () =>
     {
         jObject = new Newtonsoft.Json.Linq.JObject();
         creator = default(System.Func <Newtonsoft.Json.Linq.JToken, T>); //No Constructor
         ValuesToObjects_PreCondition(ref jObject, ref creator);
     },
         () =>
     {
         _retVal = DynCon.OSI.VSO.ReSTClient.JsonParsers.ValuesToObjects <object>(jObject, creator);
     },
         () =>
     {
         ValuesToObjects_PostValidate(jObject, creator, _retVal);
     });
 }
Example #32
0
        private void AddTags(Newtonsoft.Json.Linq.JObject json)
        {
            if (AddTag != null && AddTag.Length > 0)
            {
                for (int i = 0; i < AddTag.Length; i++)
                {
                    string value = ExpandField(AddTag[i], json);

                    JToken tags = json["tags"];
                    if (tags == null)
                    {
                        json.Add("tags", new JArray(value));
                    }
                    else
                    {
                        JArray a = tags as JArray;
                        a.Add(value);
                    }
                }
            }
        }
Example #33
0
 public Boolean DelteEmp([FromBody] Newtonsoft.Json.Linq.JObject value)
 {
     try
     {
         var          mystr  = JObject.Parse(value.ToString());
         int          id     = int.Parse(mystr["ID"].ToString());
         testEntities db     = new testEntities();
         Employee     objEmp = new Employee()
         {
             ID = id
         };
         db.Employees.Attach(objEmp);
         db.Employees.Remove(objEmp);
         db.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
Example #34
0
        void _hook_KeyPressed(object sender, KeyPressEventArgs e) //Событие нажатия клавиш
        {
            PictureBox pictureBox1 = new PictureBox();

            //это действие задаёт параметр расположения
            //изображения в pictureBox1
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

            //Делаем снимок экрана (изображение в памяти)
            Image pr = TakeScreenShot(Screen.PrimaryScreen);

            //Впихиваем изображение в pictureBox1
            pictureBox1.Image = pr;
            pr.Save(Environment.CurrentDirectory + "/tmp.jpg");

            string data = UploadFilesToRemoteUrl(JObject.Parse(GetMethod("photos.getMessagesUploadServer", new string[] { "peer_id=1" }, token))["response"]["upload_url"].ToString(), Environment.CurrentDirectory + "/tmp.jpg");

            Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(data);
            //MessageBox.Show(JObject.Parse(GetMethod("photos.saveMessagesPhoto", new string[] { "photo=" + obj["photo"], "server=" + obj["server"], "hash=" + obj["hash"] }, token))["response"][0].ToString());
            GetMethod("messages.send", new string[] { ("user_id=" + toolStripTextBox1.Text), "message=Отправлено из скриншотера", ("attachment=photo" + JObject.Parse(GetMethod("photos.saveMessagesPhoto", new string[] { "photo=" + obj["photo"], "server=" + obj["server"], "hash=" + obj["hash"] }, token))["response"][0]["owner_id"].ToString() + "_" + JObject.Parse(GetMethod("photos.saveMessagesPhoto", new string[] { "photo=" + obj["photo"], "server=" + obj["server"], "hash=" + obj["hash"] }, token))["response"][0]["id"].ToString()) }, token);
        }
Example #35
0
        public static void ETStatusUpdate(string ETid)
        {
            if (ETid == null)
            {
                return;
            }
            string file = System.Web.Hosting.HostingEnvironment.MapPath("~/TestData/") + @"/EventsAndTraining_June.json";
            string json = File.ReadAllText(file);

            Newtonsoft.Json.Linq.JObject ETObj = Newtonsoft.Json.Linq.JObject.Parse(json);
            for (int i = 0; i < ETObj["EventsAndTraining"].Count(); i++)
            {
                if (ETObj["EventsAndTraining"][i]["ETID"].ToString().Equals(ETid))
                {
                    ETObj["EventsAndTraining"][i]["UserAdded"] = !(bool)ETObj["EventsAndTraining"][i]["UserAdded"];
                    string FileOutput = Newtonsoft.Json.JsonConvert.SerializeObject(ETObj, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText(file, FileOutput);
                    break;
                }
            }
        }
Example #36
0
        private string BuildAnalyzeTypeInfo(Linq.JObject analyzeJObj)
        {
            Debug.Assert(analyzeJObj != null);
            string outputResult = "";

            var continueJObj = analyzeJObj["Continue"] as Linq.JObject;

            Debug.Assert(continueJObj != null);

            outputResult += BuildRecordInfo(continueJObj, "连续情况:" + NewLine_String);

            outputResult += NewLine_String + LineSeparator_String + NewLine_String;

            var stepJObj = analyzeJObj["Step"] as Linq.JObject;

            Debug.Assert(stepJObj != null);

            outputResult += BuildRecordInfo(stepJObj, "隔断情况:" + NewLine_String);

            return(outputResult);
        }
Example #37
0
        public void GetLabelList(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            MESDBHelper.OleExec SFCDB = this.DBPools["SFCDB"].Borrow();

            try
            {
                T_R_Label      TRL = new T_R_Label(SFCDB, DB_TYPE_ENUM.Oracle);
                List <R_Label> ret = TRL.GetLabelList(SFCDB);

                StationReturn.Data   = ret;
                StationReturn.Status = StationReturnStatusValue.Pass;
            }
            catch (Exception ee)
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000037";
                StationReturn.MessagePara.Add(ee.Message);
            }
            SFCDB.ThrowSqlExeception = false;
            this.DBPools["SFCDB"].Return(SFCDB);
        }
Example #38
0
        public string GetUserMoblie(string accesstoken, string userticket)
        {
            string postUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=" + accesstoken;

            StringBuilder sBuilder = new StringBuilder();

            sBuilder.Append("{");
            sBuilder.Append("\"user_ticket\":  \"" + userticket + "\"");
            sBuilder.Append("}");

            string jsonStr = sBuilder.ToString();

            byte[]         bytes   = Encoding.UTF8.GetBytes(jsonStr);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);

            request.Method        = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType   = "text/xml";
            Stream reqstream = request.GetRequestStream();

            reqstream.Write(bytes, 0, bytes.Length);

            //声明一个HttpWebRequest请求
            request.Timeout = 90000;
            //设置连接超时时间
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
            Stream          streamReceive = response.GetResponseStream();
            Encoding        encoding      = Encoding.UTF8;

            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string       strResult    = streamReader.ReadToEnd();

            streamReceive.Dispose();
            streamReader.Dispose();

            Newtonsoft.Json.Linq.JObject ja = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(strResult);

            return(ja["mobile"].ToString());
        }
        private System.Type GetObjectSubtypeBetter(Newtonsoft.Json.Linq.JObject jObject, System.Type objectType, string discriminator)
        {
            // TODO: Cleanup in 2.0.0, we should not have special cases where we need to prefix "Speckle" to things.
            // For now, we're going to stick to the following.

            // TODO: not elegant at all, should be broken up and recursified if needed.
            // This part makes sure that we deserialise to what we can - in case we get an object from a speckle kit that we do not posses, that nevertheless inherits from
            // an object that we do posses, we degrade to that (ie, GridLine -> Line).
            var pieces = discriminator.Split('/').ToList();

            pieces.Reverse();
            foreach (var piece in pieces)
            {
                var subtypePiece = piece;

                if (CachedTypes.ContainsKey(subtypePiece))
                {
                    return(CachedTypes[subtypePiece]);
                }

                var secondaryType = SpeckleCore.SpeckleInitializer.GetTypes().FirstOrDefault(t => t.Name == subtypePiece);

                if (secondaryType == null)
                {
                    subtypePiece  = "Speckle" + subtypePiece;
                    secondaryType = SpeckleCore.SpeckleInitializer.GetTypes().FirstOrDefault(t => t.Name == subtypePiece);
                }

                if (secondaryType != null)
                {
                    if (!CachedTypes.ContainsKey(subtypePiece))
                    {
                        CachedTypes.Add(subtypePiece, secondaryType);
                    }
                    return(secondaryType);
                }
            }

            throw new System.InvalidOperationException("Could not find subtype of '" + objectType.Name + "' with discriminator '" + discriminator + "'.");
        }
Example #40
0
    /// <summary>
    /// 获取指定币对价格
    /// </summary>
    public static int CoinPrice(string CoinPair)
    {
        string postdz = "https://openapi.factorde.com/open/api/get_ticker";

        System.Collections.Generic.Dictionary <String, String> myDi = new System.Collections.Generic.Dictionary <String, String>();
        myDi.Add("symbol", CoinPair);
        string rspp = PublicClass.GetFunction(postdz, myDi);

        Newtonsoft.Json.Linq.JObject stJson = Newtonsoft.Json.Linq.JObject.Parse(rspp);
        int            cg   = 0;
        SqlTransaction tran = null;
        SqlConnection  conn = DAL.DBHelper.SqlCon();

        conn.Open();
        tran = conn.BeginTransaction();
        try
        {
            string sql = "INSERT INTO CoinPriceList (CoinIndex,CoinPrice,updatetime) values('" + CoinPair + "'," + stJson["data"]["last"].ToString() + "," + DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + ") NowPrice='" + postdz + "'";
            cg = DAL.DBHelper.ExecuteNonQuery(tran, sql);

            if (cg > 0)
            {
                tran.Commit();
                conn.Close();
            }
            else
            {
                tran.Rollback();
                conn.Close();
            }
        }
        catch (Exception)
        {
            conn.Close();
        }



        return(cg);
    }
Example #41
0
        public void MergeTwoResponses()
        {
            var response1 = LoadJson <Dns.DTO.QueryComposer.QueryComposerResponseDTO>("Lpp.Dns.Api.Tests.Requests.Samples.DM1-response.json");
            var response2 = LoadJson <Dns.DTO.QueryComposer.QueryComposerResponseDTO>("Lpp.Dns.Api.Tests.Requests.Samples.DM2-response.json");

            IEnumerable <Dictionary <string, object> > r1 = response1.Results.First();

            Console.WriteLine("Result 1 count:" + r1.Count());
            IEnumerable <Dictionary <string, object> > r2 = response2.Results.First();

            Console.WriteLine("Result 2 count:" + r2.Count());
            Console.WriteLine("Total count:" + (r1.Count() + r2.Count()));

            IEnumerable <Dictionary <string, object> > combined = r1.Select(d => { d.Add("DataMart", "DM1"); return(d); }).Concat(r2.Select(d => { d.Add("DataMart", "DM2"); return(d); })).ToArray();

            Dns.DTO.QueryComposer.QueryComposerResponseDTO combinedResponse = new DTO.QueryComposer.QueryComposerResponseDTO();
            combinedResponse.ResponseDateTime = DateTime.UtcNow;
            combinedResponse.RequestID        = Guid.Empty;
            combinedResponse.Results          = new [] { combined };

            string mergedSerialized = Newtonsoft.Json.JsonConvert.SerializeObject(combinedResponse, Newtonsoft.Json.Formatting.None);

            System.IO.File.WriteAllText("merged-response.json", mergedSerialized);

            Newtonsoft.Json.Linq.JObject jobj = new Newtonsoft.Json.Linq.JObject();
            jobj.Add("prop1", new Newtonsoft.Json.Linq.JValue("23"));



            /**
             * Test Name:	MergeTwoResponses
             * Test Outcome:	Passed
             * Result StandardOutput:
             * Lpp.Dns.Api.Tests.Requests.Samples.DM1-response.json
             * Lpp.Dns.Api.Tests.Requests.Samples.DM2-response.json
             * Lpp.Dns.Api.Tests.Requests.Samples.request.json
             *
             *
             * */
        }
Example #42
0
        public void GetID(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            OleExec     sfcdb;
            T_R_Station station;
            string      ID = "";

            sfcdb = this.DBPools["SFCDB"].Borrow();
            try
            {
                station = new T_R_Station(sfcdb, DBTYPE);
                ID      = station.GetNewID(BU, sfcdb);
                StationReturn.Status      = StationReturnStatusValue.Pass;
                StationReturn.Data        = ID;
                StationReturn.MessageCode = "MES00000001";
                this.DBPools["SFCDB"].Return(sfcdb);
            }
            catch (Exception e)
            {
                this.DBPools["SFCDB"].Return(sfcdb);
                throw e;
            }
        }
Example #43
0
        public void GetSNStationKPList(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            MESDBHelper.OleExec SFCDB = this.DBPools["SFCDB"].Borrow();
            try
            {
                string strSN      = Data["SN"].ToString();
                string strSTATION = Data["STATION"].ToString();
                string strWO      = null;
                try
                {
                    strWO = Data["WO"].ToString();
                }
                catch
                { }

                LogicObject.SN SN = new LogicObject.SN();
                SN.Load(strSN, SFCDB, DB_TYPE_ENUM.Oracle);

                MESDataObject.Module.T_R_WO_BASE TWO = new T_R_WO_BASE(SFCDB, DB_TYPE_ENUM.Oracle);
                Row_R_WO_BASE RWO  = TWO.GetWo(SN.WorkorderNo, SFCDB);
                T_R_SN_KP     TRKP = new T_R_SN_KP(SFCDB, DB_TYPE_ENUM.Oracle);

                List <R_SN_KP> snkp = TRKP.GetKPRecordBySnIDStation(SN.ID, strSTATION, SFCDB);

                SN_KP ret = new SN_KP(snkp, SN.WorkorderNo, SN.SkuNo, SFCDB);


                StationReturn.Data   = ret;
                StationReturn.Status = StationReturnStatusValue.Pass;
            }
            catch (Exception ee)
            {
                //this.DBPools["SFCDB"].Return(SFCDB);
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000037";
                StationReturn.MessagePara.Add(ee.Message);
            }
            this.DBPools["SFCDB"].Return(SFCDB);
        }
Example #44
0
        public void QueryFailStation(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            OleExec          sfcdb = null;
            T_R_Station      station;
            List <R_Station> rList;

            try
            {
                sfcdb   = this.DBPools["SFCDB"].Borrow();
                station = new T_R_Station(sfcdb, DBTYPE);
                rList   = station.QueryFailStation(sfcdb);
                StationReturn.Status      = StationReturnStatusValue.Pass;
                StationReturn.MessageCode = "MES00000001";
                StationReturn.Data        = rList;
                this.DBPools["SFCDB"].Return(sfcdb);
            }
            catch (Exception e)
            {
                this.DBPools["SFCDB"].Return(sfcdb);
                throw e;
            }
        }
Example #45
0
        public void GetFileByName(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            MESDBHelper.OleExec SFCDB = this.DBPools["SFCDB"].Borrow();

            try
            {
                T_R_FILE TRF = new T_R_FILE(SFCDB, DB_TYPE_ENUM.Oracle);
                //R_FILE R = TRF.GetFileByName(Data["Name"].ToString(),Data["UseType"].ToString(),SFCDB );
                R_FILE R = TRF.GetFileByFileName(Data["Name"].ToString(), Data["UseType"].ToString(), SFCDB);

                StationReturn.Data   = R;
                StationReturn.Status = StationReturnStatusValue.Pass;
            }
            catch (Exception ee)
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000037";
                StationReturn.MessagePara.Add(ee.Message);
            }
            SFCDB.ThrowSqlExeception = false;
            this.DBPools["SFCDB"].Return(SFCDB);
        }
        public void JObjectToInstance_UnitTest()
        {
            Newtonsoft.Json.Linq.JObject jObject = default(Newtonsoft.Json.Linq.JObject);
            System.Func <Newtonsoft.Json.Linq.JObject, T> creator = default(System.Func <Newtonsoft.Json.Linq.JObject, T>);
            T _retVal = default(T);

            ExecuteMethod(
                () =>
            {
                jObject = new Newtonsoft.Json.Linq.JObject();
                creator = default(System.Func <Newtonsoft.Json.Linq.JObject, T>); //No Constructor
                JObjectToInstance_PreCondition(ref jObject, ref creator);
            },
                () =>
            {
                _retVal = DynCon.OSI.VSO.ReSTClient.JsonParsers.JObjectToInstance <object>(jObject, creator);
            },
                () =>
            {
                JObjectToInstance_PostValidate(jObject, creator, _retVal);
            });
        }
Example #47
0
        static JArray CallScript(byte[] script)
        {
            if (wc == null)
            {
                wc = new System.Net.WebClient();
            }
            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "invokescript";
            var _params = new Newtonsoft.Json.Linq.JArray();

            _params.Add(ThinNeo.Helper.Bytes2HexString(script));
            upparam["params"] = _params;

            var info   = wc.UploadString(url, upparam.ToString());
            var result = JObject.Parse(info)["result"]["stack"] as JArray;

            return(result);
            //Console.WriteLine(info);
        }
Example #48
0
        public async Task WeatherNowIntent(IDialogContext context, LuisResult result)
        {
            if (result.Entities.Count > 0)
            {
                string city          = result.Entities[0].Entity;
                string weatherResult = await GetCurrentWeather(result.Entities[0].Entity);

                Newtonsoft.Json.Linq.JObject jsonResult = JObject.Parse(weatherResult);

                string conditions  = jsonResult["data"][0]["weather"]["description"].ToString();
                string temperature = jsonResult["data"][0]["temp"].ToString();
                await context.SayAsync($"Das aktuelle Wetter in {city} kann so zusammengefasst werden: {conditions}, {temperature}°.");

                context.Wait(MessageReceived);
            }
            else
            {
                await context.SayAsync($"Leider könnte ich nichts dazu finden!");

                context.Wait(MessageReceived);
            }
        }
Example #49
0
        static void ConvertAttachStringToObject(Newtonsoft.Json.Linq.JObject token)
        {
            //处理"msg_attach"值,该json原始值是一个string,需要转换为json object
            var attachmentToken = token.SelectToken(NIMIMMessage.AttachmentPath);

            if (attachmentToken == null)
            {
                return;
            }

            if (attachmentToken.Type == Newtonsoft.Json.Linq.JTokenType.String)
            {
                var attachValue = attachmentToken.ToObject <string>();
                if (string.IsNullOrEmpty(attachValue))
                {
                    token.Remove(NIMIMMessage.AttachmentPath);
                    return;
                }
                var newAttachToken = Newtonsoft.Json.Linq.JToken.Parse(attachValue);
                attachmentToken.Replace(newAttachToken);
            }
        }
Example #50
0
        private HtmlGenericControl GenerateTestRunSummarySection()
        {
            HtmlGenericControl divTestRunSummary = new HtmlGenericControl("div");

            divTestRunSummary.ID = "testRunSummary";

            //List<XElement> tests = new List<XElement>(_xDoc.Document.XPathSelectElements(ReportElements.ReportTag + "/" + ReportElements.TestTag));

            //divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<h1 id=\"testRunName\" class=\"summaryTitle\"><span style=\"font-weight: bold;\">Test Run Name: </span><span id=\"testRunNameVal\"></span></h1>"))); // , this.SuiteName
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunStartTime\" class=\"summaryData\"><span style=\"font-weight: bold;\">Start Time: </span><span id=\"testRunStartTimeVal\"></span></p>")));                      // , String.Format("{0} ({1})", startTime.ToDateTimeUtc().ToLocalTime().ToString("ddd, MMM dd, yyyy HH:mm:ss zzz"), System.TimeZoneInfo.Local.StandardName)
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunEndTime\" class=\"summaryData\"><span style=\"font-weight: bold;\">End Time: </span><span id=\"testRunEndTimeVal\"></span></p>")));                            // , String.Format("{0} ({1})", startTime.ToDateTimeUtc().ToLocalTime().ToString("ddd, MMM dd, yyyy HH:mm:ss zzz"), System.TimeZoneInfo.Local.StandardName)
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunDuration\" class=\"summaryData\"><span style=\"font-weight: bold;\">Duration: </span><span id=\"testRunDurationVal\"></span></p>")));                          // , duration.ToString(@"hh\:mm\:ss\.fff")
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofTests\" class=\"summaryData\"><span style=\"font-weight: bold;\">Number of Tests: </span><span id=\"testRunNumofTestsVal\"></span></p>")));               // , total
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofPass\" class=\"summaryData stepPass\"><span style=\"font-weight: bold;\">Total Pass: </span><span id=\"testRunNumofPassVal\"></span></p>")));             // , passed
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofWarning\" class=\"summaryData stepWarning\"><span style=\"font-weight: bold;\">Total Warning: </span><span id=\"testRunNumofWarningVal\"></span></p>"))); // , warning
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<p id=\"testRunNumofFail\" class=\"summaryData stepFail\"><span style=\"font-weight: bold;\">Total Fail: </span><span id=\"testRunNumofFailVal\"></span></p>")));             // , failed

            Newtonsoft.Json.Linq.JObject jsonObj = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(_testsSummary));
            divTestRunSummary.Controls.Add(new LiteralControl(String.Format("<input name='testRunSummaryObj' type='hidden' value='{0}' />", jsonObj.ToString())));

            return(divTestRunSummary);
        }
Example #51
0
        public void SendMessage(Message message, MessageReplyCallback replyCallback)
        {
            log.DebugFormat("Sending message \"{0}\"", message["message"]);

            if (replyCallback != null)
            {
                outstandingCallbacks.Add(new MessageCallbackInfo()
                {
                    MessageName = message["message"].ToString(),
                    Callback    = replyCallback,
                    ExpireTick  = Environment.TickCount + 1000 * 10,
                    Tag         = message["tag"].ToString(),
                });
            }

            var rawData = Encoding.UTF8.GetBytes(message.ToString(Formatting.None, null) + "\r\n");

            // TODO: Handle the stream ending
            source.Write(rawData, 0, rawData.Length);

            log.Debug("...Done");
        }
        protected string GetXmlCfgFromJson(string jsonConfig)
        {
            string xmlString = null;

            if (!string.IsNullOrWhiteSpace(jsonConfig))
            {
                try
                {
                    Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonConfig);
                    string base64EncodedXml = (string)jObject["xmlCfg"];
                    if (!string.IsNullOrWhiteSpace(base64EncodedXml))
                    {
                        byte[] data = Convert.FromBase64String(base64EncodedXml);
                        xmlString = Encoding.UTF8.GetString(data);
                    }
                }
                catch (Exception)
                {
                }
            }
            return(xmlString);
        }
Example #53
0
 private void ProcessDetail(IList <string> entStrList, InWarehouse iwEnt)
 {
     if (entStrList != null && entStrList.Count > 0)
     {
         for (int j = 0; j < entStrList.Count; j++)
         {
             Newtonsoft.Json.Linq.JObject objL   = JsonHelper.GetObject <Newtonsoft.Json.Linq.JObject>(entStrList[j]);
             OtherInWarehouseDetail       oidEnt = new OtherInWarehouseDetail();
             oidEnt.InWarehouseId    = iwEnt.Id;
             oidEnt.ProductId        = objL.Value <string>("ProductId");
             oidEnt.ProductName      = objL.Value <string>("ProductName");
             oidEnt.ProductCode      = objL.Value <string>("ProductCode");
             oidEnt.ProductPCN       = objL.Value <string>("ProductPCN");
             oidEnt.ProductISBN      = objL.Value <string>("ProductISBN");
             oidEnt.ProductType      = objL.Value <string>("ProductType");
             oidEnt.Quantity         = objL.Value <int>("Quantity");
             oidEnt.InWarehouseState = "未入库";
             oidEnt.Remark           = objL.Value <string>("Remark");
             oidEnt.DoCreate();
         }
     }
 }
        protected override Entity ReadJson(Entity entity, Type objectType, Newtonsoft.Json.Linq.JObject json, JsonSerializer serializer)
        {
            var conn = base.ReadJson(entity, objectType, json, serializer) as Connection;

            if (conn == null)
            {
                return(null);
            }
            // Parse the relation information
            // Relation id
            JToken value;

            if (json.TryGetValue("__relationid", out value) == true && value.Type != JTokenType.Null)
            {
                conn.RelationId = value.ToString();
            }

            // Parse the endpoints
            Endpoint ep1 = null, ep2 = null;

            if (json.TryGetValue("__endpointa", out value) == true && value.Type == JTokenType.Object)
            {
                ep1 = ParseEndpoint(value as JObject, serializer);
            }
            else
            {
                throw new Exception(string.Format("Endpoint A for connection with id {0} is invalid.", conn.Id));
            }
            if (json.TryGetValue("__endpointb", out value) == true && value.Type == JTokenType.Object)
            {
                ep2 = ParseEndpoint(value as JObject, serializer);
            }
            else
            {
                throw new Exception(string.Format("Endpoint B for connection with id {0} is invalid.", conn.Id));
            }
            conn.Endpoints = new EndpointPair(ep1, ep2);
            return(conn);
        }
Example #55
0
 private void RemoveTags(Newtonsoft.Json.Linq.JObject json)
 {
     if (RemoveTag != null && RemoveTag.Length > 0)
     {
         JToken tags = json["tags"];
         if (tags != null)
         {
             List <JToken> children = tags.Children().ToList();
             for (int i = 0; i < RemoveTag.Length; i++)
             {
                 string tagName = ExpandField(RemoveTag[i], json);
                 foreach (JToken token in children)
                 {
                     if (token.ToString() == tagName)
                     {
                         token.Remove();
                     }
                 }
             }
         }
     }
 }
Example #56
0
        CommonParameter[] JSONtoCommonParameter(string json)
        {
            Newtonsoft.Json.Linq.JObject jo = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(json);

            //Additional JSON Data to be added
            if (JSONHeader != null)
            {
                jo.Merge(JSONHeader, new JsonMergeSettings()
                {
                    MergeArrayHandling = MergeArrayHandling.Union
                });
            }

            IList <string> keys = jo.Properties().Select(x => x.Name).ToList();

            CommonParameter[] p = new CommonParameter[keys.Count];
            for (int i = 0; i < keys.Count; i++)
            {
                p[i] = new CommonParameter(keys[i], jo[keys[i]].ToString());
            }
            return(p);
        }
Example #57
0
        public static List <Company> GetCompanies(string Text, TraceWriter log)
        {
            List <Company> results = new List <Company>();

            using (HttpClient client = new HttpClient())
            {
                string payload          = "{\"documents\": [ { \"id\": \"1\", \"text\": \"" + Text + "\"}]}";
                string textAnalyticsKey = System.Environment.GetEnvironmentVariable("TextAnalyticsKey");
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", textAnalyticsKey);
                var content = new StringContent(payload, Encoding.UTF8, "application/json");

                HttpResponseMessage msg = client.PostAsync("https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/entities", content).Result;
                if (msg.IsSuccessStatusCode)
                {
                    var JsonDataResponse             = msg.Content.ReadAsStringAsync().Result;
                    Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(JsonDataResponse);

                    if (obj != null)
                    {
                        foreach (JObject docObject in obj["documents"])
                        {
                            foreach (JObject entityObject in docObject["entities"])
                            {
                                string name = entityObject["name"].ToString().Replace(" (company)", "");

                                Company newCompany = GetCompanyInfo(name, log);
                                if (newCompany.Type == "Organization" && !newCompany.Blacklisted)
                                {
                                    results.Add(newCompany);
                                }
                            }
                        }
                    }
                }
            }

            return(results);
        }
Example #58
0
        public void GetFileUseType(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            //MESDBHelper.OleExec SFCDB = this.DBPools["SFCDB"].Borrow();

            try
            {
                List <string> ret = new List <string>();
                ret.Add("LABEL");
                ret.Add("PPL");
                ret.Add("FACK");
                StationReturn.Data   = ret;
                StationReturn.Status = StationReturnStatusValue.Pass;
            }
            catch (Exception ee)
            {
                //this.DBPools["SFCDB"].Return(SFCDB);
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000037";
                StationReturn.MessagePara.Add(ee.Message);
            }
            //SFCDB.ThrowSqlExeception = false;
            //this.DBPools["SFCDB"].Return(SFCDB);
        }
Example #59
0
        public string GetUserID(string accesstoken, string code)
        {
            string accessget = "";

            try
            {
                accessget = GetData(string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", accesstoken, code));
                Newtonsoft.Json.Linq.JObject ja = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(accessget);
                try
                {
                    return(ja["UserId"].ToString());
                }
                catch
                {
                    return(accesstoken);
                }
            }
            catch
            {
                accessget = "api";
                return(accessget);
            }
        }
Example #60
-1
        private JObject Alert_1(HttpListenerContext context, long chartId)
        {
            MQLCommandManager mqlCommandManager = DLLObjectWrapper.getInstance().getMQLCommandManager(chartId);
            JObject payload = this.GetJsonPayload(context.Request);
            JObject result = new JObject();
            if (payload == null)
            {
                result["result"] = PARSE_ERROR;
                return result;
            }
            List<Object> parameters = new List<Object>();
            parameters.Add(payload["argument"]);
            int id = mqlCommandManager.ExecCommand(MQLCommand.Alert_1, parameters); // MQLCommand ENUM = 1
            while (mqlCommandManager.IsCommandRunning(id)) ; // block while command is running
            try
            {
                mqlCommandManager.throwExceptionIfErrorResponse(id);
                result["result"] = "";
            }
            catch (Exception e)
            {
                result["error"] = MQLExceptions.convertRESTException(e.ToString());
            }

            return result;
        }