Exemplo n.º 1
0
 public T DeserializeAnonymousType <T>(string value, T anonymousTypeObject, bool serializeNonPublic = false, bool loopSerialize = false, bool useCamelCase = false)
 {
     return(JsonConvert.DeserializeAnonymousType(value, anonymousTypeObject,
                                                 JsonHelper.GetCustomJsonSerializerSettings(serializeNonPublic, loopSerialize, useCamelCase)));
 }
Exemplo n.º 2
0
        public static async Task <TResponse> ReadContent <TResponse>(this HttpResponseMessage response, TResponse anonymous)
        {
            string content = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeAnonymousType(content, anonymous));
        }
Exemplo n.º 3
0
        /// <summary>
        ///     采集品牌
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPickBrand(object sender, EventArgs e)
        {
            string url = ConfigurationManager.AppSettings["BrandsUrl"];

            Task.Run(async() =>
            {
                #region 品牌

                string task        = await SpiderFile.GetStringAsync(url);
                string brandStr    = task.Substring(14, task.Length - 15);
                JObject objJObject = (JObject)JsonConvert.DeserializeObject(brandStr);
                Dictionary <string, object> resultDictionary =
                    JsonConvert.DeserializeObject <Dictionary <string, object> >(objJObject["brand"].ToString());
                var definition = new[]
                {
                    new
                    {
                        type = string.Empty,
                        id   = 0,
                        name = string.Empty,
                        url  = string.Empty,
                        cur  = string.Empty,
                        num  = 0
                    }
                };
                IList <CarBrandEntity> listBrands = (from valuePair in resultDictionary
                                                     let result = JsonConvert.DeserializeAnonymousType(valuePair.Value.ToString(), definition)
                                                                  from brand in result
                                                                  where !string.IsNullOrEmpty(brand.url)
                                                                  let index = brand.url.IndexOf("mb_", StringComparison.Ordinal)
                                                                              let temp = brand.url.Substring(index + 3, brand.url.Length - index - 4)
                                                                                         select new CarBrandEntity
                {
                    AddTime = DateTime.Now,
                    BrandName = brand.name,
                    TagName = valuePair.Key,
                    Url = ConfigurationManager.AppSettings["Domain"] + brand.url,
                    Rid = brand.id
                })
                                                    .ToList();

                #endregion

                if (listBrands.Count > 0)
                {
                    CarBrandBusiness.ShowInfoEventHandler += CarBrandBusiness_ShowInfoEventHandler;
                    var parallelResult = Parallel.ForEach(listBrands, async carBrand =>
                    {
                        //                    foreach (var carBrand in listBrands)
                        //                    {

                        #region 并行处理

                        var replaceUrl = ConfigurationManager.AppSettings["LogoUrl"]
                                         .Replace("{0}", carBrand.Rid.ToString());
                        carBrand.BrandLogo =
                            await SpiderFile.DownImageAsync(replaceUrl, this._logoPath, "/Upload/logo/");
                        carBrand.Id = CarBrandBusiness.Insert(carBrand);

                        #region 车型

                        var modelTask = await SpiderFile.GetStringAsync($"{ConfigurationManager.AppSettings["BrandsUrl"]}&pagetype=masterbrand&objid={carBrand.Rid}");

                        string modelStr      = modelTask.Substring(14, modelTask.Length - 15);
                        JObject modelJObject = (JObject)JsonConvert.DeserializeObject(modelStr);
                        Dictionary <string, object> modelDictionary =
                            JsonConvert.DeserializeObject <Dictionary <string, object> >(modelJObject["brand"].ToString());
                        IList <CarModelEntity> carModels = new List <CarModelEntity>();
                        JArray array = JArray.FromObject(modelDictionary[carBrand.TagName]);
                        foreach (var token in array)
                        {
                            if (token["child"] != null)
                            {
                                JToken childArray = JToken.FromObject(token["child"]);
                                foreach (var child in childArray)
                                {
                                    if (child["child"] != null)
                                    {
                                        JToken childrenArray = JToken.FromObject(child["child"]);
                                        foreach (var model in childrenArray)
                                        {
                                            carModels.Add(new CarModelEntity
                                            {
                                                BrandId   = carBrand.Id,
                                                ModelName = model["name"].ToString(),
                                                Factory   = child["name"].ToString(),
                                                LinkUrl   = $"{ConfigurationManager.AppSettings["Domain"]}{model["url"]}",
                                                AddTime   = DateTime.Now,
                                            });
                                        }
                                    }
                                    else
                                    {
                                        carModels.Add(new CarModelEntity
                                        {
                                            BrandId   = carBrand.Id,
                                            ModelName = child["name"].ToString(),
                                            Factory   = carBrand.BrandName,
                                            LinkUrl   = $"{ConfigurationManager.AppSettings["Domain"]}{child["url"]}",
                                            AddTime   = DateTime.Now,
                                        });
                                    }
                                }
                                break;
                            }
                        }

                        #endregion

                        if (carModels.Count > 0)
                        {
                            //                            Task.Run(() => { Parallel.ForEach(carModels, model => { }); });
                            var document = new HtmlDocument();
                            CarModelBusiness.ShowInfoEventHandler  += CarModelBusiness_ShowInfoEventHandler;
                            CarSeriesBusiness.ShowInfoEventHandler += CarSeriesBusiness_ShowInfoEventHandler;
                            foreach (CarModelEntity carModel in carModels)
                            {
                                #region 车型入库

                                var htmlStream = await SpiderFile.GetStreamAsync(carModel.LinkUrl);
                                document.Load(htmlStream, Encoding.UTF8);
                                //全国参考价
                                HtmlNode infoNode      = document.DocumentNode.SelectSingleNode("//div[@class='desc']");
                                var referencePriceNode = infoNode.SelectSingleNode("//div[@class='top']/h5/a/em") ??
                                                         infoNode.SelectSingleNode("//div[@class='top']/h5/em");
                                carModel.NationalReferencePrice = referencePriceNode.InnerText.Trim();
                                //厂商指导价
                                var msrpNode  = infoNode.SelectSingleNode("//div[@class='mid row']/div[1]/h5");
                                carModel.Msrp = msrpNode.InnerText.Trim();
                                //二手车
                                var secondHandNode  = infoNode.SelectSingleNode("//div[@class='mid row']/div[2]/h5/a");
                                carModel.SecondHand = secondHandNode.InnerText.Trim();
                                //油耗
                                var fuelConsumptionNode =
                                    infoNode.SelectSingleNode("//div[@class='mid row']/div[3]/h5/a") ??
                                    infoNode.SelectSingleNode("//div[@class='mid row']/div[3]/h5");
                                if (fuelConsumptionNode != null)
                                {
                                    carModel.FuelConsumption = fuelConsumptionNode.InnerText.Trim();
                                }
                                HtmlNode imageNode =
                                    document.DocumentNode.SelectSingleNode("//div[@class='img']/a[1]/img[1]");
                                string imageUrl    = imageNode?.GetAttributeValue("src", null);
                                carModel.ImageUrl  = imageUrl;
                                carModel.ImagePath =
                                    await SpiderFile.DownImageAsync(imageUrl, this._modelPath, "/Upload/model/");
                                carModel.Id = CarModelBusiness.Insert(carModel);

                                #endregion


                                #region 车系入库

                                #region  ------------------在售------------------------

                                //在售
                                HtmlNodeCollection nodeCollection =
                                    document.DocumentNode.SelectNodes("//td[starts-with(@id,'carlist_')]");
                                if (nodeCollection != null && nodeCollection.Count > 0)
                                {
                                    foreach (HtmlNode node in nodeCollection)
                                    {
                                        if (node.FirstChild.Name == "a")
                                        {
                                            CarSeriesBusiness.Insert(new CarSeriesEntity
                                            {
                                                AddTime = DateTime.Now,
                                                LinkUrl =
                                                    $"{ConfigurationManager.AppSettings["Domain"]}{node.FirstChild.GetAttributeValue("href", null)}",
                                                ModelId    = carModel.Id,
                                                SeriesName = node.FirstChild.InnerText.Trim(),
                                            });
                                        }
                                    }
                                }

                                #endregion

                                #region  -------------------停售-----------------------

                                //停售
                                HtmlNodeCollection liNodeCollection =
                                    document.DocumentNode.SelectNodes("//div[@id='pop_nosalelist']/a");
                                if (liNodeCollection != null && liNodeCollection.Count > 0)
                                {
                                    foreach (HtmlNode node in liNodeCollection)
                                    {
                                        string href = node.GetAttributeValue("href", null);
                                        if (href != null)
                                        {
                                            HtmlDocument doc = new HtmlDocument();
                                            doc.Load(
                                                await SpiderFile.GetStreamAsync(ConfigurationManager.AppSettings["Domain"] + href), Encoding.UTF8);
                                            HtmlNodeCollection pdLnNodeCollection =
                                                doc.DocumentNode.SelectNodes("//td[starts-with(@id,'carlist_')]");
                                            if (pdLnNodeCollection != null && pdLnNodeCollection.Count > 0)
                                            {
                                                foreach (HtmlNode htmlNode in pdLnNodeCollection)
                                                {
                                                    if (htmlNode.FirstChild.Name == "a")
                                                    {
                                                        CarSeriesBusiness.Insert(new CarSeriesEntity
                                                        {
                                                            AddTime = DateTime.Now,
                                                            LinkUrl =
                                                                $"{ConfigurationManager.AppSettings["Domain"]}{htmlNode.FirstChild.GetAttributeValue("href", null)}",
                                                            ModelId    = carModel.Id,
                                                            SeriesName = htmlNode.FirstChild.InnerText,
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                #endregion

                                #endregion
                            }
                            CarSeriesBusiness.ShowInfoEventHandler -= CarSeriesBusiness_ShowInfoEventHandler;
                            CarModelBusiness.ShowInfoEventHandler  -= CarModelBusiness_ShowInfoEventHandler;
                        }

                        #endregion

                        //                    }
                    });

                    if (parallelResult.IsCompleted)
                    {
                        CarBrandBusiness.ShowInfoEventHandler -= CarBrandBusiness_ShowInfoEventHandler;
                    }
                }
                else
                {
                    View.ShowMessage("没有获取到品牌", "提示");
                }
            }).LogExceptions();
        }
Exemplo n.º 4
0
        public static string GenerateValidUsBankAccountNonce(BraintreeGateway gateway, string accountNumber = "1000000000")
        {
            var clientToken = GenerateDecodedClientToken(gateway);
            var def         = new {
                braintree_api = new {
                    url          = "",
                    access_token = ""
                }
            };
            var    config      = JsonConvert.DeserializeAnonymousType(clientToken, def);
            var    url         = config.braintree_api.url + "/tokens";
            var    accessToken = config.braintree_api.access_token;
            string postData    = @"
            {
                ""type"": ""us_bank_account"",
                ""billing_address"": {
                    ""street_address"": ""123 Ave"",
                    ""region"": ""CA"",
                    ""locality"": ""San Francisco"",
                    ""postal_code"": ""94112""
                },
                ""account_type"": ""checking"",
                ""routing_number"": ""021000021"",
                ""account_number"": """ + accountNumber + @""",
                ""ownership_type"": ""personal"",
                ""first_name"": ""Dan"",
                ""last_name"": ""Schulman"",
                ""ach_mandate"": {
                    ""text"": ""cl mandate text""
                }
            }";

#if netcore
            var    request = new HttpRequestMessage(new HttpMethod("POST"), url);
            byte[] buffer  = Encoding.UTF8.GetBytes(postData);
            request.Content = new StringContent(postData, Encoding.UTF8, "application/json");
            request.Headers.Add("Braintree-Version", "2016-10-07");
            request.Headers.Add("Authorization", "Bearer " + accessToken);

            var httpClientHandler = new HttpClientHandler {
            };

            HttpResponseMessage response;
            using (var client = new HttpClient(httpClientHandler))
            {
                response = client.SendAsync(request).GetAwaiter().GetResult();
            }
            StreamReader reader       = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8);
            string       responseBody = reader.ReadToEnd();
#else
            string  curlCommand = $@"-s -H ""Content-type: application/json"" -H ""Braintree-Version: 2016-10-07"" -H ""Authorization: Bearer {accessToken}"" -d '{postData}' -XPOST ""{url}""";
            Process process     = new Process {
                StartInfo = new ProcessStartInfo {
                    FileName               = "curl",
                    Arguments              = curlCommand,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                }
            };
            process.Start();

            StringBuilder responseBodyBuilder = new StringBuilder();
            while (!process.HasExited)
            {
                responseBodyBuilder.Append(process.StandardOutput.ReadToEnd());
            }
            responseBodyBuilder.Append(process.StandardOutput.ReadToEnd());
            string responseBody = responseBodyBuilder.ToString();
#endif
            var resDef = new {
                data = new {
                    id = "",
                }
            };
            var json = JsonConvert.DeserializeAnonymousType(responseBody, resDef);
            return(json.data.id);
        }
Exemplo n.º 5
0
        public static T DeserializeAnonymousType <T>(string json, T anonymousTypeObject)
        {
            T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);

            return(t);
        }
        public static async Task MessageRecieved(SocketMessage parameterMessage, bool edited = false)
        {
            Core.Messages++;
            // Don't do stuff if the user is blacklisted
            if (Core.CheckBlacklisted(parameterMessage.Author.Id))
            {
                return;
            }
            // Ignore self
            if (parameterMessage.Author.Id == Core.GetCurrentUserId())
            {
                return;
            }

            // Handle me saying "open an issue"
            try
            {
                if (parameterMessage.Content.ToLower().Contains("open an issue") && parameterMessage.Author.Id == Core.DiscordClient.GetApplicationInfoAsync().Result.Owner.Id)
                {
                    parameterMessage.Channel.SendMessageAsync("https://github.com/galenguyer/GenericBot/issues");
                }
            }
            catch { }
            // pluralkit logging integration
            try
            {
                if (parameterMessage.Author.IsWebhook)
                {
                    using (var client = new System.Net.WebClient())
                    {
                        var resp = client.DownloadString($"https://api.pluralkit.me/v1/msg/{parameterMessage.Id}");
                        var type = new
                        {
                            original = "string"
                        };
                        var obj = JsonConvert.DeserializeAnonymousType(resp, type);
                        Program.ClearedMessageIds.Add(ulong.Parse(obj.original));
                    }
                }
            }
            catch { }
            // viccy validation
            try
            {
                if (parameterMessage.Author.Id == 343830280131444746 && new Random().Next(50) == 1)
                {
                    await parameterMessage.ReplyAsync("<@!343830280131444746>, you're a good girl <3");
                }
            }
            catch { }
            // luko validation
            try
            {
                if (parameterMessage.Author.Id == 572532145743200256 && new Random().Next(50) == 1)
                {
                    await parameterMessage.ReplyAsync("<@!572532145743200256>, you're a good and valid enby <3");
                }
            }
            catch { }
            // points
            try
            {
                var dbUser = Core.GetUserFromGuild(parameterMessage.Author.Id, parameterMessage.GetGuild().Id);
                dbUser.IncrementPointsAndMessages();
                Core.SaveUserToGuild(dbUser, parameterMessage.GetGuild().Id);
            }
            catch (Exception e)
            {
                await Core.Logger.LogErrorMessage(e, null);
            }

            try
            {
                ParsedCommand command;

                if (parameterMessage.Channel is SocketDMChannel)
                {
                    command = new Command("t").ParseMessage(parameterMessage);

                    Core.Logger.LogGenericMessage($"Recieved DM: {parameterMessage.Content}");

                    if (command != null && command.RawCommand != null && command.RawCommand.WorksInDms)
                    {
                        command.Execute();
                    }
                    else
                    {
                        IUserMessage alertMessage = null;
                        if (Core.GlobalConfig.CriticalLoggingChannel != 0)
                        {
                            alertMessage = ((ITextChannel)Core.DiscordClient.GetChannel(Core.GlobalConfig.CriticalLoggingChannel))
                                           .SendMessageAsync($"```\nDM from: {parameterMessage.Author}({parameterMessage.Author.Id})\nContent: {parameterMessage.Content}\n```").Result;
                        }
                        if (parameterMessage.Content.Trim().Split().Length == 1)
                        {
                            var guild = VerificationEngine.GetGuildFromCode(parameterMessage.Content, parameterMessage.Author.Id);
                            if (guild == null)
                            {
                                parameterMessage.ReplyAsync("Invalid verification code");
                            }
                            else
                            {
                                guild.GetUser(parameterMessage.Author.Id)
                                .AddRoleAsync(guild.GetRole(Core.GetGuildConfig(guild.Id).VerifiedRole));
                                if (guild.TextChannels.HasElement(c => c.Id == (Core.GetGuildConfig(guild.Id).LoggingChannelId), out SocketTextChannel logChannel))
                                {
                                    logChannel.SendMessageAsync($"`{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")}`:  `{parameterMessage.Author}` (`{parameterMessage.Author.Id}`) just verified");
                                }
                                parameterMessage.ReplyAsync($"You've been verified on **{guild.Name}**!");
                                if (alertMessage != null)
                                {
                                    alertMessage.ModifyAsync(m =>
                                                             m.Content = $"```\nDM from: {parameterMessage.Author}({parameterMessage.Author.Id})\nContent: {parameterMessage.Content.SafeSubstring(1900)}\nVerified on {guild.Name}\n```");
                                }
                            }
                        }
                    }
                }
                else
                {
                    ulong guildId = parameterMessage.GetGuild().Id;
                    command = new Command("t").ParseMessage(parameterMessage);

                    if (Core.GetCustomCommands(guildId).HasElement(c => c.Name == command.Name,
                                                                   out CustomCommand customCommand))
                    {
                        Core.AddToCommandLog(command, guildId);
                        if (customCommand.Delete)
                        {
                            parameterMessage.DeleteAsync();
                        }
                        parameterMessage.ReplyAsync(customCommand.Response);
                    }

                    if (command != null && command.RawCommand != null)
                    {
                        Core.AddToCommandLog(command, guildId);
                        command.Execute();
                    }
                }
            }
            catch (Exception ex)
            {
                if (parameterMessage.Author.Id == Core.GetOwnerId())
                {
                    parameterMessage.ReplyAsync("```\n" + $"{ex.Message}\n{ex.StackTrace}".SafeSubstring(1000) + "\n```");
                }
                Core.Logger.LogErrorMessage(ex, new Command("t").ParseMessage(parameterMessage));
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Create configuration file for RoxyFileman
        /// </summary>
        public virtual void CreateConfiguration()
        {
            var filePath = GetFullPath(CONFIGURATION_FILE);

            //create file if not exists
            if (!System.IO.File.Exists(filePath))
            {
                //we use 'using' to close the file after it's created
                using (System.IO.File.Create(filePath)) { }
            }

            //try to read existing configuration
            var existingText          = System.IO.File.ReadAllText(filePath);
            var existingConfiguration = JsonConvert.DeserializeAnonymousType(existingText, new
            {
                FILES_ROOT           = string.Empty,
                SESSION_PATH_KEY     = string.Empty,
                THUMBS_VIEW_WIDTH    = string.Empty,
                THUMBS_VIEW_HEIGHT   = string.Empty,
                PREVIEW_THUMB_WIDTH  = string.Empty,
                PREVIEW_THUMB_HEIGHT = string.Empty,
                MAX_IMAGE_WIDTH      = string.Empty,
                MAX_IMAGE_HEIGHT     = string.Empty,
                DEFAULTVIEW          = string.Empty,
                FORBIDDEN_UPLOADS    = string.Empty,
                ALLOWED_UPLOADS      = string.Empty,
                FILEPERMISSIONS      = string.Empty,
                DIRPERMISSIONS       = string.Empty,
                LANG              = string.Empty,
                DATEFORMAT        = string.Empty,
                OPEN_LAST_DIR     = string.Empty,
                INTEGRATION       = string.Empty,
                RETURN_URL_PREFIX = string.Empty,
                DIRLIST           = string.Empty,
                CREATEDIR         = string.Empty,
                DELETEDIR         = string.Empty,
                MOVEDIR           = string.Empty,
                COPYDIR           = string.Empty,
                RENAMEDIR         = string.Empty,
                FILESLIST         = string.Empty,
                UPLOAD            = string.Empty,
                DOWNLOAD          = string.Empty,
                DOWNLOADDIR       = string.Empty,
                DELETEFILE        = string.Empty,
                MOVEFILE          = string.Empty,
                COPYFILE          = string.Empty,
                RENAMEFILE        = string.Empty,
                GENERATETHUMB     = string.Empty,
            });

            //check whether the path base has changed, otherwise there is no need to overwrite the configuration file
            var currentPathBase = this.HttpContext.Request.PathBase.ToString();

            if (existingConfiguration?.RETURN_URL_PREFIX?.Equals(currentPathBase) ?? false)
            {
                return;
            }

            //create configuration
            var configuration = new
            {
                FILES_ROOT           = existingConfiguration?.FILES_ROOT ?? "content/images/uploaded",
                SESSION_PATH_KEY     = existingConfiguration?.SESSION_PATH_KEY ?? string.Empty,
                THUMBS_VIEW_WIDTH    = existingConfiguration?.THUMBS_VIEW_WIDTH ?? "140",
                THUMBS_VIEW_HEIGHT   = existingConfiguration?.THUMBS_VIEW_HEIGHT ?? "120",
                PREVIEW_THUMB_WIDTH  = existingConfiguration?.PREVIEW_THUMB_WIDTH ?? "300",
                PREVIEW_THUMB_HEIGHT = existingConfiguration?.PREVIEW_THUMB_HEIGHT ?? "200",
                MAX_IMAGE_WIDTH      = existingConfiguration?.MAX_IMAGE_WIDTH ?? "1000",
                MAX_IMAGE_HEIGHT     = existingConfiguration?.MAX_IMAGE_HEIGHT ?? "1000",
                DEFAULTVIEW          = existingConfiguration?.DEFAULTVIEW ?? "list",
                FORBIDDEN_UPLOADS    = existingConfiguration?.FORBIDDEN_UPLOADS ?? @"zip js jsp jsb mhtml mht xhtml xht php phtml 
                    php3 php4 php5 phps shtml jhtml pl sh py cgi exe application gadget hta cpl msc jar vb jse ws wsf wsc wsh 
                    ps1 ps2 psc1 psc2 msh msh1 msh2 inf reg scf msp scr dll msi vbs bat com pif cmd vxd cpl htpasswd htaccess",
                ALLOWED_UPLOADS      = existingConfiguration?.ALLOWED_UPLOADS ?? string.Empty,
                FILEPERMISSIONS      = existingConfiguration?.FILEPERMISSIONS ?? "0644",
                DIRPERMISSIONS       = existingConfiguration?.DIRPERMISSIONS ?? "0755",
                LANG          = existingConfiguration?.LANG ?? _workContext.WorkingLanguage.UniqueSeoCode,
                DATEFORMAT    = existingConfiguration?.DATEFORMAT ?? "dd/MM/yyyy HH:mm",
                OPEN_LAST_DIR = existingConfiguration?.OPEN_LAST_DIR ?? "yes",

                //no need user to configure
                INTEGRATION       = "tinymce4",
                RETURN_URL_PREFIX = currentPathBase,
                DIRLIST           = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=DIRLIST",
                CREATEDIR         = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=CREATEDIR",
                DELETEDIR         = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=DELETEDIR",
                MOVEDIR           = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=MOVEDIR",
                COPYDIR           = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=COPYDIR",
                RENAMEDIR         = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=RENAMEDIR",
                FILESLIST         = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=FILESLIST",
                UPLOAD            = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=UPLOAD",
                DOWNLOAD          = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=DOWNLOAD",
                DOWNLOADDIR       = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=DOWNLOADDIR",
                DELETEFILE        = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=DELETEFILE",
                MOVEFILE          = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=MOVEFILE",
                COPYFILE          = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=COPYFILE",
                RENAMEFILE        = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=RENAMEFILE",
                GENERATETHUMB     = $"{this.HttpContext.Request.PathBase}/Admin/RoxyFileman/ProcessRequest?a=GENERATETHUMB",
            };

            //save the file
            var text = JsonConvert.SerializeObject(configuration, Formatting.Indented);

            System.IO.File.WriteAllText(filePath, text);
        }
Exemplo n.º 8
0
        public static T GetJsonObject <T>(this string content, T definition)
        {
            var json = JsonConvert.DeserializeAnonymousType(content, definition);

            return(json);
        }
Exemplo n.º 9
0
        public async Task <IActionResult> MakeAssertion([FromBody] AuthenticatorAssertionRawResponse clientResponse)
        {
            var o = new
            {
                challenge = string.Empty,
                origin    = string.Empty,
                type      = string.Empty
            };

            var username = string.Empty;

            try
            {
                o = JsonConvert.DeserializeAnonymousType((Encoding.UTF8.GetString(clientResponse.Response.ClientDataJson)), o);
                var jsonOptions = _memoryCache.Get <string>(o.challenge);

                var parsedObject = JObject.Parse(jsonOptions);

                username = parsedObject["User"]?["Name"]?.ToString();

                var options = Fido2NetLib.AssertionOptions.FromJson(jsonOptions);

                var credentials = _dataStore.GetCredentialById(clientResponse.Id);

                if (credentials == null)
                {
                    throw new Exception("Unknown credentials");
                }

                var storedCounter = credentials.SignatureCounter;

                async Task <bool> Callback(IsUserHandleOwnerOfCredentialIdParams args)
                {
                    var storedCredentials = await _dataStore.GetCredentialsByUserHandleAsync(args.UserHandle);

                    return(storedCredentials.Exists(c => c.Descriptor.Id.SequenceEqual(args.CredentialId)));
                }

                var res = await _lib.MakeAssertionAsync(clientResponse, options, credentials.PublicKey, storedCounter, Callback);

                _dataStore.UpdateCounter(res.CredentialId, res.Counter);

                var response = new AuthenticationResult
                {
                    ErrorMessage = res.ErrorMessage,
                    Status       = res.Status
                };

                var ev = new Event(username, "Successful assertion made", nameof(AuthenticationController), nameof(MakeAssertion));
                await _elasticClient.IndexAsync(ev, i => i.Index(GetIndexName(nameof(Ok))));

                return(Ok(response));
            }
            catch (Exception e)
            {
                var errorEvent = new ErrorEvent(e, username, nameof(AuthenticationController), nameof(MakeAssertion));
                await _elasticClient.IndexAsync(errorEvent, i => i.Index(GetIndexName(nameof(Exception))));

                return(Ok(new AuthenticationResult {
                    Status = "error", ErrorMessage = FormatException(e)
                }));
            }
        }
Exemplo n.º 10
0
        private static void StoveLogin(MyWebClient client)
        {
            client.DownloadData("https://member.onstove.com/auth/login");

            string id = UserSettings.GameId;
            string pw = UserSettings.GamePw;

            if (String.IsNullOrEmpty(id))
            {
                throw new Exception(StringLoader.GetText("exception_empty_id"));
            }

            var values = new NameValueCollection(3)
            {
                [Strings.Web.KR.PostId] = id
            };

            using (System.Security.SecureString secure = Methods.DecryptString(pw))
            {
                if (String.IsNullOrEmpty(values[Strings.Web.KR.PostPw] = Methods.ToInsecureString(secure)))
                {
                    throw new Exception(StringLoader.GetText("exception_empty_pw"));
                }
            }
            values[Strings.Web.KR.KeepForever] = Strings.Web.KR.KeepForeverDefaultValue;

            client.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
            byte[] byteResponse  = client.UploadValues(Urls.StoveLogin, values);
            string loginResponse = Encoding.UTF8.GetString(byteResponse);

            var loginJSON    = new { value = "", message = "", result = "" };
            var jsonResponse = JsonConvert.DeserializeAnonymousType(loginResponse, loginJSON);

            switch (jsonResponse.result ?? throw new Exception("unexpected null result"))
            {
            case "000":

                break;

            case "589":
                Process.Start("https://member.onstove.com/auth/login");
                throw new Exception(StringLoader.GetText("exception_captcha_required"));

            case "551":
            case "552":
            case "553":
            case "554":
                Process.Start($"https://member.onstove.com/block?user_id={id}");
                throw new Exception(StringLoader.GetText("exception_follow_instruction_webpage"));

            case "569":
                Process.Start($"https://member.onstove.com/register/ok?user_id={id}");
                throw new Exception(StringLoader.GetText("exception_follow_instruction_webpage"));

            case "556":
                throw new Exception(StringLoader.GetText("exception_incorrect_id_pw"));

            case "610":
                throw new Exception(StringLoader.GetText("exception_account_to_be_deleted"));

            case "550":
                var onlyIdValues = new NameValueCollection(1)
                {
                    [Strings.Web.KR.PostId] = id
                };
                client.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                byte[] byteWakeUpResponse = client.UploadValues("https://member.onstove.com/member/wake/up", onlyIdValues);
                string wakeUpResponse     = Encoding.UTF8.GetString(byteWakeUpResponse);
                var    jsonWakeUpResponse = JsonConvert.DeserializeAnonymousType(wakeUpResponse, loginJSON);
                switch (jsonWakeUpResponse.result ?? throw new Exception("unexpected null result"))
                {
                case "000":
                    StoveLogin(client);

                    break;

                default:
                    throw new Exception($"result=[{jsonResponse.result}]\n{jsonResponse.message ?? "no error details"}");
                }

                break;

            default:
                throw new Exception($"result=[{jsonResponse.result}]\n{jsonResponse.message ?? "no error details"}");
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Gets the ID of the rich menu linked to a user.
        /// https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-id-of-user
        /// </summary>
        /// <param name="userId">ID of the user</param>
        /// <returns>RichMenu Id</returns>
        public virtual async Task <string> GetRichMenuIdOfUserAsync(string userId)
        {
            var json = await GetStringAsync($"{_uri}/bot/user/{userId}/richmenu");

            return(JsonConvert.DeserializeAnonymousType(json, new { richMenuId = "" }).richMenuId);
        }
Exemplo n.º 12
0
        public void fillList()
        {
            listView1.Items.Clear();
            List <changes> lst = c_DBHandler.getDeletedCustomers(sqlc);

            foreach (changes c in lst)
            {
                var definition = new
                {
                    id                           = 00,
                    nev                          = "",
                    születesi_nev                = "",
                    szig_szam                    = "",
                    lakcim_varos                 = "",
                    lakcim_uh                    = "",
                    lakcim_zip                   = "",
                    szul_datum                   = "",
                    szul_hely                    = "",
                    csaladi_allapot              = 00,
                    anyja_neve                   = "",
                    vegzettseg                   = "",
                    foglalkozas                  = "",
                    szakkepzettseg               = "",
                    munkaltato                   = "",
                    azonosito                    = "",
                    utolso_tamogatas_idopontja   = "",
                    jovedelem_igazolas           = "",
                    elhunyt                      = "",
                    allapot                      = "",
                    vallas                       = 00,
                    környezettanulmanyt_végezte  = "",
                    környezettanulmany_idopontja = "",
                    hozzaadas_datuma             = "",
                    felvevo_profil               = "",
                    legutobb_modositotta         = "",
                    legutobbi_modositas_datuma   = ""
                };

                var conv = JsonConvert.DeserializeAnonymousType(c.before, definition);

                ListViewItem lvi = new ListViewItem()
                {
                    Tag       = conv,
                    Text      = conv.azonosito,
                    BackColor = listView1.Items.Count % 2 == 0 ? Color.LightGray : Color.LightYellow
                };

                lvi.SubItems.AddRange(new ListViewItem.ListViewSubItem[] {
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = conv.nev
                    },                                                                                                                                                                                          //ch_CustomerName
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = conv.lakcim_varos + " " + conv.lakcim_zip + " " + conv.lakcim_uh
                    },                                                                                                                                  //ch_Address
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = conv.szul_datum
                    },                                                                                                                                                                                  //ch_Birth
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = conv.anyja_neve
                    },                                                                                                                                                                                  //ch_MothersName
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = conv.utolso_tamogatas_idopontja
                    },                                                                                                                                                                  //ch_LastAid
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = conv.elhunyt == "T" ? "PIPA" : "IKSZ"
                    },                                                                                                                                                                  //ch_PassedAway
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = c.whochanged
                    },                                                                                                                                                                                          //ch_WhoDeleted
                    new ListViewItem.ListViewSubItem()
                    {
                        Text = c.whenchanged
                    },                                                                                                                                                                                          //ch_WhenDeleted
                });

                listView1.Items.Add(lvi);
            }
        }
Exemplo n.º 13
0
        private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            Pusher.Trace.TraceEvent(TraceEventType.Information, 0, "Websocket message received: " + e.Message);

            Debug.WriteLine(e.Message);

            // DeserializeAnonymousType will throw and error when an error comes back from pusher
            // It stems from the fact that the data object is a string normally except when an error is sent back
            // then it's an object.

            // bad:  "{\"event\":\"pusher:error\",\"data\":{\"code\":4201,\"message\":\"Pong reply not received\"}}"
            // good: "{\"event\":\"pusher:error\",\"data\":\"{\\\"code\\\":4201,\\\"message\\\":\\\"Pong reply not received\\\"}\"}";

            var jObject = JObject.Parse(e.Message);

            if (jObject["data"] != null && jObject["data"].Type != JTokenType.String)
            {
                jObject["data"] = jObject["data"].ToString(Formatting.None);
            }

            string jsonMessage = jObject.ToString(Formatting.None);
            var    template    = new { @event = String.Empty, data = String.Empty, channel = String.Empty };

            //var message = JsonConvert.DeserializeAnonymousType(e.Message, template);
            var message = JsonConvert.DeserializeAnonymousType(jsonMessage, template);

            _pusher.EmitEvent(message.@event, message.data);

            if ([email protected]("pusher"))
            {
                // Assume Pusher event
                switch (message.@event)
                {
                case Constants.ERROR:
                    ParseError(message.data);
                    break;

                case Constants.CONNECTION_ESTABLISHED:
                    ParseConnectionEstablished(message.data);
                    break;

                case Constants.CHANNEL_SUBSCRIPTION_SUCCEEDED:

                    if (_pusher.Channels.ContainsKey(message.channel))
                    {
                        var channel = _pusher.Channels[message.channel];
                        channel.SubscriptionSucceeded(message.data);
                    }

                    break;

                case Constants.CHANNEL_SUBSCRIPTION_ERROR:

                    RaiseError(new PusherException("Error received on channel subscriptions: " + e.Message, ErrorCodes.SubscriptionError));
                    break;

                case Constants.CHANNEL_MEMBER_ADDED:

                    // Assume channel event
                    if (_pusher.Channels.ContainsKey(message.channel))
                    {
                        var channel = _pusher.Channels[message.channel];

                        if (channel is PresenceChannel)
                        {
                            ((PresenceChannel)channel).AddMember(message.data);
                            break;
                        }
                    }

                    Pusher.Trace.TraceEvent(TraceEventType.Warning, 0, "Received a presence event on channel '" + message.channel + "', however there is no presence channel which matches.");
                    break;

                case Constants.CHANNEL_MEMBER_REMOVED:

                    // Assume channel event
                    if (_pusher.Channels.ContainsKey(message.channel))
                    {
                        var channel = _pusher.Channels[message.channel];

                        if (channel is PresenceChannel)
                        {
                            ((PresenceChannel)channel).RemoveMember(message.data);
                            break;
                        }
                    }

                    Pusher.Trace.TraceEvent(TraceEventType.Warning, 0, "Received a presence event on channel '" + message.channel + "', however there is no presence channel which matches.");
                    break;
                }
            }
            else
            {
                // Assume channel event
                if (_pusher.Channels.ContainsKey(message.channel))
                {
                    _pusher.Channels[message.channel].EmitEvent(message.@event, message.data);
                }
            }
        }
Exemplo n.º 14
0
        private async void _openId_SteamOpenIdCallback(object sender, SteamOpenIdCallbackEventArgs e)
        {
            if (e.Successful)
            {
                var player = new
                {
                    RealName    = (string)null,
                    PersonaName = (string)null
                };
                try
                {
                    using (var wc = new WebClient())
                    {
                        var data = await wc.DownloadStringTaskAsync($@"http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={_config.SteamApiKey}&steamids={e.SteamId}");

                        var response = JsonConvert.DeserializeAnonymousType(data, new { response = new { players = new[] { player } } });
                        player = response?.response?.players?.FirstOrDefault();
                    }
                }
                catch { /* ignore exceptions */ }

                //QueryMaster.Steam.GetPlayerSummariesResponsePlayer player = null;
                //await Task.Factory.StartNew(() =>
                //{
                //    try
                //    {
                //        //this results in an exception (but it is easy enough to query by ourselves)
                //        var query = new QueryMaster.Steam.SteamQuery(_config.SteamApiKey);
                //        var result = query?.ISteamUser.GetPlayerSummaries(new[] { e.SteamId });
                //        if (result == null || !result.IsSuccess) return;

                //        player = result.ParsedResponse.Players.FirstOrDefault();
                //    }
                //    catch { /* ignore exceptions */}
                //});

                //set ark role on users when they link
                //foreach(var server in _discord.Servers)
                //{
                //    var user = server.GetUser(e.DiscordUserId);
                //    var role = server.FindRoles(_config.MemberRoleName, true).FirstOrDefault();
                //    if (user == null || role == null) continue;

                //    //try
                //    //{
                //    //    if (!user.HasRole(role)) await user.AddRoles(role);

                //    //    var p = _context.Players?.FirstOrDefault(x => { ulong steamId = 0; return ulong.TryParse(x.SteamId, out steamId) ? steamId == e.SteamId : false; });
                //    //    if (p != null && !string.IsNullOrWhiteSpace(p.Name))
                //    //    {

                //    //        //must be less or equal to 32 characters
                //    //        await user.Edit(nickname: p.Name.Length > 32 ? p.Name.Substring(0, 32) : p.Name);

                //    //    }
                //    //}
                //    //catch (HttpException)
                //    //{
                //    //    //could be due to the order of roles on the server. bot role with "manage roles"/"change nickname" permission must be higher up than the role it is trying to set
                //    //}
                //}

                using (var context = _databaseContextFactory.Create())
                {
                    var user = context.Users.FirstOrDefault(x => x.DiscordId == (long)e.DiscordUserId);
                    if (user != null)
                    {
                        user.RealName         = player?.RealName;
                        user.SteamDisplayName = player?.PersonaName;
                        user.SteamId          = (long)e.SteamId;
                        user.Unlinked         = false;
                    }
                    else
                    {
                        user = new Database.Model.User {
                            DiscordId = (long)e.DiscordUserId, SteamId = (long)e.SteamId, RealName = player?.RealName, SteamDisplayName = player?.PersonaName
                        };
                        context.Users.Add(user);
                    }

                    foreach (var associatePlayed in context.Played.Where(x => x.SteamId == (long)e.SteamId))
                    {
                        associatePlayed.SteamId = null;
                        user.Played.Add(associatePlayed);
                    }

                    context.SaveChanges();
                }

                var ch = await _discord.GetUser(e.DiscordUserId).GetOrCreateDMChannelAsync();

                if (ch != null)
                {
                    await ch.SendMessageAsync($"Your Discord user is now linked with your Steam account! :)");
                }
            }
            else
            {
                var ch = await _discord.GetUser(e.DiscordUserId).GetOrCreateDMChannelAsync();

                if (ch != null)
                {
                    await ch.SendMessageAsync($"Something went wrong during the linking process. Please try again later!");
                }
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Deserializes the JSON to the given anonymous type
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="value"></param>
 /// <param name="anonymousType"></param>
 /// <returns></returns>
 public static T DeserializeAnonymousType <T>(string value, T anonymousType)
 {
     return(JsonConvert.DeserializeAnonymousType <T>(value, anonymousType));
 }
Exemplo n.º 16
0
        private async Task FollowChange()
        {
            if (isfollowing)
            {
                HttpRequestMessage message = new HttpRequestMessage()
                {
                    RequestUri = new Uri(Config.VidmeUrlClass.UserUnfollowURL(user.user_id)),
                    Method     = HttpMethod.Post
                };

                await http_client_semaphore.WaitAsync();

                HttpResponseMessage response = await httpClient.SendAsync(message);

                http_client_semaphore.Release();

                string response_string = await response.Content.ReadAsStringAsync();

                var status = new { status = true };

                var data = JsonConvert.DeserializeAnonymousType(response_string, status);


                if (data.status)
                {
                    isfollowing = false;
                    await Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        FollowButton.Content = "Follow";
                    });
                }
            }
            else
            {
                HttpRequestMessage message = new HttpRequestMessage()
                {
                    RequestUri = new Uri(Config.VidmeUrlClass.UserFollowURL(user.user_id)),
                    Method     = HttpMethod.Post
                };

                await http_client_semaphore.WaitAsync();

                HttpResponseMessage response = await httpClient.SendAsync(message);

                http_client_semaphore.Release();

                string response_string = await response.Content.ReadAsStringAsync();

                var status = new { status = true };

                var data = JsonConvert.DeserializeAnonymousType(response_string, status);


                if (data.status)
                {
                    isfollowing = true;

                    await Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        FollowButton.Content = "UnFollow";
                    });
                }
            }
        }
Exemplo n.º 17
0
 public static T ToAnonType <T>(this string json_string, T t_object)
 {
     return(JsonConvert.DeserializeAnonymousType(json_string, t_object));
 }
Exemplo n.º 18
0
 public static T ParseFromJson <T>(this T shape, string json)
 {
     return(JsonConvert.DeserializeAnonymousType(json, shape));
 }
Exemplo n.º 19
0
 public T Deserialize <T>(string value, T anonymousTypeObject)
 {
     return(JsonConvert.DeserializeAnonymousType <T>(JObject.Parse(value).ToString(), anonymousTypeObject));
 }
Exemplo n.º 20
0
        /// <summary>
        /// метод конвертирует JSON в классы C# и отправляет на верх
        /// </summary>
        private void Converter()
        {
            while (true)
            {
                try
                {
                    if (_neadToStopAllThreads == true)
                    {
                        return;
                    }
                    if (!_newMessage.IsEmpty)
                    {
                        string mes;

                        if (_newMessage.TryDequeue(out mes))
                        {
                            if (mes.Contains("error"))
                            {
                                if (ErrorEvent != null)
                                {
                                    ErrorEvent(mes);
                                }
                            }

                            if (mes.Contains("\"table\"" + ":" + "\"margin\""))
                            {
                                var portf = JsonConvert.DeserializeAnonymousType(mes, new BitMexPortfolio());

                                if (UpdatePortfolio != null)
                                {
                                    UpdatePortfolio(portf);
                                }
                                continue;
                            }

                            if (mes.Contains("\"table\"" + ":" + "\"position\""))
                            {
                                var pos = JsonConvert.DeserializeAnonymousType(mes, new BitMexPosition());

                                if (UpdatePosition != null)
                                {
                                    UpdatePosition(pos);
                                }
                                continue;
                            }

                            if (mes.Contains("\"table\"" + ":" + "\"orderBookL2\""))
                            {
                                var quotes = JsonConvert.DeserializeAnonymousType(mes, new BitMexQuotes());

                                if (UpdateMarketDepth != null && quotes.data.Count != 0 && quotes.data != null)
                                {
                                    UpdateMarketDepth(quotes);
                                }
                                continue;
                            }

                            if (mes.Contains("\"table\"" + ":" + "\"trade\""))
                            {
                                var trade = JsonConvert.DeserializeAnonymousType(mes, new BitMexTrades());

                                if (NewTradesEvent != null)
                                {
                                    NewTradesEvent(trade);
                                }
                                continue;
                            }

                            if (mes.Contains("\"table\"" + ":" + "\"execution\""))
                            {
                                var myOrder = JsonConvert.DeserializeAnonymousType(mes, new BitMexMyOrders());

                                if (MyTradeEvent != null && myOrder.data.Count != 0 && myOrder.data[0].execType == "Trade")
                                {
                                    MyTradeEvent(myOrder);
                                }
                                continue;
                            }

                            if (mes.Contains("\"table\"" + ":" + "\"order\""))
                            {
                                var order = JsonConvert.DeserializeAnonymousType(mes, new BitMexOrder());

                                if (MyOrderEvent != null && order.data.Count != 0)
                                {
                                    MyOrderEvent(order);
                                }
                                continue;
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(2);
                    }
                }
                catch (Exception exception)
                {
                    if (BitMexLogMessageEvent != null)
                    {
                        BitMexLogMessageEvent(exception.ToString(), LogMessageType.Error);
                    }
                }
            }
        }
Exemplo n.º 21
0
        public static string GenerateValidIdealPaymentId(BraintreeGateway gateway, decimal amount)
        {
            var clientTokenJson = GenerateDecodedClientToken(
                gateway,
                new ClientTokenRequest {
                MerchantAccountId = "ideal_merchant_account"
            }
                );
            var clientTokenDef = new
            {
                authorizationFingerprint = "",
                braintree_api            = new
                {
                    url          = "",
                    access_token = ""
                }
            };
            var clientToken   = JsonConvert.DeserializeAnonymousType(clientTokenJson, clientTokenDef);
            var configuration = GetClientConfiguration(gateway, clientToken.authorizationFingerprint);

            var url         = clientToken.braintree_api.url + "/ideal-payments";
            var accessToken = clientToken.braintree_api.access_token;
            var routeId     = configuration.Ideal.RouteId;

            StringBuilder postDataBuilder = new StringBuilder();

            postDataBuilder.Append(@"{
                ""issuer"": ""ROBONL2u"",
                ""order_id"": ""ABC123"",
                ""currency"": ""EUR"",
                ""redirect_url"": ""https:\/\/braintree-api.com"",
                ""amount"": """);
            postDataBuilder.Append(amount.ToString());
            postDataBuilder.Append(@""",");
            postDataBuilder.Append(@"""route_id"": """);
            postDataBuilder.Append(routeId);
            postDataBuilder.Append(@"""}");
            string postData = postDataBuilder.ToString();

#if netcore
            var    request = new HttpRequestMessage(new HttpMethod("POST"), url);
            byte[] buffer  = Encoding.UTF8.GetBytes(postData);
            request.Content = new StringContent(postData, Encoding.UTF8, "application/json");
            request.Headers.Add("Braintree-Version", "2015-11-01");
            request.Headers.Add("Authorization", "Bearer " + accessToken);

            var httpClientHandler = new HttpClientHandler {
            };

            HttpResponseMessage response;
            using (var client = new HttpClient(httpClientHandler))
            {
                response = client.SendAsync(request).GetAwaiter().GetResult();
            }
            StreamReader reader       = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8);
            string       responseBody = reader.ReadToEnd();
#else
            string  curlCommand = $@"-s -H ""Content-type: application/json"" -H ""Braintree-Version: 2015-11-01"" -H ""Authorization: Bearer {accessToken}"" -d '{postData}' -XPOST ""{url}""";
            Process process     = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = "curl",
                    Arguments              = curlCommand,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                }
            };
            process.Start();

            StringBuilder responseBodyBuilder = new StringBuilder();
            while (!process.HasExited)
            {
                responseBodyBuilder.Append(process.StandardOutput.ReadToEnd());
            }
            responseBodyBuilder.Append(process.StandardOutput.ReadToEnd());
            string responseBody = responseBodyBuilder.ToString();
#endif
            var resDef = new
            {
                data = new
                {
                    id = "",
                }
            };
            var json = JsonConvert.DeserializeAnonymousType(responseBody, resDef);
            return(json.data.id);
        }
Exemplo n.º 22
0
 public T DeserializeAnonymousType <T>(string json, T definition)
 {
     return(JsonConvert.DeserializeAnonymousType(json, definition));
 }
Exemplo n.º 23
0
        /// <summary>
        /// берет сообщения из общей очереди, конвертирует их в классы C# и отправляет на верх
        /// </summary>
        public void ConverterUserData()
        {
            while (true)
            {
                try
                {
                    if (_isDisposed)
                    {
                        return;
                    }

                    if (!_newUserDataMessage.IsEmpty)
                    {
                        string mes;

                        if (_newUserDataMessage.TryDequeue(out mes))
                        {
                            if (mes.Contains("code"))
                            {
                                SendLogMessage(JsonConvert.DeserializeAnonymousType(mes, new ErrorMessage()).msg, LogMessageType.Error);
                            }

                            else if (mes.Contains("\"e\"" + ":" + "\"executionReport\""))
                            {
                                var order = JsonConvert.DeserializeAnonymousType(mes, new ExecutionReport());

                                string orderNumUser = order.C;

                                if (string.IsNullOrEmpty(orderNumUser) ||
                                    orderNumUser == "null")
                                {
                                    orderNumUser = order.c;
                                }

                                try
                                {
                                    Convert.ToInt32(orderNumUser);
                                }
                                catch (Exception)
                                {
                                    continue;
                                }

                                if (order.x == "NEW")
                                {
                                    Order newOrder = new Order();
                                    newOrder.SecurityNameCode = order.s;
                                    newOrder.TimeCallBack     = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(order.E));
                                    newOrder.NumberUser       = Convert.ToInt32(orderNumUser);

                                    newOrder.NumberMarket = order.i.ToString();
                                    //newOrder.PortfolioNumber = order.PortfolioNumber; добавить в сервере
                                    newOrder.Side            = order.S == "BUY" ? Side.Buy : Side.Sell;
                                    newOrder.State           = OrderStateType.Activ;
                                    newOrder.Volume          = Convert.ToDecimal(order.q.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.Price           = Convert.ToDecimal(order.p.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.ServerType      = ServerType.Binance;
                                    newOrder.PortfolioNumber = newOrder.SecurityNameCode;

                                    if (MyOrderEvent != null)
                                    {
                                        MyOrderEvent(newOrder);
                                    }
                                }
                                else if (order.x == "CANCELED")
                                {
                                    Order newOrder = new Order();
                                    newOrder.SecurityNameCode = order.s;
                                    newOrder.TimeCallBack     = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(order.E));
                                    newOrder.NumberUser       = Convert.ToInt32(orderNumUser);
                                    newOrder.NumberMarket     = order.i.ToString();
                                    newOrder.Side             = order.S == "BUY" ? Side.Buy : Side.Sell;
                                    newOrder.State            = OrderStateType.Cancel;
                                    newOrder.Volume           = Convert.ToDecimal(order.q.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.Price            = Convert.ToDecimal(order.p.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.ServerType       = ServerType.Binance;
                                    newOrder.PortfolioNumber  = newOrder.SecurityNameCode;

                                    if (MyOrderEvent != null)
                                    {
                                        MyOrderEvent(newOrder);
                                    }
                                }
                                else if (order.x == "REJECTED")
                                {
                                    Order newOrder = new Order();
                                    newOrder.SecurityNameCode = order.s;
                                    newOrder.TimeCallBack     = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(order.E));
                                    newOrder.NumberUser       = Convert.ToInt32(orderNumUser);
                                    newOrder.NumberMarket     = order.i.ToString();
                                    newOrder.Side             = order.S == "BUY" ? Side.Buy : Side.Sell;
                                    newOrder.State            = OrderStateType.Fail;
                                    newOrder.Volume           = Convert.ToDecimal(order.q.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.Price            = Convert.ToDecimal(order.p.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.ServerType       = ServerType.Binance;
                                    newOrder.PortfolioNumber  = newOrder.SecurityNameCode;

                                    if (MyOrderEvent != null)
                                    {
                                        MyOrderEvent(newOrder);
                                    }
                                }
                                else if (order.x == "TRADE")
                                {
                                    MyTrade trade = new MyTrade();
                                    trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(order.T));
                                    trade.NumberOrderParent = order.i.ToString();
                                    trade.NumberTrade       = order.t.ToString();
                                    trade.Volume            = Convert.ToDecimal(order.l.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    trade.Price             = Convert.ToDecimal(order.L.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    trade.SecurityNameCode  = order.s;

                                    if (MyTradeEvent != null)
                                    {
                                        MyTradeEvent(trade);
                                    }
                                }
                                else if (order.x == "EXPIRED")
                                {
                                    Order newOrder = new Order();
                                    newOrder.SecurityNameCode = order.s;
                                    newOrder.TimeCallBack     = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(order.E));
                                    newOrder.NumberUser       = Convert.ToInt32(orderNumUser);
                                    newOrder.NumberMarket     = order.i.ToString();
                                    newOrder.Side             = order.S == "BUY" ? Side.Buy : Side.Sell;
                                    newOrder.State            = OrderStateType.Cancel;
                                    newOrder.Volume           = Convert.ToDecimal(order.q.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.Price            = Convert.ToDecimal(order.p.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                                    newOrder.ServerType       = ServerType.Binance;
                                    newOrder.PortfolioNumber  = newOrder.SecurityNameCode;

                                    if (MyOrderEvent != null)
                                    {
                                        MyOrderEvent(newOrder);
                                    }
                                }

                                continue;
                            }

                            else if (mes.Contains("\"e\"" + ":" + "\"outboundAccountInfo\""))
                            {
                                var portfolios = JsonConvert.DeserializeAnonymousType(mes, new OutboundAccountInfo());

                                if (UpdatePortfolio != null)
                                {
                                    UpdatePortfolio(portfolios);
                                }
                                continue;
                            }
                        }
                    }
                }

                catch (Exception exception)
                {
                    SendLogMessage(exception.ToString(), LogMessageType.Error);
                }
                Thread.Sleep(1);
            }
        }
Exemplo n.º 24
0
        public List <TicketTable> SearchDocument(string accountNumber = null, int?ticketNumber = null, DateTime?deliveryDate = null)
        {
            #region Request Parameters

            Credentials credentials = new Credentials()
            {
                AppUsername    = PODEnvironment.GetSetting("AppUsername"),
                ClientUsername = PODEnvironment.GetSetting("ClientUsername"),
                AppPassword    = PODEnvironment.GetSetting("AppPassword")
            };

            string     companyID    = PODEnvironment.GetSetting("companyID");
            string     documentType = PODEnvironment.GetSetting("documentType");
            DataFormat dataFormat   = DataFormat.JSON;

            //fill the required columns to be returned from the service
            List <ResultField> resultDatas = new List <ResultField>();
            List <TicketDocumentResultNames> FieldNamesList = Enum.GetValues(typeof(TicketDocumentResultNames)).Cast <TicketDocumentResultNames>().ToList();
            List <TicketDocumentResultKeys>  FieldKeysList  = Enum.GetValues(typeof(TicketDocumentResultKeys)).Cast <TicketDocumentResultKeys>().ToList();
            var zippedFields = FieldNamesList.Zip(FieldKeysList, (n, w) => new { Value = n, Key = w });
            foreach (var zippedField in zippedFields)
            {
                resultDatas.Add(new ResultField()
                {
                    FieldName = zippedField.Key.ToString(), FieldAlias = zippedField.Value.ToString()
                });
            }

            //fill the search criteria fields
            List <DataField> searchDatas = new List <DataField>();
            if (!String.IsNullOrWhiteSpace(accountNumber))
            {
                DataField searchData = new DataField()
                {
                    FieldName = TicketDocumentSearchKeys.fldCust_Acc.ToString(), FieldValue = accountNumber                                     /* "143016" */
                };
                searchDatas.Add(searchData);
            }
            if (ticketNumber.HasValue)
            {
                DataField searchData = new DataField()
                {
                    FieldName = TicketDocumentSearchKeys.fldSAP_Ticket_No.ToString(), FieldValue = ticketNumber.Value.ToString()                                      /* "143016" */
                };
                searchDatas.Add(searchData);
            }
            if (deliveryDate.HasValue)
            {
                DataField searchData = new DataField()
                {
                    FieldName = TicketDocumentSearchKeys.fldDate.ToString(), FieldValue = deliveryDate.Value.ToString("dd/MM/yyyy HH:mm:ss")                                      /* "143016" */
                };
                searchDatas.Add(searchData);
            }
            //DataField searchData2 = new DataField() { FieldName = "fldCust_Acc", FieldValue = null };
            //searchDatas.Add(searchData2);


            #region Zibil
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldSerial_No.ToString(), FieldAlias = TicketDocumentFieldNames.SerialNo.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldPOD_Ticket_No.ToString(), FieldAlias = TicketDocumentFieldNames.BarCode.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldSAP_Ticket_No.ToString(), FieldAlias = TicketDocumentFieldNames.TicketNo.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldDepot.ToString(), FieldAlias = TicketDocumentFieldNames.Depot.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldDate.ToString(), FieldAlias = TicketDocumentFieldNames.TicketDateDT.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldCust_Acc.ToString(), FieldAlias = TicketDocumentFieldNames.CustomerAcc.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldCust_Name.ToString(), FieldAlias = TicketDocumentFieldNames.CustomerName.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldHaulier_Acc.ToString(), FieldAlias = TicketDocumentFieldNames.HaulierAcc.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldVehicle_Reg.ToString(), FieldAlias = TicketDocumentFieldNames.VehicleReg.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldSAP_Quote.ToString(), FieldAlias = TicketDocumentFieldNames.SAPQuote.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldSAP_Invoice.ToString(), FieldAlias = TicketDocumentFieldNames.SAPInvoice.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldPayer.ToString(), FieldAlias = TicketDocumentFieldNames.Payer.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldDate_Imported.ToString(), FieldAlias = TicketDocumentFieldNames.DateImported.ToString() });
            //resultDatas.Add(new ResultField() { FieldName = TicketDocumentFieldKeys.fldEDM_ID.ToString(), FieldAlias = TicketDocumentFieldNames.EDMDocumentID.ToString() });
            #endregion

            #endregion


            EDMOnlineServiceReference.DocumentManagementClient client = new DocumentManagementClient();
            Document doc = new EDMOnlineServiceReference.Document();

            try
            {
                List <TicketTable> ticketDocuments = new List <TicketTable>();
                var response     = client.DocumentSearch(credentials, companyID, documentType, searchDatas, resultDatas, dataFormat);
                var responseData = JObject.Parse(response.Data).ToString();
                ticketDocuments = JsonConvert.DeserializeAnonymousType(responseData, new { Tables = (List <TicketTable>)null }).Tables;

                return(ticketDocuments);
            }
            catch (Exception ex)
            {
                _loggingManager.Log.Error(ex, ex.Source);
                throw;
            }
        }
Exemplo n.º 25
0
        /// <summary>
        ///     Returns a new instance of Authenticator class based on the description provided by the passed serialized string in
        ///     Json format
        /// </summary>
        /// <param name="serialized">The serialized representation of an Authenticator instance as string in Json format.</param>
        /// <returns>An instance of Authenticator class</returns>
        public static Authenticator DeSerialize(string serialized)
        {
            var authenticator = JsonConvert.DeserializeObject <Authenticator>(serialized);

            // Tries to fill authenticator data by searching for properties in the root of Json object
            if (authenticator.AuthenticatorData == null || !authenticator.AuthenticatorData.HasEnoughInfo())
            {
                var authenticatorData = JsonConvert.DeserializeObject <AddAuthenticatorResponse>(serialized);
                authenticator = new Authenticator(
                    authenticatorData,
                    authenticator.Session,
                    authenticator.DeviceId
                    );
            }

            // Tries to fill session data by searching for properties in the root of Json object
            if (authenticator.Session == null || !authenticator.Session.HasEnoughInfo())
            {
                var sessionData = JsonConvert.DeserializeObject <MobileSession>(serialized);
                authenticator = new Authenticator(
                    authenticator.AuthenticatorData,
                    sessionData,
                    authenticator.DeviceId
                    );
            }

            // Tries to extract steam guard machine authentication tokens
            if (authenticator.Session != null && !(authenticator.Session.SteamMachineAuthenticationTokens?.Count > 0))
            {
                var steamIdProperties = JsonConvert.DeserializeAnonymousType(
                    serialized,
                    new
                {
                    steamid  = (ulong?)null,
                    steam_id = (ulong?)null,
                    session  = new
                    {
                        steamid  = (ulong?)null,
                        steam_id = (ulong?)null
                    }
                }
                    );
                var steamId = steamIdProperties.steam_id ??
                              steamIdProperties.steamid ??
                              steamIdProperties.session.steam_id ??
                              steamIdProperties.session.steamid ?? authenticator.Session.SteamId;

                var webCookieProperties = JsonConvert.DeserializeAnonymousType(
                    serialized,
                    new
                {
                    webcookie  = (string)null,
                    web_cookie = (string)null,
                    session    = new
                    {
                        webcookie  = (string)null,
                        web_cookie = (string)null
                    }
                }
                    );
                var webCookie = webCookieProperties.web_cookie ??
                                webCookieProperties.webcookie ??
                                webCookieProperties.session.web_cookie ?? webCookieProperties.session.webcookie;

                if (steamId != null && !string.IsNullOrWhiteSpace(webCookie))
                {
                    var newSession = new MobileSession(
                        authenticator.Session.OAuthToken,
                        steamId,
                        authenticator.Session.SteamLogin,
                        authenticator.Session.SteamLoginSecure,
                        authenticator.Session.SessionId,
                        authenticator.Session.RememberLoginToken,
                        new Dictionary <ulong, string>
                    {
                        { steamId.Value, webCookie }
                    }
                        );

                    authenticator = new Authenticator(
                        authenticator.AuthenticatorData,
                        newSession,
                        authenticator.DeviceId
                        );
                }
            }

            // Tries to fill device identification string by searching for properties in the root of Json object
            if (string.IsNullOrWhiteSpace(authenticator.DeviceId))
            {
                var deviceIdProperties = JsonConvert.DeserializeAnonymousType(
                    serialized,
                    new
                {
                    deviceId  = (string)null,
                    device_id = (string)null,
                    device    = (string)null
                }
                    );
                authenticator = new Authenticator(
                    authenticator.AuthenticatorData,
                    authenticator.Session,
                    deviceIdProperties.device_id ?? deviceIdProperties.deviceId ?? deviceIdProperties.device
                    );
            }

            // Do we have a enough information to call this a valid instance?
            return(authenticator.HasEnoughInfo() ? authenticator : null);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Executes the WorkFlow.
        /// </summary>
        /// <param name="crmWorkflowContext">The <see cref="LocalWorkflowContext"/> which contains the
        /// <param name="executionContext" > <see cref="CodeActivityContext"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances.
        /// The WorkFlow's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the WorkFlow. Also, multiple system threads
        /// could execute the WorkFlow at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in WorkFlows.
        /// </remarks>
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            if (crmWorkflowContext == null)
            {
                throw new ArgumentNullException("crmWorkflowContext");
            }

            //try
            //{
            var tracingService = executionContext.GetExtension <ITracingService>();
            var serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            var service        = crmWorkflowContext.OrganizationService;
            var adminService   = serviceFactory.CreateOrganizationService(null);

            var postcode = this.Postcode.Get(executionContext);

            tracingService.Trace(string.Format("In GetAddressesForPostcode with PostCode = {0}", postcode));

            // Read the settings
            var url = string.Empty;

            try
            {
                var configSettings = adminService.GetConfigurationStringValues("OSPlaces.AddressbaseFacadeUrl");

                url = configSettings["OSPlaces.AddressbaseFacadeUrl"];
                // url will be something like http://addressfacade.cloudapp.net/address-service/v1/addresses/postcode?key=client1&postcode={0}
                // so we need to substitute the postcode
                url = string.Format(configSettings["OSPlaces.AddressbaseFacadeUrl"], postcode);
            }
            catch (Exception exc)
            {
                throw new InvalidPluginExecutionException("The Address base facade url needs to be configured.");
            }

            var addresses = string.Empty;

            tracingService.Trace(url);

            using (var httpclient = new HttpClient())
            {
                // Synchronous call to address base facade
                var response = httpclient.GetAsync(url).Result;
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                if (!response.IsSuccessStatusCode)
                {
                    if (response.StatusCode != HttpStatusCode.BadRequest)
                    {
                        // Throw exception if its not 400
                        response.EnsureSuccessStatusCode();
                    }
                    else
                    {
                        // Handle error in body that was returned by address base facade
                        // and throw a new one with the error message in it so can be used
                        // in web resource.

                        var httpErrorObject = response.Content.ReadAsStringAsync().Result;
                        tracingService.Trace(string.Format("Facacde Error: {0}", httpErrorObject));

                        // Template for anonymous deserialisation
                        var anonymousErrorObject = new
                        {
                            facade_status_code   = 400,
                            facade_error_message = string.Empty,
                            facade_error_code    = string.Empty,
                            supplier_was_called  = true,
                            supplier_status_code = 400,
                            supplier_response    = new { error = new { statuscode = 400, message = string.Empty } }
                        };
                        var deserializedErrorObject = JsonConvert.DeserializeAnonymousType(httpErrorObject, anonymousErrorObject);

                        var ex = new InvalidPluginExecutionException(deserializedErrorObject.supplier_response.error.message);
                        tracingService.Trace(string.Format("Throwing exception for Facacde Error: {0}", deserializedErrorObject.supplier_response.error.message));
                        throw ex;
                    }
                }
                else
                {
                    addresses = response.Content.ReadAsStringAsync().Result;
                }
            }
            this.Addresses.Set(executionContext, addresses);
            tracingService.Trace(string.Format("Returned addresses: {0}", addresses));
            //}
            //catch (FaultException<OrganizationServiceFault> e)
            //{
            //    throw e;
            //}
        }
Exemplo n.º 27
0
        /// <summary>
        /// Resolves failure reason flags based on the returned error code.
        /// </summary>
        /// <remarks>Currently only provides support for failed email auth flags.</remarks>
        private static AuthErrorReason GetFailureReason(string responseData)
        {
            var failureReason = AuthErrorReason.Undefined;

            try
            {
                if (!string.IsNullOrEmpty(responseData) && responseData != "N/A")
                {
                    //create error data template and try to parse JSON
                    var errorData = new { error = new { code = 0, message = "errorid" } };
                    errorData = JsonConvert.DeserializeAnonymousType(responseData, errorData);

                    //errorData is just null if different JSON was received
                    switch (errorData?.error?.message)
                    {
                    //general errors
                    case "invalid access_token, error code 43.":
                        failureReason = AuthErrorReason.InvalidAccessToken;
                        break;

                    case "CREDENTIAL_TOO_OLD_LOGIN_AGAIN":
                        failureReason = AuthErrorReason.LoginCredentialsTooOld;
                        break;

                    //possible errors from Third Party Authentication using GoogleIdentityUrl
                    case "INVALID_PROVIDER_ID : Provider Id is not supported.":
                        failureReason = AuthErrorReason.InvalidProviderID;
                        break;

                    case "MISSING_REQUEST_URI":
                        failureReason = AuthErrorReason.MissingRequestURI;
                        break;

                    case "A system error has occurred - missing or invalid postBody":
                        failureReason = AuthErrorReason.SystemError;
                        break;

                    //possible errors from Email/Password Account Signup (via signupNewUser or setAccountInfo) or Signin
                    case "INVALID_EMAIL":
                        failureReason = AuthErrorReason.InvalidEmailAddress;
                        break;

                    case "MISSING_PASSWORD":
                        failureReason = AuthErrorReason.MissingPassword;
                        break;

                    //possible errors from Email/Password Account Signup (via signupNewUser or setAccountInfo)
                    case "WEAK_PASSWORD : Password should be at least 6 characters":
                        failureReason = AuthErrorReason.WeakPassword;
                        break;

                    case "EMAIL_EXISTS":
                        failureReason = AuthErrorReason.EmailExists;
                        break;

                    //possible errors from Account Delete
                    case "USER_NOT_FOUND":
                        failureReason = AuthErrorReason.UserNotFound;
                        break;

                    //possible errors from Email/Password Signin
                    case "INVALID_PASSWORD":
                        failureReason = AuthErrorReason.WrongPassword;
                        break;

                    case "EMAIL_NOT_FOUND":
                        failureReason = AuthErrorReason.UnknownEmailAddress;
                        break;

                    case "USER_DISABLED":
                        failureReason = AuthErrorReason.UserDisabled;
                        break;

                    //possible errors from Email/Password Signin or Password Recovery or Email/Password Sign up using setAccountInfo
                    case "MISSING_EMAIL":
                        failureReason = AuthErrorReason.MissingEmail;
                        break;

                    //possible errors from Password Recovery
                    case "MISSING_REQ_TYPE":
                        failureReason = AuthErrorReason.MissingRequestType;
                        break;

                    //possible errors from Account Linking
                    case "INVALID_ID_TOKEN":
                        failureReason = AuthErrorReason.InvalidIDToken;
                        break;

                    //possible errors from Getting Linked Accounts
                    case "INVALID_IDENTIFIER":
                        failureReason = AuthErrorReason.InvalidIdentifier;
                        break;

                    case "MISSING_IDENTIFIER":
                        failureReason = AuthErrorReason.MissingIdentifier;
                        break;

                    case "FEDERATED_USER_ID_ALREADY_LINKED":
                        failureReason = AuthErrorReason.AlreadyLinked;
                        break;
                    }
                }
            }
            catch (JsonReaderException)
            {
                //the response wasn't JSON - no data to be parsed
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Unexpected error trying to parse the response: {e}");
            }

            return(failureReason);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Creates the Configuration table
        /// </summary>
        public override void Up()
        {
            //  Environment
            Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.SortOrder)).AsInt32().NotNullable().WithDefaultValue(999999);
            Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.Enable)).AsBoolean().NotNullable().WithDefaultValue(true);
            Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.ContinueProcessing)).AsBoolean().NotNullable().WithDefaultValue(true);
            Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.ColorIndicator)).AsString(7).NotNullable().WithDefaultValue("#df7f48");

            //  Journal
            Delete.ForeignKey("FK_" + nameof(Shield) + "_" + nameof(Data.Dto.Journal) + "_" + nameof(Dto.Configuration)).OnTable <Dto.Journal.Journal101>();
            Create.Index("IX_" + nameof(Shield) + "_" + nameof(Dto.Journal.Journal103.Datestamp)).OnTable <Dto.Journal.Journal103>()
            .OnColumn(nameof(Dto.Journal.Journal103.Datestamp)).Ascending().WithOptions().NonClustered();

            //  Configuration
            Delete.Index("IX_" + nameof(Shield) + "_" + nameof(Dto.Configuration.Configuration101.AppId)).OnTable <Dto.Configuration.Configuration101>();
            Create.Index("IX_" + nameof(Shield) + "_" + nameof(Dto.Configuration.Configuration103.AppId)).OnTable <Dto.Configuration.Configuration103>()
            .OnColumn(nameof(Dto.Configuration.Configuration103.AppId)).Ascending().WithOptions().NonClustered();

            //  Check if Backoffice Access has been installed, as we may
            //  need to update the configuration to match the new class
            var sql = new Sql();

            sql.Where <Data.Dto.Configuration>(x => x.AppId == "BackofficeAccess");

            var config = _database.FirstOrDefault <Data.Dto.Configuration>(sql);

            if (config == null)
            {
                return;
            }

            var definition = new
            {
                backendAccessUrl             = "",
                ipAddressesAccess            = 0,
                ipAddresses                  = new IpEntry103[0],
                unauthorisedAction           = TransferTypes.Redirect,
                unauthorisedUrlType          = UmbracoUrlTypes.Url,
                unauthorisedUrl              = "",
                unauthorisedUrlXPath         = "",
                unauthorisedUrlContentPicker = ""
            };

            //  Deserialize the current config to an anonymous object
            var oldData = JsonConvert.DeserializeAnonymousType(config.Value, definition);

            //  Copy the configuration to the new anonymous object
            var newData = new
            {
                oldData.backendAccessUrl,
                oldData.ipAddressesAccess,
                oldData.ipAddresses,
                oldData.unauthorisedAction,
                urlType = new UrlType103
                {
                    UrlSelector      = oldData.unauthorisedUrlType,
                    StrUrl           = oldData.unauthorisedUrl,
                    XPathUrl         = oldData.unauthorisedUrlXPath,
                    ContentPickerUrl = oldData.unauthorisedUrlContentPicker
                }
            };

            //  serialize the new configuration to the db entry's value
            config.Value = JsonConvert.SerializeObject(newData, Formatting.None);

            //  Update the entry within the DB.
            _database.Update(config);
        }
Exemplo n.º 29
0
            public static string AuthenticateAsyncViaRest(bool UseMSI, string ResourceUrl = null, string AuthorityUrl = null, string ClientId = null, string ClientSecret = null, string Username = null, string Password = null, string Scope = null, string GrantType = null)
            {
                HttpResponseMessage result = new HttpResponseMessage();

                if (UseMSI == true)
                {
                    //Logging.LogInformation("AuthenticateAsyncViaRest is using MSI");
                    using (HttpClient client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Add("Secret", Environment.GetEnvironmentVariable("MSI_SECRET"));
                        result = client.GetAsync(string.Format("{0}/?resource={1}&api-version={2}", Environment.GetEnvironmentVariable("MSI_ENDPOINT"), ResourceUrl, "2017-09-01")).Result;
                    }
                }
                else
                {
                    //Logging.LogInformation("AuthenticateAsyncViaRest is using Service Principal");
                    Uri oauthEndpoint = new Uri(AuthorityUrl);

                    using (HttpClient client = new HttpClient())
                    {
                        List <KeyValuePair <string, string> > body = new List <KeyValuePair <string, string> >();

                        if (ResourceUrl != null)
                        {
                            body.Add(new KeyValuePair <string, string>("resource", ResourceUrl));
                        }
                        if (ClientId != null)
                        {
                            body.Add(new KeyValuePair <string, string>("client_id", ClientId));
                        }
                        if (ClientSecret != null)
                        {
                            body.Add(new KeyValuePair <string, string>("client_secret", ClientSecret));
                        }
                        if (GrantType != null)
                        {
                            body.Add(new KeyValuePair <string, string>("grant_type", GrantType));
                        }
                        if (Username != null)
                        {
                            body.Add(new KeyValuePair <string, string>("username", Username));
                        }
                        if (Password != null)
                        {
                            body.Add(new KeyValuePair <string, string>("password", Password));
                        }
                        if (Scope != null)
                        {
                            body.Add(new KeyValuePair <string, string>("scope", Scope));
                        }

                        result = client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(body)).Result;
                    }
                }
                if (result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string content    = result.Content.ReadAsStringAsync().Result;
                    var    definition = new { access_token = "" };
                    var    jobject    = JsonConvert.DeserializeAnonymousType(content, definition);
                    return(jobject.access_token);
                }
                else
                {
                    string error = "AuthenticateAsyncViaRest Failed..";
                    try
                    {
                        string content = result.Content.ReadAsStringAsync().Result;
                        error = error + content;
                    }
                    catch
                    {
                    }
                    finally
                    {
                        //Logging.LogErrors(new Exception(error));
                        throw new Exception(error);
                    }
                }
            }
Exemplo n.º 30
0
        public object InsertTemporaryPeople([FromBody] JObject jObject)
        {
            var userService = new UserBLL();

            try
            {
                string res = jObject.Value <string>("json");
                var    dy  = JsonConvert.DeserializeAnonymousType(res, new
                {
                    userid = string.Empty,
                    data   = new List <TemporaryPeopleParameter>()
                });
                UserEntity createUser = userService.GetEntity(dy.userid);;
                if (createUser == null)
                {
                    throw new Exception("你没有权限添加权限");
                }

                List <UserEntity> successList = new List <UserEntity>(); //要新增到数据库里的数据
                List <object>     badList     = new List <object>();     //有问题的数据
                foreach (TemporaryPeopleParameter item in dy.data)
                {
                    try
                    {
                        if (!string.IsNullOrWhiteSpace(item.Mobile) && !userService.ExistMoblie(item.Mobile))
                        {
                            //校验手机号是否重复,重复该条数据不让添加
                            badList.Add(new { data = item, msg = "手机号重复" });
                            continue;
                        }
                        //如果账号存在则再生成一个,直到没有重复的为止
                        string pyStr   = Str.PinYin(item.RealName);
                        string account = pyStr;
                        int    count   = 1;
                        while (!userService.ExistAccount(account))
                        {
                            account = pyStr + GetNumStr(count);
                            count++;
                        }

                        UserEntity user = new UserEntity();
                        user.UserId             = Guid.NewGuid().ToString();
                        user.RealName           = item.RealName;
                        user.IdentifyID         = item.IdentifyID;
                        user.Mobile             = item.Mobile;
                        user.Account            = account;
                        user.IdentifyID         = item.IdentifyID;
                        user.IsEpiboly          = "1";
                        user.Gender             = "男";
                        user.OrganizeId         = createUser.OrganizeId;
                        user.OrganizeCode       = createUser.OrganizeCode;
                        user.CreateUserOrgCode  = createUser.OrganizeCode;
                        user.CreateDate         = DateTime.Now;
                        user.CreateUserDeptCode = createUser.DepartmentCode;
                        user.CreateUserId       = createUser.UserId;
                        user.CreateUserName     = createUser.RealName;
                        user.DepartmentId       = createUser.DepartmentId;
                        user.DepartmentCode     = createUser.DepartmentCode;
                        user.Password           = "******";//默认密码123456
                        user.IsPresence         = "1";

                        //岗位随机分配一个本班组下没有负责人角色的岗位
                        IEnumerable <RoleEntity> rlist = new JobBLL().GetList().Where(p => p.DeptId == createUser.DepartmentId && !p.RoleIds.Contains("27eb996b-1294-41d6-b8e6-837645a66819"));
                        if (rlist != null && rlist.Count() > 0)
                        {
                            var defaultRole = rlist.FirstOrDefault();
                            user.DutyId   = defaultRole.RoleId;
                            user.DutyName = defaultRole.FullName;
                        }
                        //	职务:默认为编码管理中排序为最后一个的职务
                        var defaultJob = new JobBLL().GetList().Where(p => p.OrganizeId == createUser.OrganizeId).OrderByDescending(x => x.SortCode).FirstOrDefault();
                        if (defaultJob != null)
                        {
                            user.PostName = defaultJob.FullName;
                            user.PostId   = defaultJob.RoleId;
                            user.PostCode = defaultJob.EnCode;
                        }
                        //角色,默认班组级用户
                        RoleEntity roleEntity = new RoleCache().GetList().Where(a => a.OrganizeId == createUser.OrganizeId || string.IsNullOrWhiteSpace(a.OrganizeId)).Where(p => p.FullName.Contains("班组级用户")).FirstOrDefault();
                        if (roleEntity != null)
                        {
                            user.RoleId = roleEntity.RoleId;
                        }
                        user.RoleName = roleEntity.FullName;
                        roleEntity    = new RoleCache().GetList().Where(a => a.OrganizeId == createUser.OrganizeId || string.IsNullOrWhiteSpace(a.OrganizeId)).Where(p => p.FullName.Contains("普通用户")).FirstOrDefault();
                        if (roleEntity != null)
                        {
                            if (!string.IsNullOrEmpty(roleEntity.RoleId))
                            {
                                user.RoleId   += "," + roleEntity.RoleId;
                                user.RoleName += "," + roleEntity.FullName;
                            }
                            else
                            {
                                user.RoleId  += roleEntity.RoleId;
                                user.RoleName = roleEntity.FullName;
                            }
                        }
                        string objId = userService.SaveForm(user.UserId, user, 0);
                        if (!string.IsNullOrWhiteSpace(objId))
                        {
                            //不为空则添加成功
                            successList.Add(user);
                            if (!string.IsNullOrWhiteSpace(new DataItemDetailBLL().GetItemValue("bzAppUrl")))
                            {
                                user.Password = "******";
                                var task = Task.Factory.StartNew(() =>
                                {
                                    SaveUser(user);
                                });
                            }
                        }
                        else
                        {
                            badList.Add(new { data = item, msg = "添加失败" });
                        }
                    }
                    catch (Exception itemEx)
                    {
                        badList.Add(new { data = item, msg = itemEx.Message });
                    }
                }

                return(new { Code = 0, Info = "操作成功", data = successList.Select(p => new { p.RealName, p.Account, Password = "******" }) });
            }
            catch (Exception ex)
            {
                return(new { Code = -1, info = "操作失败", data = ex.Message });
            }
        }