コード例 #1
0
        public override void OnPut(string key, Json.Linq.RavenJObject document, Json.Linq.RavenJObject metadata, Abstractions.Data.TransactionInformation transactionInformation)
        {
            if (metadata.Remove(Constants.RavenReplicationConflictDocumentForcePut))
                return;

            metadata.Remove(Constants.RavenReplicationConflictDocument); // or conflict documents
        }
コード例 #2
0
ファイル: ForgeInfo.cs プロジェクト: gdianaty/MinechatPC
        /// <summary>
        /// Create a new ForgeInfo from the given data.
        /// </summary>
        /// <param name="data">The modinfo JSON tag.</param>
        internal ForgeInfo(Json.JSONData data)
        {
            // Example ModInfo (with spacing):

            // "modinfo": {
            //     "type": "FML",
            //     "modList": [{
            //         "modid": "mcp",
            //         "version": "9.05"
            //     }, {
            //         "modid": "FML",
            //         "version": "8.0.99.99"
            //     }, {
            //         "modid": "Forge",
            //         "version": "11.14.3.1512"
            //     }, {
            //         "modid": "rpcraft",
            //         "version": "Beta 1.3 - 1.8.0"
            //     }]
            // }

            this.Mods = new List<ForgeMod>();
            foreach (Json.JSONData mod in data.Properties["modList"].DataArray)
            {
                String modid = mod.Properties["modid"].StringValue;
                String version = mod.Properties["version"].StringValue;

                this.Mods.Add(new ForgeMod(modid, version));
            }
        }
コード例 #3
0
		public override ReadVetoResult AllowRead(string key, Json.Linq.RavenJObject metadata, ReadOperation operation, Abstractions.Data.TransactionInformation transactionInformation)
		{
			if (operation == ReadOperation.Index  && metadata.ContainsKey(Constants.RavenReplicationConflictDocument))
			{
				return ReadVetoResult.Ignore;
			}
			return ReadVetoResult.Allowed;
		}
コード例 #4
0
 /// <summary>
 /// Retrieves the Starcounter transaction log directory from the server's settings URI.
 /// </summary>
 static public string GetTransactionLogDirectory() {
     string settingsUri = "http://127.0.0.1:" + StarcounterEnvironment.Default.SystemHttpPort + "/api/admin/databases/" + StarcounterEnvironment.DatabaseNameLower + "/settings";
     var settingsResult = Http.GET(settingsUri);
     if (settingsResult == null || !settingsResult.IsSuccessStatusCode)
         throw new Exception("Can't access " + settingsUri);
     dynamic json = new Json(settingsResult.Body);
     return json.TransactionLogDirectory;
 }
コード例 #5
0
        public void Setup()
        {
            _updateJson = "{\"name\":\"agentupdate\",\"value\":\"http://c0473242.cdn.cloudfiles.rackspacecloud.com/AgentService.zip,e6b39323fc3cf982b270fc114b9bb9e5\"}";

            _jsonCommand = new Json<Command>();
            _jsonInterface = new Json<NetworkInterface>();
            _partialJsonStringForImport = "{\"name\":\"password\",\"value\":\"somepassword\"}";
            _fullJsonStringWithObjectCompletelyPopulated = "{\"name\":\"password\",\"value\":\"somepassword\",\"key\":\"67745jhgj7683\"}";
            _fullJsonStringWithObjectPartiallyPopulated = "{\"key\":null,\"name\":\"password\",\"value\":\"somepassword\"}";
            _fullInterfaceJsonString = "{\"mac\":\"40:40:ed:65:h6\",\"dns\":[\"1.1.1.1\",\"64.39.2.138\"],\"label\":\"Label 1\",\"ips\":[{\"Ip\":\"3.3.3.3\",\"NetMask\":\"255.255.255.0\"},{\"Ip\":\"4.4.4.4\",\"NetMask\":\"255.255.255.0\"}],\"gateway\":\"10.1.1.100\"}";
        }
コード例 #6
0
        public IList<Command> GetCommands()
        {
            var messageKeysAsUuids = Read(Constants.WritableDataHostBase).ValidateAndClean();
            IList<Command> commands = new List<Command>();

            foreach (var messageKey in messageKeysAsUuids) {
                var command = new Json<Command>().Deserialize(ReadKey(messageKey));
                command.key = messageKey;
                commands.Add(command);
            }

            return commands;
        }
コード例 #7
0
ファイル: JsonFixture.cs プロジェクト: Chandu/Wyam
        public void SetsMetadataKey()
        {
            // Given
            IDocument document = Substitute.For<IDocument>();
            document.Content.Returns(JsonContent);
            Json json = new Json("MyJson");

            // When
            json.Execute(new[] {document}, null).ToList();  // Make sure to materialize the result list

            // Then
            document.Received(1).Clone(Arg.Any<IEnumerable<KeyValuePair<string, object>>>());
            document.Received().Clone(Arg.Is<IEnumerable<KeyValuePair<string, object>>>(x => x.First().Key == "MyJson"));
        }
コード例 #8
0
 public Limit Process(string data)
 {
     var json = new Json<Limit>();
     Limit limit;
     try
     {
         limit = json.Deserialize(data);
     }
     catch (SerializationException)
     {
         limit = null;
     }
     return limit;
 }
コード例 #9
0
ファイル: Try.ashx.cs プロジェクト: thsunmy/visualcaptcha
        public void ProcessRequest(HttpContext context)
        {
            var captcha = (Captcha)context.Session[SessionKey];

            var success = captcha.ValidateAnswer(context.Request.Form.GetValues("value")[0]);
            var message = "Your answer was " + (success ? "valid." : "invalid.");
            Json json = new Json()
            {
                success = success,
                message = message
            };
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(json));
        }
        public IList<Command> GetCommands()
        {
            var messageKeysAsUuids = Read(Constants.WritableDataHostBase).ValidateAndClean();
            IList<Command> commands = new List<Command>();

            foreach (var messageKey in messageKeysAsUuids) {
                var result = ReadKey(messageKey);
                if (result.Contains("The system cannot find the file specified.")) continue;
                var command = new Json<Command>().Deserialize(result);
                command.key = messageKey;
                commands.Add(command);
            }
            return commands;
        }
コード例 #11
0
 public ArtifactLoaderOptions(Json.JToken conf,bool defaultVersion=true) {
     if (conf.ValueType == Json.ValueType.String)
     {
         if(defaultVersion) this.Version = conf.ToString();
         else this.Assembly = conf.ToString();
     }
     else
     {
         var config = conf as Json.JObject;
         if (config["assembly"] != null) this.Assembly = config["assembly"].ToString();
         if (config["version"] != null) this.Version = config["version"].ToString();
         if (config["pdb"] != null) this.Version = config["pdb"].ToString();
     }
 }
        private IDictionary<string, NetworkInterface> GetInterfaces()
        {
            IDictionary<string, NetworkInterface> interfaces = new Dictionary<string, NetworkInterface>();

            var macAddressesWithoutColons =
                _xenStore.Read(_networkKeyLocation);

            foreach (var macAddress in macAddressesWithoutColons) {
                var jsonData = _xenStore.ReadVmDataKey(macAddress);
                var networkInterface = new Json<NetworkInterface>().Deserialize(jsonData);
                interfaces.Add(networkInterface.mac.ToUpper(), networkInterface);
            }

            return interfaces;
        }
コード例 #13
0
        public Status Process(string data)
        {
            var json = new Json<Status>();

            Status status;
            try
            {
                status = json.Deserialize(data);
            }
            catch (SerializationException)
            {
                status = null;
            }
            return status;
        }
コード例 #14
0
 public override VetoResult AllowPut(string key, Json.Linq.RavenJObject document, Json.Linq.RavenJObject metadata, Abstractions.Data.TransactionInformation transactionInformation)
 {
     if (metadata.ContainsKey(Constants.RavenReplicationConflictDocument) && metadata.ContainsKey(Constants.RavenReplicationConflictDocumentForcePut) == false)
         return VetoResult.Deny("You cannot PUT a document with metadata " + Constants.RavenReplicationConflictDocument);
     JsonDocument documentByKey = null;
     Database.TransactionalStorage.Batch(accessor =>
     {
         documentByKey = accessor.Documents.DocumentByKey(key);
     });
     if (documentByKey == null)
         return VetoResult.Allowed;
     if (documentByKey.Metadata.ContainsKey(Constants.RavenReplicationConflictDocument))
         return VetoResult.Deny("Conflict documents (with " + Constants.RavenReplicationConflictDocument +
                             ") are read only and can only be modified by RavenDB when you resolve the conflict");
     return VetoResult.Allowed;
 }
コード例 #15
0
ファイル: Start.ashx.cs プロジェクト: thsunmy/visualcaptcha
        public void ProcessRequest(HttpContext context)
        {
            int numberOfImages = int.Parse(context.Request.RawUrl.Split('/')[3].Split('?')[0].ToString());
            var captcha = new Captcha(numberOfImages);
            context.Session[SessionKey] = captcha;

            var frontEndData = captcha.GetFrontEndData();

            Json json = new Json()
            {
                values = frontEndData.Values,
                imageName = frontEndData.ImageName,
                imageFieldName = frontEndData.ImageFieldName,
                audioFieldName = frontEndData.AudioFieldName
            };
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(json));
        }
コード例 #16
0
ファイル: ChannelInfo.cs プロジェクト: alexguo88/DoubanFM
        internal ChannelInfo(Json.ChannelInfo ci)
        {
            if (ci == null) return;
			List<Channel> list1 = new List<Channel>();
			if (ci.personal != null)
			{
				foreach (var channel in ci.personal)
				{
					Channel ch = new Channel(channel);
					if (ch.IsEffective)
					{
						list1.Add(ch);
					}
				}
			}
            Personal = list1;
			List<Channel> list2 = new List<Channel>();
			if (ci.Public != null)
			{
				foreach (var channel in ci.Public)
				{
					Channel ch = new Channel(channel);
					if (ch.IsEffective)
					{
						list2.Add(ch);
					}
				}
			}
            Public = list2;
			List<Channel> list3 = new List<Channel>();
			if (ci.dj != null)
			{
				foreach (var channel in ci.dj)
				{
					Channel ch = new Channel(channel);
					if (ch.IsEffective)
					{
						list3.Add(ch);
					}
				}
			}
            Dj = list3;
        }
コード例 #17
0
ファイル: AdhocEngine.cs プロジェクト: xeno-by/xenogears
        public override Object Deserialize(Type t, Json json)
        {
            var m_deserialize = t.GetMethods(BF.All).AssertSingle(m => m.Name == "Deserialize" && (
                Seq.Equal(m.Params(), typeof(Json)) || 
                (Seq.Equal(m.Params(), typeof(Object)) && m.GetParameters()[0].HasAttr<DynamicAttribute>())));
            if (m_deserialize.IsStatic)
            {
                (m_deserialize.Ret() != typeof(void)).AssertTrue();
                return m_deserialize.Invoke(null, json.MkArray());
            }
            else
            {
                var a_json = t.AttrOrNull<JsonAttribute>();
                var default_ctor = a_json == null ? true : a_json.DefaultCtor;
                var instance = default_ctor ? t.CreateInstance() : t.CreateUninitialized();

                (m_deserialize.Ret() == typeof(void)).AssertTrue();
                m_deserialize.Invoke(instance, json.MkArray());
                return instance;
            }
        }
コード例 #18
0
ファイル: JsonFixture.cs プロジェクト: Chandu/Wyam
        public void FlattensTopLevel()
        {
            // Given
            IDocument document = Substitute.For<IDocument>();
            IEnumerable<KeyValuePair<string, object>> items = null;
            document
                .When(x => x.Clone(Arg.Any<IEnumerable<KeyValuePair<string, object>>>()))
                .Do(x => items = x.Arg<IEnumerable<KeyValuePair<string, object>>>());
            document.Content.Returns(JsonContent);
            Json json = new Json();

            // When
            json.Execute(new[] { document }, null).ToList();  // Make sure to materialize the result list

            // Then
            document.Received(1).Clone(Arg.Any<IEnumerable<KeyValuePair<string, object>>>());
            Assert.AreEqual(4, items.Count());
            Assert.AreEqual("*****@*****.**", items.First(x => x.Key == "Email").Value);
            Assert.AreEqual(true, items.First(x => x.Key == "Active").Value);
            Assert.AreEqual(new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), items.First(x => x.Key == "CreatedDate").Value);
            CollectionAssert.AreEqual(new[] { "User", "Admin" }, (IEnumerable)items.First(x => x.Key == "Roles").Value);
        }
コード例 #19
0
ファイル: JsonFixture.cs プロジェクト: Chandu/Wyam
        public void GeneratesDynamicObject()
        {
            // Given
            IDocument document = Substitute.For<IDocument>();
            IEnumerable<KeyValuePair<string, object>> items = null;
            document
                .When(x => x.Clone(Arg.Any<IEnumerable<KeyValuePair<string, object>>>()))
                .Do(x => items = x.Arg<IEnumerable<KeyValuePair<string, object>>>());
            document.Content.Returns(JsonContent);
            Json json = new Json("MyJson");

            // When
            json.Execute(new[] {document}, null).ToList();  // Make sure to materialize the result list

            // Then
            document.Received(1).Clone(Arg.Any<IEnumerable<KeyValuePair<string, object>>>());
            Assert.AreEqual(1, items.Count());
            Assert.IsInstanceOf<ExpandoObject>(items.First().Value);
            Assert.AreEqual("*****@*****.**", (string)((dynamic)items.First().Value).Email);
            Assert.AreEqual(true, (bool)((dynamic)items.First().Value).Active);
            Assert.AreEqual(new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), (DateTime)((dynamic)items.First().Value).CreatedDate);
            CollectionAssert.AreEqual(new [] { "User", "Admin" }, (IEnumerable)((dynamic)items.First().Value).Roles);
        }
        public IList<Command> GetCommands()
        {
            var commands = new List<Command>();
            try
            {

                var keys = Read(Constants.WritableDataHostBase).ValidateAndClean();

                foreach (var messageKey in keys)
                {
                    _logger.Log(messageKey);
                    var result = ReadKey(messageKey);
                    if (result.Contains("The system cannot find the file specified.")) continue;
                    var command = new Json<Command>().Deserialize(result);
                    command.key = messageKey;
                    commands.Add(command);
                }
            }
            catch (Exception e)
            {
                _logger.Log(e.ToString());
            }
            return commands;
        }
コード例 #21
0
        public static void MakeReport()
        {
            var teams = File.ReadLines("teams.csv")
                        .Skip(1)
                        .Select(z => z.Split(';'))
                        .Select(z => new { name = z[0], id = int.Parse(z[1]), team = z[2] })
                        .ToList();

            var extract = Json.Read <List <TournamentParticipantExtraction> >("extract.json")
                          .ToDictionary(z => z.Participant.Id, z => z);
            var verify = Json.Read <List <TournamentVerificationResult> >("verify.json")
                         .ToDictionary(z => z.Participant.Id, z => z);

            var results = File.ReadLines("results.json").Select(JsonConvert.DeserializeObject <TournamentGameResult>)
                          .GroupBy(z => z.Task.Participants[0].Id)
                          .ToDictionary(z => z.Key, z => z);

            var report = new List <UserReport>();

            foreach (var e in teams)
            {
                var r = new UserReport();
                r.Name   = e.name;
                r.Team   = e.team;
                r.TeamId = e.id;

                if (extract.ContainsKey(e.id))
                {
                    r.Extraction = extract[e.id].Status;
                }
                if (verify.ContainsKey(e.id))
                {
                    r.Verification = verify[e.id].Status;
                }
                if (results.ContainsKey(e.id))
                {
                    r.Results = results[e.id]
                                .Select(z => z.Result.ScoresByPlayer["Left"].Where(x => x.Key == "Main").Select(x => x.Value).First())
                                .ToArray();
                    r.Average = r.Results.Average();
                }
                report.Add(r);
            }

            using (var wr = new StreamWriter("report.html"))
            {
                wr.WriteLine("<!DOCTYPE html>\n<meta charset=\"UTF-8\">\n<html><body><table>");
                wr.WriteLine("<tr><th>ФИО</th><th>Команда</th><th>ИД команды</th><th>Формат</th><th>Прозвон</th><th>Игра 1</th><th>Игра 2</th><th>Игра 3</th><th>Среднее</th><tr>");
                foreach (var e in report.OrderByDescending(z => z.Average).ThenBy(z => !z.Extraction.HasValue).ThenBy(z => z.TeamId))
                {
                    wr.WriteLine($"<tr><td>{e.Name}</td><td>{e.Team}</td><td>{e.TeamId}</td><td>{e.Extraction}</td><td>{e.Verification}</td>");
                    for (int i = 0; i < 3; i++)
                    {
                        wr.WriteLine("<td>");
                        if (e.Results != null && e.Results.Length > i)
                        {
                            wr.WriteLine(e.Results[i]);
                        }
                        wr.WriteLine("</td>");
                    }
                    wr.WriteLine($"<td>{e.Average.ToString("0.00")}</td></tr>");
                }
                wr.WriteLine("</table></body></html>");
            }
            Process.Start("report.html");
        }
コード例 #22
0
ファイル: LoginView.cs プロジェクト: brianmed/Todo
		public async Task POSTRequest(string action, TKDataForm dataForm)
		{
			if (false == Monitor.TryEnter(LoginView.POSTLock)) {
				return;
			}

			var json = new Json();

			var inUsername = (NSString)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Username").Value.ToString();
			var inPassword = (NSString)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Password").Value.ToString();
			var inVerify = (NSString)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Verify").Value.ToString();
			var mode = ((NSNumber)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Mode").Value).Int32Value;
			var inQuestion = (NSString)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Question").Value.ToString();
			var inAnswer = (NSString)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Answer").Value.ToString();

			var isRegister = 1 == mode ? true : false;

			if (String.IsNullOrWhiteSpace(inUsername)) {
				DisplayAlert ("Alert", "Username required", "OK");
				Monitor.Exit(LoginView.POSTLock);
				return;
			}

			if (String.IsNullOrWhiteSpace(inPassword)) {
				DisplayAlert ("Alert", "Password required", "OK");
				Monitor.Exit(LoginView.POSTLock);
				return;
			}

			if (isRegister) {
				if (String.IsNullOrWhiteSpace(inVerify)) {
					DisplayAlert ("Alert", "Verify required", "OK");
					Monitor.Exit(LoginView.POSTLock);
					return;
				}

				if (inVerify != inPassword) {
					DisplayAlert ("Alert", "Passwords much match", "OK");
					Monitor.Exit(LoginView.POSTLock);
					return;
				}

				if (null == inQuestion) {
					DisplayAlert ("Alert", "Please select a security question", "OK");
					Monitor.Exit(LoginView.POSTLock);
					return;
				}

				if (String.IsNullOrWhiteSpace(inQuestion)) {
					DisplayAlert ("Alert", "Please select a security question", "OK");
					Monitor.Exit(LoginView.POSTLock);
					return;
				}

				if (String.IsNullOrWhiteSpace (inAnswer)) {
					DisplayAlert ("Alert", "Security answer required", "OK");
					Monitor.Exit(LoginView.POSTLock);
					return;
				}
			}				

			var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

			var notificationView = new GCDiscreetNotificationView (
				text: isRegister ? "Signing up" : "Logging in",
				activity: false,
				presentationMode: GCDNPresentationMode.Bottom,
				view: appDelegate.navigationController.View
			);

			notificationView.SetShowActivity(true, true);
			notificationView.Show (true);

			json.ContentType = "application/json";
			var data = new Dictionary<string, string>();

			data ["username"] = inUsername;
			data ["password"] = inPassword;

			if (isRegister) {
				data ["question"] = inQuestion;
				data ["answer"] = inAnswer;
			}

			try {
				json.PostData = Newtonsoft.Json.JsonConvert.SerializeObject (data);

				var endpoints = new Dictionary<string, string>();
				endpoints.Add("signin", String.Concat(Globals.EndpointBase, "/api/v1/account/signin"));
				endpoints.Add("register", String.Concat(Globals.EndpointBase, "/api/v1/account/register"));
				var endpoint = endpoints[action];

				await json.PostAsync(endpoint);

				json.XPath = "/json/status";
				if ("\"success\"" == json.XText) {
					json.XPath = "/json/data/api_key";

					var s = new Settings { 
						API_Key = json.XText.Replace("\"", ""),
						username = inUsername,
					};
					Globals.SQLite.Insert (s);

					var settings = Globals.SQLite.Table<Settings>().Where (v => v.API_Key != null);
					Globals.theSettings = settings.First();

					appDelegate.navigationController.PopToRootViewController(true);
					appDelegate.navigationController.ViewControllers = new List<UIViewController> { new TodoListView() }.ToArray();
				}
				else {
					json.XPath = "/json/data/message";
					var newStr = json.XText.Replace("\"", "");
					DisplayAlert("Alert", newStr, "OK");
				}
			}
			catch (Exception e) {
				var msgs = new Dictionary<string, string>();
				msgs.Add("signin", "Unable to signin");
				msgs.Add("register", "Unable to register");
				var msg = msgs[action];

				DisplayAlert ("Alert", msg, "OK");
			}

			notificationView.Hide (true);

			Monitor.Exit(LoginView.POSTLock);
		}
コード例 #23
0
 public void UserUpdate(string userUpdate)
 {
     try
     {
         Dictionary <string, object>             dictionary  = (Dictionary <string, object>)Json.Deserialize(userUpdate);
         Dictionary <string, string>             dictionary2 = new Dictionary <string, string>();
         Dictionary <string, object> .Enumerator enumerator  = dictionary.GetEnumerator();
         while (enumerator.MoveNext())
         {
             dictionary2[enumerator.Current.Key] = $"{enumerator.Current.Value}";
         }
         SDK.UserUpdate(dictionary2);
     }
     catch (Exception ex)
     {
         SwrveLog.LogError(ex.ToString(), "userUpdate");
     }
 }
コード例 #24
0
ファイル: DefaultEngine.cs プロジェクト: xeno-by/xenogears
        public override Object Deserialize(Type t, Json json)
        {
            if (json.HasValue && json.Value == null) return null;

            if (t.IsNullable()) return json.Deserialize(t.UndecorateNullable());
            if (t == typeof(DateTime)) { /* do nothing - just deserialize from UTC string */ }

            var cfg = t.Config().DefaultEngine().Config;
            if (cfg.IsPrimitive)
            {
                if (t.IsJsonPrimitive())
                {
                    return json.Value;
                }
                else
                {
                    t.SupportsSerializationToString().AssertTrue();
                    var s_value = json.Value.AssertCast<String>();
                    return s_value.FromInvariantString(t);
                }
            }   
            else
            {
                var obj = t.Reify();
                t = obj.GetType();
                if (t.IsArray) obj = Enumerable.ToList((dynamic)obj);

                if (cfg.IsHash)
                {
                    var add = t.GetDictionarySetter().AssertNotNull();
                    (add.Param(0) == typeof(String)).AssertTrue();
                    var t_v = add.Param(1);

                    json.IsObject.AssertTrue();
                    json.Cast<String, Json>().ForEach(kvp =>
                    {
                        var key = kvp.Key;
                        // todo. what if the value passed has a subtype of t_v
                        // we won't be able to find out this and will deserialize incorrectly!
                        var value = kvp.Value.Deserialize(t_v);
                        add.Invoke(obj, new []{key, value});
                    });
                }
                else if (cfg.IsList)
                {
                    var add = t.GetListAdder().AssertNotNull();
                    var t_v = add.Param(0);

                    json.IsArray.AssertTrue();
                    json.Values.Cast<Json>().ForEach(j_value =>
                    {
                        // todo. what if the value passed has a subtype of t_v
                        // we won't be able to find out this and will deserialize incorrectly!
                        var value = j_value.Deserialize(t_v);
                        add.Invoke(obj, new []{value});
                    });
                }
                else if (cfg.IsObject)
                {
                    json.IsObject.AssertTrue();
                    json.Cast<String, Json>().ForEach(kvp =>
                    {
                        var key = kvp.Key;
                        var mi = cfg.Slots.AssertSingle(s =>
                        {
                            var a_include = s.AttrOrNull<JsonIncludeAttribute>();
                            var a_key = a_include == null ? null : a_include.Name;
                            var name = a_key ?? s.Name;
                            return String.Compare(name, key, true) == 0;
                        });

                        var value = kvp.Value.Deserialize(mi);
                        mi.SetValue(obj, value);
                    });
                }
                else
                {
                    throw AssertionHelper.Fail();
                }

                if (t.IsArray) obj = Enumerable.ToArray((dynamic)obj);
                return obj;
            }
        }
コード例 #25
0
        /// <summary>
        /// Serializes the request into a StringContent with a json media type, but serialized with SimpleJson
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public HttpContent Serialize <T>(T request)
        {
            var json = Json.Serialize(request);

            return(new StringContent(json, Encoding.UTF8, "application/json"));
        }
コード例 #26
0
        public override void SendTags(IDictionary <string, string> tags)
        {
            string jsonString = Json.Serialize(tags);

            iOS.OneSignal.SendTagsWithJsonString(jsonString);
        }
コード例 #27
0
 /// <summary>
 /// 获取Json结果
 /// </summary>
 public async Task <TResult> ResultFromJsonAsync <TResult>()
 {
     return(Json.ToObject <TResult>(await ResultAsync()));
 }
コード例 #28
0
        public static bool UserCanManageAccessForSubscription(string subscriptionId, string organizationId)
        {
            bool ret = false;

            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));


                // Get permissions of the user on the subscription
                string requestUrl = string.Format("{0}/subscriptions/{1}/providers/microsoft.authorization/permissions?api-version={2}",
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], subscriptionId, ConfigurationManager.AppSettings["ida:ARMAuthorizationPermissionsAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Actions and NotActions
                // actions  notActions
                // -------  ----------
                // {*}      {Microsoft.Authorization/*/Write, Microsoft.Authorization/*/Delete}
                // {*/read} {}

                if (response.IsSuccessStatusCode)
                {
                    string responseContent   = response.Content.ReadAsStringAsync().Result;
                    var    permissionsResult = (Json.Decode(responseContent)).value;

                    foreach (var permissions in permissionsResult)
                    {
                        bool permissionMatch = false;
                        foreach (string action in permissions.actions)
                        {
                            var actionPattern = "^" + Regex.Escape(action.ToLower()).Replace("\\*", ".*") + "$";
                            permissionMatch = Regex.IsMatch("microsoft.authorization/roleassignments/write", actionPattern);
                            if (permissionMatch)
                            {
                                break;
                            }
                        }
                        // if one of the actions match, check that the NotActions don't
                        if (permissionMatch)
                        {
                            foreach (string notAction in permissions.notActions)
                            {
                                var notActionPattern = "^" + Regex.Escape(notAction.ToLower()).Replace("\\*", ".*") + "$";
                                if (Regex.IsMatch("microsoft.authorization/roleassignments/write", notActionPattern))
                                {
                                    permissionMatch = false;
                                }
                                if (!permissionMatch)
                                {
                                    break;
                                }
                            }
                        }
                        if (permissionMatch)
                        {
                            ret = true;
                            break;
                        }
                    }
                }
            }
            catch { }

            return(ret);
        }
コード例 #29
0
        /// <summary>
        /// Due to the way node_modues work, the directory depth can get very deep and go beyond MAX_PATH (260 chars).
        /// Therefore grab all node_modues directories and move them up to baseNodeModuleDir. Node's require() will then
        /// traverse up and find them at the higher level. Should be fine as long as there are no versioning conflicts.
        /// </summary>
        void FlattenNodeModules(string baseNodeModuleDir)
        {
            var        baseDir              = new DirectoryInfo(baseNodeModuleDir);
            object     instance             = Activator.CreateInstance(_directoryInfo, new Object[] { baseNodeModuleDir });
            MethodInfo enumerateDirectories = _directoryInfo.GetMethod("EnumerateDirectories", new Type[] { typeof(string), typeof(SearchOption) });

            var nodeModulesDirs = from dir in (IEnumerable <dynamic>)enumerateDirectories.Invoke(instance, new object[] { "*", SearchOption.AllDirectories })
                                  where dir.Name.Equals("node_modules", StringComparison.OrdinalIgnoreCase)
                                  //orderby dir.FullName.ToString().Count(c => c == Path.DirectorySeparatorChar) descending // Get deepest first
                                  select dir;

            // Since IEnumerable<dynamic> can't use orderby (throws CS1977), we will use custom sort.
            var nodeModulesDirsList = nodeModulesDirs.ToList();

            nodeModulesDirsList.Sort((dir1, dir2) => dir2.FullName.Split(Path.DirectorySeparatorChar).Length.CompareTo(dir1.FullName.Split(Path.DirectorySeparatorChar).Length));

            foreach (var nodeModules in nodeModulesDirsList)
            {
                foreach (var module in nodeModules.EnumerateDirectories())
                {
                    // If the package uses a non-default main file,
                    // add a redirect in index.js so that require()
                    // can find it without package.json.
                    if (module.Name != ".bin" && !File.Exists(Path.Combine(module.FullName, "index.js")))
                    {
                        enumerateDirectories = _file.GetMethod("ReadAllText", new Type[] { typeof(string) });
                        string  path    = (string)enumerateDirectories.Invoke(null, new object[] { module.FullName + "\\package.json" });
                        dynamic package = Json.Decode(path);
                        string  main    = package.main;

                        if (!string.IsNullOrEmpty(main))
                        {
                            if (!main.StartsWith("."))
                            {
                                main = "./" + main;
                            }

                            File.WriteAllText(
                                Path.Combine(module.FullName, "index.js"),
                                "module.exports = require(" + Json.Encode(main) + ");"
                                );
                        }
                    }

                    string targetDir = Path.Combine(baseDir.FullName, "node_modules", module.Name);
                    if (!Directory.Exists(targetDir))
                    {
                        enumerateDirectories = _directoryInfo.GetMethod("MoveTo", new Type[] { typeof(string) });
                        //module.MoveTo(targetDir);
                        enumerateDirectories.Invoke(module, new object[] { targetDir });
                    }
                    else if (module.Name != ".bin")
                    {
                        Log.LogMessage(MessageImportance.High, "Not collapsing conflicting module " + module.FullName);
                    }
                }

                enumerateDirectories = _directoryInfo.GetMethod("EnumerateFileSystemInfos", Type.EmptyTypes);

                if (!(enumerateDirectories.Invoke(nodeModules, new object[] { }) as IEnumerable <dynamic>).Any())
                {
                    nodeModules.Delete();
                }
            }
        }
コード例 #30
0
ファイル: Account_BLL.cs プロジェクト: chenxiang357/chenx
 /// <summary>
 /// 原始信息
 /// </summary>
 /// <param name="entity"></param>
 public void OriginalInfo(AccountNumber entity)
 {
     if (Combination == null)
     {
         Combination = new ContentsCombination();
     }
     Combination.OldName = entity.Name;
     ContentsArray       = new string[2];
     ContentsArray[0]    = Combination.Log_Contents_Json("原始信息", "data.json文件", Json.Serialization(entity));
 }
コード例 #31
0
 /// <summary>
 /// Parses the json as a given type from the request body string.
 /// </summary>
 /// <typeparam name="T">The type of specified object type</typeparam>
 /// <param name="requestBody">The request body.</param>
 /// <returns>
 /// A string that represents the json as a given type from the request body string
 /// </returns>
 public static T ParseJson<T>(this string requestBody)
     where T : class
 {
     return requestBody == null ? null : Json.Deserialize<T>(requestBody);
 }
コード例 #32
0
 /// <summary>
 /// 添加Json参数
 /// </summary>
 /// <param name="value">值</param>
 public TRequest JsonData <T>(T value)
 {
     ContentType(HttpContentType.Json);
     _json = Json.ToJson(value);
     return(This());
 }
コード例 #33
0
ファイル: Example1.cs プロジェクト: ykoji1112/example
        public static void Run()
        {
            // 帳票定義ファイルを読み込みます
            Report report = new Report(Json.Read("report\\example1.rrpt"));

            // 帳票にデータを渡します
            report.Fill(new ReportDataSource(getDataTable()));

            // ページ分割を行います
            ReportPages pages = report.GetPages();

            // PDF出力
            using (FileStream fs = new FileStream("output\\example1.pdf", FileMode.Create))
            {
                PdfRenderer renderer = new PdfRenderer(fs);
                // バックスラッシュ文字を円マーク文字に変換します
                renderer.Setting.ReplaceBackslashToYen = true;
                pages.Render(renderer);
            }

            // XLS出力
            using (FileStream fs = new FileStream("output\\example1.xls", FileMode.Create))
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                XlsRenderer  renderer = new XlsRenderer(workbook);
                // Renderメソッドを呼ぶ前に必ずNewSheetメソッドを呼んでワークシートを作成します
                renderer.NewSheet("見積書");
                pages.Render(renderer);
                workbook.Write(fs);
            }

            // XLSX出力
            using (FileStream fs = new FileStream("output\\example1.xlsx", FileMode.Create))
            {
                XSSFWorkbook workbook = new XSSFWorkbook();
                XlsxRenderer renderer = new XlsxRenderer(workbook);
                // Renderメソッドを呼ぶ前に必ずNewSheetメソッドを呼んでワークシートを作成します
                renderer.NewSheet("見積書");
                pages.Render(renderer);
                workbook.Write(fs);
            }

            // 直接印刷、プレビュー画面表示
            {
                Printer printer = new Printer(pages);

                //// 直接印刷
                //// ダイアログを出して印刷します
                //if (printer.PrintDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //{
                //    printer.PrintDocument.Print();
                //}

                //// ダイアログを出さずに印刷します
                //printer.PrintDocument.Print();

                // プレビュー画面表示
                FmPrintPreview preview = new FmPrintPreview(printer);
                // プレビュー画面が開かれた時点で表示倍率を現在のウィンドウサイズに合わせます
                preview.StartUpZoomFit = true;
                preview.ShowDialog();
            }
        }
コード例 #34
0
        public static void init(string customerId, TuningUpdater tuningUpdater, string userId, Dictionary <string, object> userProperties, string deviceId, Dictionary <string, object> deviceProperties, int reqTimeout, string host, bool logEnabled, string sdkNamePre, string sdkVersion, Callback cb, string hubObjName, bool isWebPlayer)
        {
            Error ret = Error.Success;

            // Have we already initialized CognitiveVR?
            if (Initialized)
            {
                Util.logError("CognitiveVR has already been initialized, no need to re-initialize");
                ret = Error.AlreadyInitialized;
            }
            else if (null == cb)
            {
                Util.logError("Please provide a valid callback");
                ret = Error.InvalidArgs;
            }

            if (Error.Success == ret)
            {
                sCustomerId = customerId;
                ReqTimeout  = reqTimeout;
                Host        = host;
                sSDKName    = Util.getSDKName(sdkNamePre);
                sSDKVersion = sdkVersion;

                Util.cacheDeviceAndAppInfo();

                // First see if we have a deviceId stored off locally that we can use
                string savedDeviceId;
                if (!isValidId(deviceId) && Prefs.TryGetValue(DEVICEID_KEY_NAME, out savedDeviceId))
                {
                    if (isValidId(savedDeviceId))
                    {
                        deviceId = savedDeviceId;
                    }
                }

                // set up device id & user id now, in case initial server call doesn't make it back (offline usage, etc)
                if (isValidId(deviceId))
                {
                    DeviceId = deviceId;
                }
                if (isValidId(userId))
                {
                    UserId = userId;
                }

                // add any auto-scraped device state
                IDictionary <string, object> deviceAndAppInfo = Util.getDeviceAndAppInfo();
                if (null == deviceProperties)
                {
                    deviceProperties = deviceAndAppInfo as Dictionary <string, object>;
                }
                else
                {
                    try
                    {
                        foreach (var info in deviceAndAppInfo)
                        {
                            deviceProperties.Add(info.Key, info.Value);
                        }
                    }
                    catch (ArgumentException)
                    {
                        Util.logError("device properties passed in have a duplicate key to the auto-scraped properties!");
                    }
                }

                HttpRequest.init(hubObjName, isWebPlayer);

                // No device Id, so let's retrieve one and save it off
                string url          = Host + "/isos-personalization/ws/interface/application_init" + getQueryParms();
                IList  allArgs      = new List <object>(6);
                double curTimeStamp = Util.Timestamp();
                allArgs.Add(curTimeStamp);
                allArgs.Add(curTimeStamp);
                allArgs.Add(userId);
                allArgs.Add(deviceId);
                allArgs.Add(userProperties);
                allArgs.Add(deviceProperties);

                try
                {
                    HttpRequest.executeAsync(new Uri(url), ReqTimeout, Json.Serialize(allArgs), new InitRequestListener(tuningUpdater, userProperties, deviceProperties, cb));
                }
                catch (WebException e)
                {
                    reset();

                    Util.logError("WebException during the HttpRequest.  Check your host and customerId values: " + e.Message);
                    ret = Error.InvalidArgs;
                }
                catch (Exception e)
                {
                    reset();

                    Util.logError("Error during HttpRequest: " + e.Message);
                    ret = Error.Generic;
                }
            }

            if ((Error.Success != ret) && (null != cb))
            {
                cb(ret);
            }
        }
コード例 #35
0
ファイル: TodoDataEntry.cs プロジェクト: brianmed/Todo
		public async Task POSTTodoEntry (TKDataForm dataForm)
		{
			if (false == Monitor.TryEnter(TodoDataEntry.POSTLock)) {
				return;
			}

			var json = new Json();

			var data = new Dictionary<string, string>();

			data["title"] = ((NSString)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Title").Value).ToString();
			data["content"] = ((NSString)((TKDataFormEntityDataSource)dataForm.DataSource).EntityModel.PropertyWithName ("Content").Value).ToString();

			data["api_key"] = Globals.theSettings.API_Key;
			data["username"] = Globals.theSettings.username;

			if (String.IsNullOrWhiteSpace(data["title"])) {				
				DisplayAlert ("Alert", "Title required", "OK");
				Monitor.Exit (TodoDataEntry.POSTLock);
				return;
			}

			if (String.IsNullOrWhiteSpace(data["content"])) {				
				DisplayAlert ("Alert", "Content required", "OK");
				Monitor.Exit (TodoDataEntry.POSTLock);
				return;
			}

			var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

			var notificationView = new GCDiscreetNotificationView (
				text: "Saving todo",
				activity: false,
				presentationMode: GCDNPresentationMode.Bottom,
				view: appDelegate.navigationController.View
			);

			notificationView.SetShowActivity(true, true);
			notificationView.Show (true);

			json.ContentType = "application/json";

			try {
				json.PostData = Newtonsoft.Json.JsonConvert.SerializeObject (data);

				var endpoint = String.Concat(Globals.EndpointBase, "/api/v1/account/add_todo");

				await json.PostAsync(endpoint);

				json.XPath = "/json/status";
				if ("\"success\"" == json.XText) {
					appDelegate.navigationController.PopViewController(true);

					await TodoListView._kludge.LoadTodo();
					TodoListView._kludge.dataSource.ReloadData();
					TodoListView._kludge.listView.ReloadData();
				}
				else {
					json.XPath = "/json/data/message";
					var newStr = json.XText.Replace("\"", "");
					DisplayAlert("Alert", newStr, "OK");
				}
			}
			catch (Exception e) {
				Application.Debug(e.Message);

				DisplayAlert ("Alert", "Unable to POST the todo", "OK");
			}

			notificationView.Hide (true);

			Monitor.Exit(TodoDataEntry.POSTLock);
		}
コード例 #36
0
        public static List <Organization> GetUserOrganizations()
        {
            List <Organization> organizations = new List <Organization>();

            string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserUniqueName));

                var items = authContext.TokenCache.ReadItems().ToList();


                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                items = authContext.TokenCache.ReadItems().ToList();


                // Get a list of Organizations of which the user is a member
                string requestUrl = string.Format("{0}/tenants?api-version={1}", ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"],
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Tenant Objects
                // id                                            tenantId
                // --                                            --------
                // /tenants/7fe877e6-a150-4992-bbfe-f517e304dfa0 7fe877e6-a150-4992-bbfe-f517e304dfa0
                // /tenants/62e173e9-301e-423e-bcd4-29121ec1aa24 62e173e9-301e-423e-bcd4-29121ec1aa24

                if (response.IsSuccessStatusCode)
                {
                    string responseContent     = response.Content.ReadAsStringAsync().Result;
                    var    organizationsResult = (Json.Decode(responseContent)).value;

                    foreach (var organization in organizationsResult)
                    {
                        organizations.Add(new Organization()
                        {
                            Id = organization.tenantId,
                            //DisplayName = AzureADGraphAPIUtil.GetOrganizationDisplayName(organization.tenantId),
                            objectIdOfCloudSenseServicePrincipal =
                                AzureADGraphAPIUtil.GetObjectIdOfServicePrincipalInOrganization(organization.tenantId, ConfigurationManager.AppSettings["ida:ClientID"])
                        });
                    }
                }
            }
            catch { }
            return(organizations);
        }
コード例 #37
0
ファイル: NewsController.cs プロジェクト: zhengknight/NH.Core
        public JsonResult Create(UsersRequest request)
        {
            //添加用户
            //for (int i = 0; i < 5000; i++)
            //{
            //    var rdm = new Random().Next(10000000, 999999999);
            //    Users user = new Users()
            //    {
            //        Email = rdm + "@qq.com",
            //        Id = Guid.NewGuid().GuidTo16String(),
            //        LoginIp = "127.0.0.1",
            //        LoginTime = DateTime.Now.AddDays(-new Random().Next(1000, 9999)),
            //        Mobile = "150" + new Random().Next(100000, 999999),
            //        Password = "******",
            //        Sex = rdm % 3,
            //        Status = rdm % 4,
            //        UserName = $"tibos_{i}"
            //    };
            //    _UsersIService.Save(user);
            //}

            //添加菜单
            //Navigation model_0 = new Navigation()
            //{
            //    Id = Guid.NewGuid().GuidTo16String(),
            //    Areas = "CMS",
            //    ControllerName = "News",
            //    IsSys = 0,
            //    Level = 1,
            //    Name = "资讯列表",
            //    ParentId = "",
            //    Sort = 1,
            //    Link = "#"
            //};
            //Navigation model_1 = new Navigation()
            //{
            //    Id = Guid.NewGuid().GuidTo16String(),
            //    Areas = "CMS",
            //    ControllerName = "News",
            //    IsSys = 0,
            //    Level = 2,
            //    Name = "资讯列表",
            //    ParentId = model_0.Id,
            //    Sort = 1
            //};
            //model_1.Link = $"/{model_1.Areas}/{model_1.ControllerName}/Index";
            //_NavigationIService.Save(model_0);
            //_NavigationIService.Save(model_1);



            //Navigation model_2 = new Navigation()
            //{
            //    Id = Guid.NewGuid().GuidTo16String(),
            //    Areas = "SYS",
            //    ControllerName = "Navigation",
            //    IsSys = 1,
            //    Level = 1,
            //    Name = "系统设置",
            //    ParentId = "",
            //    Sort = 1,
            //    Link = "#"
            //};
            //Navigation model_3 = new Navigation()
            //{
            //    Id = Guid.NewGuid().GuidTo16String(),
            //    Areas = "SYS",
            //    ControllerName = "Navigation",
            //    IsSys = 0,
            //    Level = 2,
            //    Name = "菜单列表",
            //    ParentId = model_2.Id,
            //    Sort = 1
            //};
            //model_3.Link = $"/{model_3.Areas}/{model_3.ControllerName}/Index";
            //_NavigationIService.Save(model_2);
            //_NavigationIService.Save(model_3);



            Json reponse = new Json();

            reponse.code   = 200;
            reponse.status = 0;
            return(Json(reponse));
        }
コード例 #38
0
        public static bool ServicePrincipalHasReadAccessToSubscription(string subscriptionId, string organizationId)
        {
            bool ret = false;

            try
            {
                // Aquire App Only Access Token to call Azure Resource Manager - Client Credential OAuth Flow
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId));
                AuthenticationResult  result      = authContext.AcquireToken(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential);


                // Get permissions of the app on the subscription
                string requestUrl = string.Format("{0}/subscriptions/{1}/providers/microsoft.authorization/permissions?api-version={2}",
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], subscriptionId, ConfigurationManager.AppSettings["ida:ARMAuthorizationPermissionsAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Actions and NotActions
                // actions  notActions
                // -------  ----------
                // {*}      {Microsoft.Authorization/*/Write, Microsoft.Authorization/*/Delete}
                // {*/read} {}

                if (response.IsSuccessStatusCode)
                {
                    string responseContent   = response.Content.ReadAsStringAsync().Result;
                    var    permissionsResult = (Json.Decode(responseContent)).value;

                    foreach (var permissions in permissionsResult)
                    {
                        bool permissionMatch = false;
                        foreach (string action in permissions.actions)
                        {
                            if (action.Equals("*/read", StringComparison.CurrentCultureIgnoreCase) || action.Equals("*", StringComparison.CurrentCultureIgnoreCase))
                            {
                                permissionMatch = true;
                                break;
                            }
                        }
                        // if one of the actions match, check that the NotActions don't
                        if (permissionMatch)
                        {
                            foreach (string notAction in permissions.notActions)
                            {
                                if (notAction.Equals("*", StringComparison.CurrentCultureIgnoreCase) || notAction.EndsWith("/read", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    permissionMatch = false;
                                    break;
                                }
                            }
                        }
                        if (permissionMatch)
                        {
                            ret = true;
                            break;
                        }
                    }
                }
            }
            catch { }

            return(ret);
        }
コード例 #39
0
ファイル: Studio.cs プロジェクト: Unimat2809/Myra
        private Stylesheet StylesheetFromFile(string path)
        {
            var data = File.ReadAllText(path);
            var root = (Dictionary <string, object>)Json.Deserialize(data);

            var folder = Path.GetDirectoryName(path);

            // Load texture atlases
            var textureAtlases = new Dictionary <string, TextureRegionAtlas>();
            Dictionary <string, object> textureAtlasesNode;

            if (root.GetStyle("textureAtlases", out textureAtlasesNode))
            {
                foreach (var pair in textureAtlasesNode)
                {
                    var atlasPath = BuildPath(folder, pair.Key.ToString());
                    var imagePath = BuildPath(folder, pair.Value.ToString());
                    using (var stream = File.OpenRead(imagePath))
                    {
                        var texture = Texture2D.FromStream(GraphicsDevice, stream);

                        var atlasData = File.ReadAllText(atlasPath);
                        textureAtlases[pair.Key] = TextureRegionAtlas.FromJson(atlasData, texture);
                    }
                }
            }

            // Load fonts
            var fonts = new Dictionary <string, SpriteFont>();
            Dictionary <string, object> fontsNode;

            if (root.GetStyle("fonts", out fontsNode))
            {
                foreach (var pair in fontsNode)
                {
                    var fontPath = BuildPath(folder, pair.Value.ToString());

                    var fontData = File.ReadAllText(fontPath);
                    fonts[pair.Key] = SpriteFontHelper.LoadFromFnt(fontData,
                                                                   s =>
                    {
                        if (s.Contains("#"))
                        {
                            var parts = s.Split('#');

                            return(textureAtlases[parts[0]][parts[1]]);
                        }

                        var imagePath = BuildPath(folder, s);
                        using (var stream = File.OpenRead(imagePath))
                        {
                            var texture = Texture2D.FromStream(GraphicsDevice, stream);

                            return(new TextureRegion(texture));
                        }
                    });
                }
            }

            return(Stylesheet.CreateFromSource(data,
                                               s =>
            {
                TextureRegion result;
                foreach (var pair in textureAtlases)
                {
                    if (pair.Value.Regions.TryGetValue(s, out result))
                    {
                        return result;
                    }
                }

                throw new Exception(string.Format("Could not find texture region '{0}'", s));
            },
                                               s =>
            {
                SpriteFont result;

                if (fonts.TryGetValue(s, out result))
                {
                    return result;
                }

                throw new Exception(string.Format("Could not find font '{0}'", s));
            }
                                               ));
        }
コード例 #40
0
        public string GetEmployees()
        {
            var people = Munq.MVC3.MunqDependencyResolver.Container.Resolve <IGetEmployee>().Execute();

            return(Json.Encode(people));
        }
コード例 #41
0
ファイル: JsonTests.cs プロジェクト: ibebbs/Wyam
            public void ReturnsDocumentOnError()
            {
                // Given
                RemoveListener();
                IDocument document = Substitute.For<IDocument>();
                document.Content.Returns("asdf");
                document.Source.Returns(string.Empty);
                IExecutionContext context = Substitute.For<IExecutionContext>();
                Json json = new Json("MyJson");

                // When
                List<IDocument> results = json.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(0).GetDocument(Arg.Any<IDocument>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>());
                Assert.IsTrue(results.Single().Equals(document));
            }
コード例 #42
0
        public Task <JiraIssueDto[]> GetAll()
        {
            return(InvokeByLock(() =>
            {
                var allAttachments = new Dictionary <long, JiraAttachment>();
                foreach (var pair in attachmentsHeaders.ReadAll())
                {
                    allAttachments[pair.Key] =
                        Json.Deserialize <JiraAttachment>(Encoding.UTF8.GetString(pair.Value));
                }
                var attachmentsIndex = new Dictionary <long, JiraAttachment[]>();
                foreach (var pair in issueAttachmentsIndex.ReadAll())
                {
                    var attachmentIds = LongArrayFromBytes(pair.Value);
                    var issueAttachments = new JiraAttachment[attachmentIds.Length];
                    for (var i = 0; i < attachmentIds.Length; ++i)
                    {
                        issueAttachments[i] = allAttachments[attachmentIds[i]];
                    }
                    attachmentsIndex[pair.Key] = issueAttachments;
                }

                var allComments = new Dictionary <long, JiraComment>();
                foreach (var pair in commentsStorage.ReadAll())
                {
                    allComments[pair.Key] = Json.Deserialize <JiraComment>(Encoding.UTF8.GetString(pair.Value));
                }

                var commentsIndex = new Dictionary <long, JiraComment[]>();
                foreach (var pair in issueCommentsIndex.ReadAll())
                {
                    var commentIds = LongArrayFromBytes(pair.Value);
                    var issueComments = new JiraComment[commentIds.Length];
                    for (var i = 0; i < commentIds.Length; ++i)
                    {
                        issueComments[i] = allComments[commentIds[i]];
                    }
                    commentsIndex[pair.Key] = issueComments;
                }

                var issues = new List <JiraIssueDto>();
                foreach (var pair in issueStorage.ReadAll())
                {
                    var jiraIssueDto = JiraIssueDto.FromBytes(pair.Value);
                    var keyId = ExtractLong(jiraIssueDto.Key);
                    if (attachmentsIndex.TryGetValue(keyId, out var a))
                    {
                        jiraIssueDto.IssueFields.SetProperty("attachment", a);
                    }
                    else
                    {
                        jiraIssueDto.IssueFields.SetProperty("attachment", emptyAttachments);
                    }
                    if (!commentsIndex.TryGetValue(keyId, out var c))
                    {
                        c = emptyComments;
                    }
                    jiraIssueDto.IssueFields.SetProperty("comment", new JiraIssueComments
                    {
                        Comments = c,
                        StartAt = 0,
                        Total = c.Length,
                        MaxResults = c.Length
                    });
                    issues.Add(jiraIssueDto);
                }

                return issues.ToArray();
            }));
        }
コード例 #43
0
 /// <summary>
 ///     Logs a purchase event in your application. The string can be any
 ///     value of your choosing, however in most cases you will want to use
 ///     Leanplum.PURCHASE_EVENT_NAME
 /// </summary>
 public override void TrackPurchase(string eventName, double value, string currencyCode,
                                    IDictionary <string, object> parameters)
 {
     NativeSDK.CallStatic("trackPurchase", eventName, value, currencyCode, Json.Serialize(parameters));
 }
コード例 #44
0
 /// <summary>
 ///     Logs a particular event in your application. The string can be
 ///     any value of your choosing, and will show up in the dashboard.
 ///     To track purchases, use Leanplum.PURCHASE_EVENT_NAME as the event name.
 /// </summary>
 public override void Track(string eventName, double value, string info,
                            IDictionary <string, object> parameters)
 {
     NativeSDK.CallStatic("track", eventName, value, info, Json.Serialize(parameters));
 }
コード例 #45
0
 public XmlJsonWriter(Json.IJsonWriter writer)
 {
   _writer = writer;
 }
コード例 #46
0
        /// <summary>
        /// Generate mapping from Minecraft blocks.jsom
        /// </summary>
        /// <param name="blocksJsonFile">path to blocks.json</param>
        /// <param name="outputClass">output path for blocks.cs</param>
        /// <param name="outputEnum">output path for material.cs</param>
        /// <remarks>java -cp minecraft_server.jar net.minecraft.data.Main --reports</remarks>
        /// <returns>state => block name mappings</returns>
        public static void JsonToClass(string blocksJsonFile, string outputClass, string outputEnum = null)
        {
            HashSet<int> knownStates = new HashSet<int>();
            Dictionary<string, HashSet<int>> blocks = new Dictionary<string, HashSet<int>>();

            Json.JSONData palette = Json.ParseJson(File.ReadAllText(blocksJsonFile));
            foreach (KeyValuePair<string, Json.JSONData> item in palette.Properties)
            {
                //minecraft:item_name => ItemName
                string blockType = String.Concat(
                    item.Key.Replace("minecraft:", "")
                    .Split('_')
                    .Select(word => char.ToUpper(word[0]) + word.Substring(1))
                );

                if (blocks.ContainsKey(blockType))
                    throw new InvalidDataException("Duplicate block type " + blockType + "!?");
                blocks[blockType] = new HashSet<int>();

                foreach (Json.JSONData state in item.Value.Properties["states"].DataArray)
                {
                    int id = int.Parse(state.Properties["id"].StringValue);

                    if (knownStates.Contains(id))
                        throw new InvalidDataException("Duplicate state id " + id + "!?");

                    knownStates.Add(id);
                    blocks[blockType].Add(id);
                }
            }

            HashSet<string> materials = new HashSet<string>();
            List<string> outFile = new List<string>();
            outFile.AddRange(new[] {
                "using System;",
                "using System.Collections.Generic;",
                "",
                "namespace MinecraftClient.Mapping.BlockPalettes",
                "{",
                "    public class PaletteXXX : PaletteMapping",
                "    {",
                "        private static Dictionary<int, Material> materials = new Dictionary<int, Material>();",
                "",
                "        static PaletteXXX()",
                "        {",
            });

            foreach (KeyValuePair<string, HashSet<int>> blockType in blocks)
            {
                if (blockType.Value.Count > 0)
                {
                    List<int> idList = blockType.Value.ToList();
                    string materialName = blockType.Key;
                    materials.Add(materialName);

                    if (idList.Count > 1)
                    {
                        idList.Sort();
                        Queue<int> idQueue = new Queue<int>(idList);

                        while (idQueue.Count > 0)
                        {
                            int startValue = idQueue.Dequeue();
                            int endValue = startValue;
                            while (idQueue.Count > 0 && idQueue.Peek() == endValue + 1)
                                endValue = idQueue.Dequeue();
                            if (endValue > startValue)
                            {
                                outFile.Add("            for (int i = " + startValue + "; i <= " + endValue + "; i++)");
                                outFile.Add("                materials[i] = Material." + materialName + ";");
                            }
                            else outFile.Add("            materials[" + startValue + "] = Material." + materialName + ";");
                        }
                    }
                    else outFile.Add("            materials[" + idList[0] + "] = Material." + materialName + ";");
                }
                else throw new InvalidDataException("No state id  for block type " + blockType.Key + "!?");
            }

            outFile.AddRange(new[] {
                "        }",
                "",
                "        protected override Dictionary<int, Material> GetDict()",
                "        {",
                "            return materials;",
                "        }",
                "    }",
                "}"
            });

            File.WriteAllLines(outputClass, outFile);

            if (outputEnum != null)
            {
                outFile = new List<string>();
                outFile.AddRange(new[] {
                    "namespace MinecraftClient.Mapping",
                    "{",
                    "    public enum Material",
                    "    {"
                });
                foreach (string material in materials)
                    outFile.Add("        " + material + ",");
                outFile.AddRange(new[] {
                    "    }",
                    "}"
                });
                File.WriteAllLines(outputEnum, outFile);
            }
        }
コード例 #47
0
        public override void TrackMessageEvent(string eventName, double value, string info, IDictionary <string, object> param)
        {
            var paramJson = param != null?Json.Serialize(param) : "";

            nativeHandle.CallStatic("trackMessageEvent", Name, eventName, value, info, paramJson);
        }
コード例 #48
0
        public void should_serialize_custom_exception_to_json()
        {
            var command = new { returncode = "1", message = "Key init was not called prior to Set Password command" };

            var _jsonObject = new Json<object>();
            _jsonStringFromCustomException = "{\"returncode\":\"1\",\"message\":\"Key init was not called prior to Set Password command\"}";
            Assert.AreEqual(_jsonStringFromCustomException, _jsonObject.Serialize(command));
        }
コード例 #49
0
 public string Encode(object obj)
 {
     return(Json.Encode(obj));
 }
コード例 #50
0
ファイル: error.cs プロジェクト: GNOME/chronojump
    private void on_button_send_log_clicked(object o, EventArgs args)
    {
        string email = entry_send_log.Text.ToString();
        //email can be validated with Util.IsValidEmail(string)
        //or other methods, but maybe there's no need of complexity now

        //1st save email on sqlite
        if(email != null && email != "" && email != "0" && email != emailStored)
            SqlitePreferences.Update("email", email, false);

        //2nd if there are comments, add them at the beginning of the file
        string comments = textview_comments.Buffer.Text;

        //2nd send Json
        Json js = new Json();
        bool success = js.PostCrashLog(email, comments);

        if(success) {
            button_send_log.Label = Catalog.GetString("Thanks");
            button_send_log.Sensitive = false;

            image_send_log_yes.Show();
            image_send_log_no.Hide();
            LogB.Information(js.ResultMessage);
        } else {
            button_send_log.Label = Catalog.GetString("Try again");

            image_send_log_yes.Hide();
            image_send_log_no.Show();
            LogB.Error(js.ResultMessage);
        }

        label_send_log_message.Text = js.ResultMessage;
    }
コード例 #51
0
		private IEnumerable<BingAddress> ParseResponse(Json.Response response)
		{
			foreach (Json.Location location in response.ResourceSets[0].Resources)
			{
				yield return new BingAddress(
					location.Address.FormattedAddress,
					new Location(location.Point.Coordinates[0], location.Point.Coordinates[1]),
					location.Address.AddressLine,
					location.Address.AdminDistrict,
					location.Address.AdminDistrict2,
					location.Address.CountryRegion,
					location.Address.Locality,
					location.Address.PostalCode,
					(EntityType)Enum.Parse(typeof(EntityType), location.EntityType),
					EvaluateConfidence(location.Confidence)
				);
			}
		}
コード例 #52
0
        public static ImpressionData FromJson(string json)
        {
            var impData = new ImpressionData();

            if (String.IsNullOrEmpty(json))
            {
                return(impData);
            }

            var fields = Json.Deserialize(json) as Dictionary <string, object>;

            if (fields == null)
            {
                return(impData);
            }

            object obj;
            double parsedDouble;
            int    parsedInt;

            if (fields.TryGetValue("adunit_id", out obj) && obj != null)
            {
                impData.AdUnitId = obj.ToString();
            }

            if (fields.TryGetValue("adunit_name", out obj) && obj != null)
            {
                impData.AdUnitName = obj.ToString();
            }

            if (fields.TryGetValue("adunit_format", out obj) && obj != null)
            {
                impData.AdUnitFormat = obj.ToString();
            }

            if (fields.TryGetValue("id", out obj) && obj != null)
            {
                impData.ImpressionId = obj.ToString();
            }

            if (fields.TryGetValue("currency", out obj) && obj != null)
            {
                impData.Currency = obj.ToString();
            }

            if (fields.TryGetValue("publisher_revenue", out obj) && obj != null &&
                Double.TryParse(obj.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedDouble))
            {
                impData.PublisherRevenue = parsedDouble;
            }

            if (fields.TryGetValue("adgroup_id", out obj) && obj != null)
            {
                impData.AdGroupId = obj.ToString();
            }

            if (fields.TryGetValue("adgroup_name", out obj) && obj != null)
            {
                impData.AdGroupName = obj.ToString();
            }

            if (fields.TryGetValue("adgroup_type", out obj) && obj != null)
            {
                impData.AdGroupType = obj.ToString();
            }

            if (fields.TryGetValue("adgroup_priority", out obj) && obj != null &&
                Int32.TryParse(obj.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedInt))
            {
                impData.AdGroupPriority = parsedInt;
            }

            if (fields.TryGetValue("country", out obj) && obj != null)
            {
                impData.Country = obj.ToString();
            }

            if (fields.TryGetValue("precision", out obj) && obj != null)
            {
                impData.Precision = obj.ToString();
            }

            if (fields.TryGetValue("network_name", out obj) && obj != null)
            {
                impData.NetworkName = obj.ToString();
            }

            if (fields.TryGetValue("network_placement_id", out obj) && obj != null)
            {
                impData.NetworkPlacementId = obj.ToString();
            }

            impData.JsonRepresentation = json;

            return(impData);
        }
コード例 #53
0
 public VisTableJsonWriter(Json.IJsonWriter writer)
 {
   _writer = writer;
   _writer.Object();
 }
コード例 #54
0
        /// <summary>
        /// 获取查询数据的JSON结果(多表查询,WEB用)
        /// </summary>
        /// <param name="sqlCmdName">执行的SQL</param>
        ///<param name="filter">查询参数</param>
        ///<param name="where">过滤语句</param>
        ///<param name="orderBy">结果排序</param>
        /// <param name="hsDDL">列表中的下拉框</param>
        /// <returns>JSON结果</returns>
        public string GetCmdQueryData(string sqlCmdName, Hashtable filter, string where, string orderBy, Hashtable hsDDL)
        {
            #region 查询结果集

            /*
             * command.config文件
             * SELECT T_.*, ROW_NUMBER() OVER(ORDER BY 行号标志字段) RN  FROM ( SQL语句) T_  WHERE 1=1
             */
            int pageindex = 0, pagesize = 0;
            int draw = 0;
            if (HttpContext.Current.Request["draw"] != null)
            {
                int.TryParse(HttpContext.Current.Request["draw"], out draw);
            }
            if (HttpContext.Current.Request["start"] != null)
            {
                int.TryParse(HttpContext.Current.Request["start"], out pageindex);
            }
            pageindex = pageindex == 0 ? 1 : pageindex;
            if (HttpContext.Current.Request["length"] != null)
            {
                int.TryParse(HttpContext.Current.Request["length"], out pagesize);
            }
            if (pagesize == 0)
            {
                pageindex = 1;
            }
            else
            {
                pageindex = pageindex / pagesize + 1;
            }
            if (pagesize == 0)
            {
                pagesize = 10;//默认10条
            }
            if (!string.IsNullOrEmpty(orderBy))
            {
                orderBy = " order by " + orderBy;
            }

            var cmd = ds.GetCommand(sqlCmdName);
            DacHelper.PrepareCommand(cmd, filter);

            if (!string.IsNullOrEmpty(where))
            {
                if (!where.Trim().ToLower().StartsWith("and"))
                {
                    cmd.DbCommand.CommandText += " AND " + where;
                }
                else
                {
                    cmd.DbCommand.CommandText += where;
                }
            }

            var oldCmdText = cmd.DbCommand.CommandText;
            cmd.DbCommand.CommandText = string.Format("select count(1) from ({0}) c_", oldCmdText);
            object count = cmd.ExecuteScalar();
            cmd.DbCommand.CommandText = string.Format("select * from ({0}) list_ where list_.RN>{1} and list_.RN<={2} {3}", oldCmdText, pagesize * (pageindex - 1), pagesize * pageindex, orderBy);
            var dt = cmd.ExecuteDataTable();

            if (hsDDL != null && hsDDL.Count > 0)
            {
                cod.ConvertTabDdl(dt, hsDDL);
            }

            #endregion 查询结果集

            #region 新增"审批类型",“审批岗位描述”两列

            //添加"审批类型",“审批岗位描述”两列
            dt.Columns.Add("APPROVE_TYPE", typeof(string));        //数据类型为 文本
            dt.Columns.Add("POST_NOTE", typeof(string));           //数据类型为 文本
            //添加"撤销审批类型",“撤销审批岗位描述”两列
            dt.Columns.Add("REVOKE_APPROVE_TYPE", typeof(string)); //数据类型为 文本
            dt.Columns.Add("REVOKE_POST_NOTE", typeof(string));    //数据类型为 文本

            #endregion 新增"审批类型",“审批岗位描述”两列

            #region 给"审批类型",“审批岗位描述”两列赋值

            foreach (DataRow row in dt.Rows)
            {
                //审批类型
                row["APPROVE_TYPE"] = GetApproveType(row["DOC_TYPE"].ToString(), WKF_VLAUES.DECLARE_TYPE_D);
                //审批岗位描述
                row["POST_NOTE"] = GetPostNote(row["DOC_TYPE"].ToString());
                //撤销审批类型
                row["REVOKE_APPROVE_TYPE"] = GetApproveType(row["DOC_TYPE"].ToString(), WKF_VLAUES.DECLARE_TYPE_R);
                //撤销审批岗位描述
                row["REVOKE_POST_NOTE"] = GetPostNote_Revoke(row["DOC_TYPE"].ToString());
            }

            #endregion 给"审批类型",“审批岗位描述”两列赋值

            //return string.Format("{{\"total\":{0},\"rows\":[{1}]}}", count == null ? 0 : Convert.ToInt32(count), Json.DatatableToJson(dt));
            return(string.Format("{{\"draw\":{0},\"recordsTotal\":{1},\"recordsFiltered\":{2},\"data\":[{3}]}}", draw, count == null ? 0 : Convert.ToInt32(count), dt.Rows.Count, Json.DatatableToJson(dt)));
        }
コード例 #55
0
ファイル: error.cs プロジェクト: GNOME/chronojump
    private void on_button_check_last_version_clicked(object o, EventArgs args)
    {
        Json js = new Json();
        bool success = js.GetLastVersion(progVersion);

        if(success) {
            LogB.Information(js.ResultMessage);
            new DialogMessage(
                    "Chronojump",
                    Constants.MessageTypes.INFO,
                    js.ResultMessage
                    );
        }
        else {
            LogB.Error(js.ResultMessage);
            new DialogMessage(
                    "Chronojump",
                    Constants.MessageTypes.WARNING,
                    js.ResultMessage);
        }
    }
コード例 #56
0
        public static object FromJson(this string json, Type objectType)
        {
            var value = Json.Parse(json);

            return(JsonSerializationReader.ReadObject(value, objectType));
        }
コード例 #57
0
            void HttpRequest.Listener.onComplete(HttpRequest.Result result)
            {
                Error retError  = Error.Generic;
                bool  userNew   = false;
                bool  deviceNew = false;

                if (Error.Success == result.ErrorCode)
                {
                    try
                    {
                        var dict = Json.Deserialize(result.Response) as Dictionary <string, object>;
                        if (dict.ContainsKey("error") && (Error.Success == (Error)Enum.ToObject(typeof(Error), dict["error"])))
                        {
                            if (dict.ContainsKey("data"))
                            {
                                var ret = dict["data"] as Dictionary <string, object>;

                                // NOTE: deviceId should only be set during the callback from init()
                                if ((null != ret) && ret.ContainsKey("deviceid") && isValidId(ret["deviceid"] as string))
                                {
                                    deviceNew = ret.ContainsKey("devicenew") ? (bool)ret["devicenew"] : false;

                                    DeviceId = ret["deviceid"] as string;

                                    if (null != DeviceId)
                                    {
                                        // Save it off
                                        Prefs.Add(DEVICEID_KEY_NAME, DeviceId);

                                        if (ret.ContainsKey("devicetuning"))
                                        {
                                            var deviceTuning = ret["devicetuning"] as IDictionary <string, object>;
                                            if (null != deviceTuning)
                                            {
                                                mTuningUpdater.onUpdate(Constants.ENTITY_TYPE_DEVICE, DeviceId, deviceTuning);
                                            }
                                        }
                                    }
                                }

                                // now handle the user id if there is one
                                if ((null != ret) && ret.ContainsKey("userid") && isValidId(ret["userid"] as string))
                                {
                                    userNew = ret.ContainsKey("usernew") ? (bool)ret["usernew"] : false;

                                    UserId = ret["userid"] as string;

                                    if (null != UserId)
                                    {
                                        if (ret.ContainsKey("usertuning"))
                                        {
                                            var userTuning = ret["usertuning"] as IDictionary <string, object>;
                                            if (null != userTuning)
                                            {
                                                mTuningUpdater.onUpdate(Constants.ENTITY_TYPE_USER, UserId, userTuning);
                                            }
                                        }

                                        if (!sRegisteredUsers.Contains(UserId))
                                        {
                                            sRegisteredUsers.Add(UserId);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            string desc = null;
                            if (dict.ContainsKey("description"))
                            {
                                desc = dict["description"] as string;
                            }
                            Util.logError(String.Format("Problem on initialization [{0}]", (null != desc) ? desc : "Unknown"));
                            retError = Error.Generic;
                        }
                    }
                    catch (Exception)
                    {
                        Util.logError("Exception during intialization: " + result.Response);
                        retError = Error.Generic;
                    }

                    mTuningUpdater.commit();
                }
                else
                {
                    // Request failure (likely a timeout), pass it through
                    Util.logError("Initialization call failed: code " + result.ErrorCode);
                    retError = result.ErrorCode;
                }


                // even if the init call failed, all is well as long as we AT LEAST have a device id
                if (isValidId(DeviceId))
                {
                    // If initialization is successful, we can initialize the EventDepot
                    EventDepot.init(Host, getQueryParms(), ReqTimeout);

                    Initialized = true;

                    // queue up some telemetry for the initial state...
                    if (null != mDeviceProperties)
                    {
                        new DataPointBuilder("datacollector_updateDeviceState").setArg(mDeviceProperties).send();
                    }
                    if (null != mUserProperties)
                    {
                        new DataPointBuilder("datacollector_updateUserState").setArg(mUserProperties).send();
                    }
                    if (deviceNew)
                    {
                        new DataPointBuilder("datacollector_newDevice").send();
                    }
                    if (userNew)
                    {
                        new DataPointBuilder("datacollector_newUser").send();
                    }

                    // TODO - decide if we want to send a TuningFailed error at this point, if there was some kind of error?

                    retError = Error.Success;
                }

                // Call the callback
                if (null != mCallback)
                {
                    mCallback(retError);
                }
            }
コード例 #58
0
 public static async Task SaveAsync <T>(this ApplicationDataContainer settings, string key, T value)
 {
     settings.SaveString(key, await Json.StringifyAsync(value));
 }
コード例 #59
0
        protected override bool InternalExecute(ProcessExecutingContext context)
        {
            if (EntitySchemaUId == Guid.Empty)
            {
                return(true);
            }
            var deleteRights = !string.IsNullOrEmpty(DeleteRights)
                                ? Json.Deserialize <List <Dictionary <string, object> > >(DeleteRights)
                                : new List <Dictionary <string, object> >(0);
            var addRights = !string.IsNullOrEmpty(AddRights)
                                ? Json.Deserialize <List <Dictionary <string, object> > >(AddRights)
                                : new List <Dictionary <string, object> >(0);

            if (deleteRights.Count == 0 && addRights.Count == 0)
            {
                return(true);
            }
            EntitySchema entitySchema = UserConnection.EntitySchemaManager.FindInstanceByUId(EntitySchemaUId);

            if (entitySchema == null)
            {
                return(true);
            }
            if (!entitySchema.AdministratedByRecords)
            {
                return(true);
            }
            var entitySchemaQuery = new EntitySchemaQuery(entitySchema)
            {
                UseAdminRights = false
            };

            entitySchemaQuery.PrimaryQueryColumn.IsAlwaysSelect = true;
            if (!string.IsNullOrEmpty(DataSourceFilters))
            {
                ProcessUserTaskUtilities.SpecifyESQFilters(UserConnection, this, entitySchema, entitySchemaQuery,
                                                           DataSourceFilters);
                bool isEmptyFilter = entitySchemaQuery.Filters.Count == 0;
                if (!isEmptyFilter && entitySchemaQuery.Filters.Count == 1)
                {
                    var filterGroup = entitySchemaQuery.Filters[0] as EntitySchemaQueryFilterCollection;
                    if (filterGroup != null && filterGroup.Count == 0)
                    {
                        return(true);
                    }
                }
            }
            Select selectQuery        = entitySchemaQuery.GetSelectQuery(UserConnection);
            var    entityRecordIdList = new List <Guid>();

            selectQuery.ExecuteReader(reader => {
                Guid entityRecordId = reader.GetGuid(0);
                entityRecordIdList.Add(entityRecordId);
            });
            DBSecurityEngine dbSecurityEngine    = UserConnection.DBSecurityEngine;
            string           schemaName          = entitySchema.Name;
            bool             useDenyRecordRights = entitySchema.UseDenyRecordRights;

            foreach (Guid entityRecordId in entityRecordIdList)
            {
                foreach (Dictionary <string, object> deleteRight in deleteRights)
                {
                    DeleteRecordRight(dbSecurityEngine, entityRecordId, schemaName, deleteRight);
                }
                for (int i = addRights.Count - 1; i >= 0; i--)
                {
                    AddRecordRight(dbSecurityEngine, entityRecordId, schemaName, useDenyRecordRights, addRights[i]);
                }
            }
            return(true);
        }
コード例 #60
0
        public List <string> Translate(string sourceLanguage, string targetLanguage, List <Paragraph> paragraphs, StringBuilder log)
        {
            string result;
            var    input       = new StringBuilder();
            var    formattings = new Formatting[paragraphs.Count];

            for (var index = 0; index < paragraphs.Count; index++)
            {
                var p = paragraphs[index];
                var f = new Formatting();
                formattings[index] = f;
                if (input.Length > 0)
                {
                    input.Append(" " + SplitChar + " ");
                }
                var text = f.SetTagsAndReturnTrimmed(TranslationHelper.PreTranslate(p.Text.Replace(SplitChar.ToString(), string.Empty), sourceLanguage), sourceLanguage);
                text = f.Unbreak(text, p.Text);
                input.Append(text);
            }

            using (var wc = new WebClient())
            {
                string url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={sourceLanguage}&tl={targetLanguage}&dt=t&q={Utilities.UrlEncode(input.ToString())}";
                wc.Proxy    = Utilities.GetProxy();
                wc.Encoding = Encoding.UTF8;
                wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
                result = wc.DownloadString(url).Trim();
            }

            var sbAll = new StringBuilder();
            int count = 0;
            int i     = 1;
            int level = result.StartsWith('[') ? 1 : 0;

            while (i < result.Length - 1)
            {
                var sb    = new StringBuilder();
                var start = false;
                for (; i < result.Length - 1; i++)
                {
                    var c = result[i];
                    if (start)
                    {
                        if (c == '"' && result[i - 1] != '\\')
                        {
                            count++;
                            if (count % 2 == 1 && level > 2 && level < 5) // even numbers are original text, level 3 is translation
                            {
                                sbAll.Append(" " + sb);
                            }

                            i++;
                            break;
                        }
                        sb.Append(c);
                    }
                    else if (c == '"')
                    {
                        start = true;
                    }
                    else if (c == '[')
                    {
                        level++;
                    }
                    else if (c == ']')
                    {
                        level--;
                    }
                }
            }

            var res = sbAll.ToString().Trim();

            res = Regex.Unescape(res);
            var lines      = res.SplitToLines().ToList();
            var resultList = new List <string>();

            for (var index = 0; index < lines.Count; index++)
            {
                var line = lines[index];
                var s    = Json.DecodeJsonText(line);
                s = string.Join(Environment.NewLine, s.SplitToLines());
                s = TranslationHelper.PostTranslate(s, targetLanguage);
                s = s.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
                s = s.Replace(Environment.NewLine + " ", Environment.NewLine);
                s = s.Replace(Environment.NewLine + " ", Environment.NewLine);
                s = s.Replace(" " + Environment.NewLine, Environment.NewLine);
                s = s.Replace(" " + Environment.NewLine, Environment.NewLine).Trim();
                if (formattings.Length > index)
                {
                    s = formattings[index].ReAddFormatting(s);
                    s = formattings[index].Rebreak(s);
                }

                resultList.Add(s);
            }

            if (resultList.Count > paragraphs.Count)
            {
                var timmedList = resultList.Where(p => !string.IsNullOrEmpty(p)).ToList();
                if (timmedList.Count == paragraphs.Count)
                {
                    return(timmedList);
                }
            }

            if (resultList.Count < paragraphs.Count)
            {
                var splitList = SplitMergedLines(resultList, paragraphs);
                if (splitList.Count == paragraphs.Count)
                {
                    return(splitList);
                }
            }

            return(resultList);
        }