protected void Page_Load(object sender, EventArgs e)
        {
            var json = Request.Form["json"];

            if (json == null)
            {
                return;
            }

            if (json == "]")
                json = "";

            var periodo = Request.Form["periodo"];

            Newtonsoft.Json.Linq.JArray gastosArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(json);
            if (gastosArray == null) gastosArray = new Newtonsoft.Json.Linq.JArray();

            Data.edificio ed = new Data.edificio(); ed.direccion = Request.Params["edificio"];

            List<Data.Recargo> gastos = new List<Data.Recargo>();
            foreach (var r in gastosArray)
            {
                Data.Recargo rec = new Data.Recargo();
                //['1','1/12/2015','Reparacion piso','00-01','Exclusivos','1.525,20','No']
                rec.Edificio = ed.direccion;
                rec.Fecha = DateTime.Parse(r[1].ToString());
                rec.Concepto = r[2].ToString();
                rec.Unidad = r[3].ToString();
                rec.Tipo = r[4].ToString();
                double importe = Math.Abs(double.Parse(r[5].ToString()));
                rec.Importe = importe;
                rec.Pagado = r[6].ToString();
                gastos.Add(rec);
            }

            var per = DateTime.Parse(periodo);

            Business.ControladorGastosExclusivos.addGastos(ed, per, gastos);

            Response.Redirect("GastosExclusivos.aspx?edificio=" + ed.direccion + "&periodo=" + per.Month + "/" + per.Year);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                var json = Request.Form["json"];
                if (json == null || json == "") { //Sectores
                Data.edificio edificio = new Data.edificio(); edificio.direccion = Request.Params["edificio"];
                List<Data.sector> sectores = new List<Data.sector>();
                foreach (String i in Request.Form)
                {
                    if (i.Contains("edi_"))
                    {
                        Data.sector s = new Data.sector();
                        s.descripcion = i.Replace("edi_", "");
                        sectores.Add(s);
                    }
                }

                    Business.ControladorSectores.setSectoresEdificio(edificio, sectores);
                    Response.Redirect("asignarSectores.aspx?edificio=" + edificio.direccion + "&cambios=1");
                }
                else //Coeficientes
                {
                    Data.edificio edificio = new Data.edificio(); edificio.direccion = Request.Params["edificio"];
                    List<Data.sector> sectores = Business.ControladorSectores.getAllSectoresEdificio(edificio);
                    //Buscar los sectores del edificio y parsear json para esos. El json trae valores para todos los sectores

                    if (json == "]")
                        json = "";

                    Newtonsoft.Json.Linq.JArray coeficientesArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(json);
                    if (coeficientesArray == null) coeficientesArray = new Newtonsoft.Json.Linq.JArray();

                    List<Entidades.Coeficientes> coeficientes = new List<Entidades.Coeficientes>();
                    foreach (var c in coeficientesArray)
                    {
                        //['00-01','5,05','0,00','0,00','0,00','0,00','0,00']
                        Entidades.Coeficientes coef = new Entidades.Coeficientes();
                        coef.Unidad = c[0].ToString();
                        coef.Rubro1 = Double.Parse(c[1].ToString());
                        coef.Rubro2 = Double.Parse(c[2].ToString());
                        coef.Rubro3 = Double.Parse(c[3].ToString());
                        coef.Rubro4 = Double.Parse(c[4].ToString());
                        coef.Rubro5 = Double.Parse(c[5].ToString());
                        coef.Rubro6 = Double.Parse(c[6].ToString());
                        coeficientes.Add(coef);
                    }

                    Business.ControladorExpensas.ActualizarCoeficientes(edificio, coeficientes);

                    Response.Redirect("asignarSectores.aspx?edificio=" + edificio.direccion + "&cambios=1");

                }

            }
        }
Example #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var json = Request.Form["json"];

            if (json == null)
            {
                return;
            }

            if (json == "]")
                json = "";

            var periodo = Request.Form["periodo"];

            Newtonsoft.Json.Linq.JArray facturasArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(json);
            if (facturasArray == null) facturasArray = new Newtonsoft.Json.Linq.JArray();

            Data.edificio ed = new Data.edificio(); ed.direccion = Request.Params["edificio"];
            List<Data.sector> sectores = Business.ControladorSectores.getAllSectoresEdificio(ed);
            List<Data.tipo_gasto> gastos = Business.ControladorTiposDeGasto.getAllTiposDeGasto();

            List<Data.factura> facturas = new List<Data.factura>();
            foreach (var f in facturasArray)
            {
                //['16/11/2015','EficientLimp','828','Limpieza Edificio','','3.500,00','Generales']
                Data.factura fact = new Data.factura();
                if (!f[0].ToString().Contains("agregado"))
                    fact.idfactura = int.Parse(f[0].ToString());
                fact.dir_edificio = ed.direccion;
                fact.fecha = DateTime.Parse(f[1].ToString());
                if (!f[2].ToString().Contains("Ninguno"))
                    fact.razon_provedor = f[2].ToString();
                fact.numero_factura = f[3].ToString();

                foreach (var g in gastos)
                    if (g.descripcion == f[4].ToString())
                        fact.id_tipogasto = g.idtipo_gasto;

                fact.detalle = f[5].ToString();
                fact.importe = parsearDoubleNulleable(f[6].ToString());
                foreach (var s in sectores)
                    if (s.descripcion == f[7].ToString())
                        fact.id_sector = s.idsector;
                facturas.Add(fact);
            }

            Business.ControladorFacturas.agregarFacturasWeb(facturas, ed, DateTime.Parse(periodo));

            Response.Redirect("Facturas.aspx?edificio=" + ed.direccion + "&periodo=" + DateTime.Parse(periodo).Month + "/" + DateTime.Parse(periodo).Year);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var json = Request.Form["json"];

            if (json == null)
            {
                return;
            }

            if (json == "]")
                json = "";

            var periodo = Request.Form["periodo"];

            Newtonsoft.Json.Linq.JArray movimientosArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(json);
            if (movimientosArray == null) movimientosArray = new Newtonsoft.Json.Linq.JArray();

            Data.edificio ed = new Data.edificio(); ed.direccion = Request.Params["edificio"];

            List<Data.movimiento_caja> movimientos = new List<Data.movimiento_caja>();
            foreach (var m in movimientosArray)
            {
                Data.movimiento_caja mov = new Data.movimiento_caja();
                // ['1','1/11/2015','Aporte fondo','Ingreso','500,00']
                if (!m[0].ToString().Contains("agregado"))
                    mov.id_movimiento = int.Parse(m[0].ToString());
                mov.dir_edificio = ed.direccion;
                mov.fecha = DateTime.Parse(m[1].ToString());
                mov.periodo = mov.fecha;
                mov.concepto = m[2].ToString();

                double importe = Math.Abs(double.Parse(m[4].ToString()));

                if (m[3].ToString().Contains("Ingreso"))
                    mov.importe = importe;
                else
                    mov.importe = importe * -1;

                movimientos.Add(mov);
            }

            var per = DateTime.Parse(periodo);

            Business.ControladorEdificios.setMovimientosCaja(ed, per, movimientos);

            Response.Redirect("MovimientoCaja.aspx?edificio=" + ed.direccion + "&periodo=" + per.Month + "/" + per.Year);
        }
        public ChangeFailureRateModel GetChangeFailureRate(bool getSampleData, TableStorageConfiguration tableStorageConfig,
                                                           DevOpsPlatform targetDevOpsPlatform, string organization_owner, string project_repo, string branch, string buildName_workflowName,
                                                           int numberOfDays, int maxNumberOfItems)
        {
            ListUtility <ChangeFailureRateBuild> utility = new ListUtility <ChangeFailureRateBuild>();
            ChangeFailureRate changeFailureRate          = new ChangeFailureRate();

            if (getSampleData == false)
            {
                //Gets a list of change failure rate builds from Azure storage
                AzureTableStorageDA           daTableStorage = new AzureTableStorageDA();
                Newtonsoft.Json.Linq.JArray   list           = daTableStorage.GetTableStorageItemsFromStorage(tableStorageConfig, tableStorageConfig.TableChangeFailureRate, PartitionKeys.CreateBuildWorkflowPartitionKey(organization_owner, project_repo, buildName_workflowName));
                List <ChangeFailureRateBuild> initialBuilds  = JsonConvert.DeserializeObject <List <ChangeFailureRateBuild> >(list.ToString());

                //Build the date list and then generate the change failure rate metric
                List <ChangeFailureRateBuild>         builds   = new List <ChangeFailureRateBuild>();
                List <KeyValuePair <DateTime, bool> > dateList = new List <KeyValuePair <DateTime, bool> >();
                float maxBuildDuration = 0f;
                foreach (ChangeFailureRateBuild item in initialBuilds)
                {
                    if (item.Branch == branch && item.StartTime > DateTime.Now.AddDays(-numberOfDays))
                    {
                        //Special branch for Azure DevOps to construct the Url to each build
                        if (targetDevOpsPlatform == DevOpsPlatform.AzureDevOps)
                        {
                            item.Url = $"https://dev.azure.com/{organization_owner}/{project_repo}/_build/results?buildId={item.Id}&view=results";
                        }
                        builds.Add(item);
                    }
                }

                //then build the calcuation
                foreach (ChangeFailureRateBuild item in builds)
                {
                    KeyValuePair <DateTime, bool> newItem = new KeyValuePair <DateTime, bool>(item.StartTime, item.DeploymentWasSuccessful);
                    dateList.Add(newItem);
                }
                //calculate the metric on all of the results
                float changeFailureRateMetric = changeFailureRate.ProcessChangeFailureRate(dateList, numberOfDays);

                //Filter the results to return the last n (maxNumberOfItems)
                List <ChangeFailureRateBuild> uiBuilds = utility.GetLastNItems(builds, maxNumberOfItems);
                foreach (ChangeFailureRateBuild item in uiBuilds)
                {
                    if (item.BuildDuration > maxBuildDuration)
                    {
                        maxBuildDuration = item.BuildDuration;
                    }
                }
                //We need to do some post processing and loop over the list a couple times to find the max build duration, construct a usable url, and calculate a build duration percentage
                foreach (ChangeFailureRateBuild item in uiBuilds)
                {
                    float interiumResult = ((item.BuildDuration / maxBuildDuration) * 100f);
                    item.BuildDurationPercent = Scaling.ScaleNumberToRange(interiumResult, 0, 100, 20, 100);
                }

                ChangeFailureRateModel model = new ChangeFailureRateModel
                {
                    TargetDevOpsPlatform               = targetDevOpsPlatform,
                    DeploymentName                     = buildName_workflowName,
                    ChangeFailureRateBuildList         = uiBuilds,
                    ChangeFailureRateMetric            = changeFailureRateMetric,
                    ChangeFailureRateMetricDescription = changeFailureRate.GetChangeFailureRateRating(changeFailureRateMetric),
                    NumberOfDays     = numberOfDays,
                    MaxNumberOfItems = uiBuilds.Count,
                    TotalItems       = builds.Count
                };
                return(model);
            }
            else
            {
                //Get sample data
                List <ChangeFailureRateBuild> sampleBuilds = utility.GetLastNItems(GetSampleBuilds(), maxNumberOfItems);
                ChangeFailureRateModel        model        = new ChangeFailureRateModel
                {
                    TargetDevOpsPlatform               = targetDevOpsPlatform,
                    DeploymentName                     = buildName_workflowName,
                    ChangeFailureRateBuildList         = sampleBuilds,
                    ChangeFailureRateMetric            = 2f / 10f,
                    ChangeFailureRateMetricDescription = changeFailureRate.GetChangeFailureRateRating(2f / 10f),
                    NumberOfDays     = numberOfDays,
                    MaxNumberOfItems = sampleBuilds.Count,
                    TotalItems       = sampleBuilds.Count
                };
                return(model);
            }
        }
Example #6
0
        ///<summary>
        /// 将JSON解析成DataSet只限特定格式的JSON数据
        /// JAFly 2015-11-26
        /// </summary>
        public static DataSet JsonToDataSet(object Json, string DataTableName)
        {
            try
            {
                Json = Json.ToString().Replace("}", "}").Replace("{", "{").Replace(":", ":");
                DataSet       ds  = new DataSet("well_data");
                List <object> lst = new List <object>();
                lst.Add(Json.ToString());
                foreach (object js in lst)
                {
                    object obj = null;
                    if (js is System.String)
                    {
                        obj = JsonConvert.DeserializeObject(js.ToString().Replace("“", "\"").Replace("”", "\"").Replace(":", ":").Replace(",", ",")); //去除中文标点影响
                    }

                    #region 多价值对
                    Newtonsoft.Json.Linq.JArray objs = null;
                    objs = (Newtonsoft.Json.Linq.JArray)obj;
                    DataTable dt = new DataTable(DataTableName);
                    if (!dt.Columns.Contains("objIndex"))
                    {
                        dt.Columns.Add("objIndex", typeof(System.Int32));
                    }
                    int objIndex = 1;



                    foreach (object obc in objs)
                    {
                        if (obc is System.String)
                        {
                            if (!dt.Columns.Contains("objName"))
                            {
                                dt.Columns.Add("objName");
                            }
                            DataRow dr = dt.NewRow();
                            dr["objIndex"] = objIndex;
                            dr["objName"]  = obc.ToString().Trim();
                            dt.Rows.Add(dr);
                        }
                        else
                        {
                            Newtonsoft.Json.Linq.JObject datajson = (Newtonsoft.Json.Linq.JObject)obc;
                            DataRow dr = dt.NewRow();
                            foreach (KeyValuePair <string, Newtonsoft.Json.Linq.JToken> sss in datajson)
                            {
                                if (!dt.Columns.Contains(sss.Key))
                                {
                                    dt.Columns.Add(sss.Key.ToString());
                                }

                                dr[sss.Key] = sss.Value;
                            }
                            dr["objIndex"] = objIndex;
                            dt.Rows.Add(dr);
                        }
                        objIndex++;
                    }

                    DataView dv = dt.DefaultView;
                    dv.Sort = "objIndex desc ";
                    DataTable dtTemp = dv.ToTable();
                    ds.Tables.Add(dtTemp);


                    #endregion
                }
                if (TmoShare.DataSetVerify(ds) != null)
                {
                    DataSet dsTemp = TmoShare.getDataSetFromXML(TmoShare.getXMLFromDataSet(ds));
                    return(TmoShare.DataSetVerify(dsTemp));
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }
        }
Example #7
0
        public static Dictionary<string, string> ParseJson(string res)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            Newtonsoft.Json.Linq.JArray result = new Newtonsoft.Json.Linq.JArray();
            try
            {
                result = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(res);

            }
            catch
            {
                MessageBox.Show("Ошибка сети, попытайтесь позже.");
                return null;
            }

            foreach (Newtonsoft.Json.Linq.JObject value in result)
            {
                dict.Add(value.Value<string>("userid").ToString().Trim(), value.Value<string>("login").ToString().Trim());
            }
            return dict;
        }
        public async Task <bool> UpdateChangeFailureRate(TableStorageAuth tableStorageAuth,
                                                         string organization_owner, string project_repo, string buildName_workflowName,
                                                         int percentComplete, int numberOfDays)
        {
            //Gets a list of change failure rate builds
            AzureTableStorageDA daTableStorage = new AzureTableStorageDA();
            string partitionKey = daTableStorage.CreateBuildWorkflowPartitionKey(organization_owner, project_repo, buildName_workflowName);

            Newtonsoft.Json.Linq.JArray   list          = daTableStorage.GetTableStorageItems(tableStorageAuth, tableStorageAuth.TableChangeFailureRate, partitionKey);
            List <ChangeFailureRateBuild> initialBuilds = JsonConvert.DeserializeObject <List <ChangeFailureRateBuild> >(list.ToString());

            //Get the list of items we are going to process, within the date/day range
            List <ChangeFailureRateBuild> builds = new List <ChangeFailureRateBuild>();

            foreach (ChangeFailureRateBuild item in initialBuilds)
            {
                if (item.StartTime > DateTime.Now.AddDays(-numberOfDays))
                {
                    builds.Add(item);
                }
            }

            //Using the percent, convert it to a fraction
            int numerator   = 0;
            int denominator = 0;

            switch (percentComplete)
            {
            case 0:
                numerator   = 0;
                denominator = 1;
                break;

            case 10:
                numerator   = 1;
                denominator = 10;
                break;

            case 25:
                numerator   = 1;
                denominator = 4;
                break;

            case 50:
                numerator   = 1;
                denominator = 2;
                break;

            case 75:
                numerator   = 3;
                denominator = 4;
                break;

            case 98:
                numerator   = 49;
                denominator = 50;
                break;

            case 100:
                numerator   = 1;
                denominator = 1;
                break;

            default:
                numerator   = 1;
                denominator = 1;
                break;
            }

            //Get builds for positive (builds we will set DeploymentWasSuccessful=true) and negative (builds we will set to DeploymentWasSuccessful=false)
            Console.WriteLine($"numerator {numerator} / denominator {denominator}");
            List <ChangeFailureRateBuild> postiveBuilds  = builds.Where((x, numerator) => numerator % denominator != 0).ToList();
            List <ChangeFailureRateBuild> negativeBuilds = builds.Where((x, numerator) => numerator % denominator == 0).ToList();

            //Make the updates
            TableStorageCommonDA tableChangeFailureRateDA = new TableStorageCommonDA(tableStorageAuth, tableStorageAuth.TableChangeFailureRate);

            foreach (ChangeFailureRateBuild item in postiveBuilds)
            {
                item.DeploymentWasSuccessful = true;
                await daTableStorage.UpdateChangeFailureRate(tableChangeFailureRateDA, item, partitionKey, true);
            }
            foreach (ChangeFailureRateBuild item in negativeBuilds)
            {
                item.DeploymentWasSuccessful = false;
                await daTableStorage.UpdateChangeFailureRate(tableChangeFailureRateDA, item, partitionKey, true);
            }

            return(true);
        }
Example #9
0
 public static TradeRecordsCommand createTradeRecordsCommand(LinkedList<long?> orders, bool prettyPrint)
 {
     JSONObject args = new JSONObject();
     JSONArray arr = new JSONArray();
     foreach (long? order in orders)
     {
         arr.Add(order);
     }
     args.Add("orders", arr);
     return new TradeRecordsCommand(args, prettyPrint);
 }
        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="obj">异步对象</param>
        protected override void ThreadPoolLogin(object obj)
        {
            if (obj is Socket socket)
            {
                OperateResult result = new OperateResult( );

                // 获取ip地址
                string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( );

                // 接收操作信息
                if (!ReceiveInformationHead(
                        socket,
                        out int customer,
                        out string fileName,
                        out string Factory,
                        out string Group,
                        out string Identify).IsSuccess)
                {
                    return;
                }

                string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName);

                if (customer == HslProtocol.ProtocolFileDownload)
                {
                    // 先获取文件的真实名称
                    string guidName = TransformFactFileName(Factory, Group, Identify, fileName);
                    // 获取文件操作锁
                    FileMarkId fileMarkId = GetFileMarksFromDictionaryWithFileName(guidName);
                    fileMarkId.EnterReadOperator( );
                    // 发送文件数据
                    OperateResult send = SendFileAndCheckReceive(socket, ReturnAbsoluteFileName(Factory, Group, Identify, guidName), fileName, "", "", null);
                    if (!send.IsSuccess)
                    {
                        fileMarkId.LeaveReadOperator( );
                        LogNet?.WriteError(ToString( ), $"{StringResources.Language.FileDownloadFailed} : {send.Message} :{relativeName} ip:{IpAddress}");
                        return;
                    }
                    else
                    {
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDownloadSuccess + ":" + relativeName);
                    }

                    fileMarkId.LeaveReadOperator( );
                    // 关闭连接
                    socket?.Close( );
                }
                else if (customer == HslProtocol.ProtocolFileUpload)
                {
                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);
                    // 上传文件
                    CheckFolderAndCreate( );
                    FileInfo info = new FileInfo(fullFileName);

                    try
                    {
                        if (!Directory.Exists(info.DirectoryName))
                        {
                            Directory.CreateDirectory(info.DirectoryName);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogNet?.WriteException(ToString( ), StringResources.Language.FilePathCreateFailed + fullFileName, ex);
                        socket?.Close( );
                        return;
                    }

                    // 接收文件并回发消息
                    if (ReceiveFileFromSocketAndUpdateGroup(
                            socket,                // 网络套接字
                            fullFileName).IsSuccess)
                    {
                        socket?.Close( );
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadSuccess + ":" + relativeName);
                    }
                    else
                    {
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadFailed + ":" + relativeName);
                    }
                }
                else if (customer == HslProtocol.ProtocolFileDelete)
                {
                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                    FileInfo           info          = new FileInfo(fullFileName);
                    GroupFileContainer fileManagment = GetGroupFromFilePath(info.DirectoryName);

                    // 新增删除的任务
                    DeleteExsistingFile(info.DirectoryName, fileManagment.DeleteFile(info.Name));

                    // 回发消息
                    if (SendStringAndCheckReceive(
                            socket,                                                            // 网络套接字
                            1,                                                                 // 没啥含义
                            "success"                                                          // 没啥含意
                            ).IsSuccess)
                    {
                        socket?.Close( );
                    }

                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDeleteSuccess + ":" + relativeName);
                }
                else if (customer == HslProtocol.ProtocolFileDirectoryFiles)
                {
                    GroupFileContainer fileManagment = GetGroupFromFilePath(ReturnAbsoluteFilePath(Factory, Group, Identify));

                    if (SendStringAndCheckReceive(
                            socket,
                            HslProtocol.ProtocolFileDirectoryFiles,
                            fileManagment.JsonArrayContent).IsSuccess)
                    {
                        socket?.Close( );
                    }
                }
                else if (customer == HslProtocol.ProtocolFileDirectories)
                {
                    List <string> folders = new List <string>( );
                    foreach (var m in GetDirectories(Factory, Group, Identify))
                    {
                        DirectoryInfo directory = new DirectoryInfo(m);
                        folders.Add(directory.Name);
                    }

                    Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( ));
                    if (SendStringAndCheckReceive(
                            socket,
                            HslProtocol.ProtocolFileDirectoryFiles,
                            jArray.ToString( )).IsSuccess)
                    {
                        socket?.Close( );
                    }
                }
                else
                {
                    // close not supported client
                    socket?.Close( );
                }
            }
        }
Example #11
0
        /// <summary>
        /// 过滤通配符
        /// </summary>
        /// <param name="str"></param>
        /// <param name="currentUser">当前登录用户实体</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Filter(string str, Model.User user = null, object obj = null)
        {
            if (str.IsNullOrWhiteSpace())
            {
                return("");
            }
            Microsoft.AspNetCore.Http.HttpRequest request = Tools.HttpContext.Request;
            foreach (string wildcard in wildcardList)
            {
                while (str.ContainsIgnoreCase(wildcard))
                {
                    string value     = string.Empty;
                    string wildcard1 = wildcard;
                    if ("{Query<".EqualsIgnoreCase(wildcard))
                    {
                        string key  = str.Substring(str.IndexOf("{Query<") + 7);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1 = wildcard + key1 + ">}";
                            value     = request.Querys(key1);
                        }
                    }
                    else if ("{Form<".EqualsIgnoreCase(wildcard))
                    {
                        string key  = str.Substring(str.IndexOf("{Form<") + 6);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1 = wildcard + key1 + ">}";
                            value     = request.Forms(key1);
                        }
                    }
                    else if ("{DataRow<".EqualsIgnoreCase(wildcard))
                    {
                        string key  = str.Substring(str.IndexOf("{DataRow<") + 9);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1 = wildcard + key1 + ">}";
                            var dr = (System.Data.DataRow)obj;
                            try
                            {
                                value = dr[key1].ToString();
                            }
                            catch
                            {
                                value = "";
                            }
                        }
                    }
                    else if ("{Method<".EqualsIgnoreCase(wildcard))
                    {
                        //执行一个方法替换通配符 object为方法参数
                        string key  = str.Substring(str.IndexOf("{Method<") + 8);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1   = wildcard + key1 + ">}";
                            var(o, err) = obj == null?Tools.ExecuteMethod(key1) : Tools.ExecuteMethod(key1, obj);

                            value = null == o ? "" : o.ToString();
                        }
                    }
                    else if ("{Date<".EqualsIgnoreCase(wildcard))
                    {
                        //取当前日期替换指定格式
                        string key  = str.Substring(str.IndexOf("{Date<") + 6);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1 = wildcard + key1 + ">}";
                            value     = DateExtensions.Now.ToString(key1);
                        }
                    }
                    else if ("{Object<".EqualsIgnoreCase(wildcard))
                    {
                        //将对象转换为字符串替换
                        string key  = str.Substring(str.IndexOf("{Object<") + 8);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1 = wildcard + key1 + ">}";
                            value     = obj == null  ? "" : obj.ToString();
                        }
                    }
                    else if ("{JArray<".EqualsIgnoreCase(wildcard))
                    {
                        //取json数组值
                        string key  = str.Substring(str.IndexOf("{JArray<") + 8);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1 = wildcard + key1 + ">}";
                            Newtonsoft.Json.Linq.JArray jArray = (Newtonsoft.Json.Linq.JArray)obj;
                            if (null != jArray)
                            {
                                foreach (Newtonsoft.Json.Linq.JObject jObject in jArray)
                                {
                                    if (jObject.ContainsKey(key1))
                                    {
                                        value = jObject.Value <string>(key1);
                                        break;
                                    }
                                }
                                if (value.IsNullOrEmpty())
                                {
                                    //这里循环找是取表单数据形式的JSON [{"name":"","value":""}] 这里取表单字段对应的值
                                    foreach (Newtonsoft.Json.Linq.JObject jObject in jArray)
                                    {
                                        if (jObject.ContainsKey("name") && jObject.Value <string>("name").Equals(key1))
                                        {
                                            value = jObject.Value <string>("value");
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                value = "";
                            }
                        }
                    }
                    else if ("{JObject<".EqualsIgnoreCase(wildcard))
                    {
                        //取json对象值
                        string key  = str.Substring(str.IndexOf("{JObject<") + 9);
                        string key1 = key.Substring(0, key.IndexOf(">}"));
                        if (!key1.IsNullOrWhiteSpace())
                        {
                            wildcard1 = wildcard + key1 + ">}";
                            Newtonsoft.Json.Linq.JObject jObject = (Newtonsoft.Json.Linq.JObject)obj;
                            if (null != jObject && jObject.ContainsKey(key1))
                            {
                                value = jObject.Value <string>(key1);
                            }
                            else
                            {
                                value = "";
                            }
                        }
                    }
                    else
                    {
                        value = GetWildcardValue(wildcard, user, obj);
                    }
                    str = str.ReplaceIgnoreCase(wildcard1, value);
                }
            }
            return(str);
        }
Example #12
0
        /// <summary>
        /// Génère le code pour la fonction de traitement des messages.
        /// </summary>
        public string ProcessRequest(string request, int clientId)
        {
            Newtonsoft.Json.Linq.JArray o = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(request);
            int functionId = o.Value <int>(0);

            switch (functionId)
            {
            case 0:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetHero(clientId)
                }));

            case 1:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetPosition(clientId)
                }));

            case 2:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetMapView(clientId)
                }));

            case 3:
                Vector2 arg3_0 = (Vector2)o[1][0].ToObject(typeof(Vector2));
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    StartMoveTo(arg3_0, clientId)
                }));

            case 4:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    IsAutoMoving(clientId)
                }));

            case 5:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    EndMoveTo(clientId)
                }));

            case 6:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetEntitiesInSight(clientId)
                }));

            case 7:
                int arg7_0 = o[1].Value <int>(0);
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetEntityById(arg7_0, clientId)
                }));

            case 8:
                int arg8_0 = o[1].Value <int>(0);
                SpellCastTargetInfoView arg8_1 = (SpellCastTargetInfoView)o[1][1].ToObject(typeof(SpellCastTargetInfoView));
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    UseSpell(arg8_0, arg8_1, clientId)
                }));

            case 9:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetMode(clientId)
                }));

            case 10:
                int arg10_0 = o[1].Value <int>(0);
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetSpellCurrentLevelDescription(arg10_0, clientId)
                }));

            case 11:
                int arg11_0 = o[1].Value <int>(0);
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetSpell(arg11_0, clientId)
                }));

            case 12:
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetSpells(clientId)
                }));

            case 13:
                int arg13_0 = o[1].Value <int>(0);
                return(Newtonsoft.Json.JsonConvert.SerializeObject(new List <object>()
                {
                    GetHeroSpells(arg13_0, clientId)
                }));
            }
            return("");
        }
        private ActionResult ImportPOI()
        {
            HttpWebRequest  request;
            HttpWebResponse response;

            string poi_tree_result;
            Dictionary <dynamic, dynamic> POITreeDictionary = new Dictionary <dynamic, dynamic>();

            POITermsDictionary.Add("it",
                                   new Dictionary <string, int> {
                { "altre attrattive", 89 },
                { "beni culturali", 32 },
                { "centri storici", 30 },
                { "edifici religiosi", 31 },
                { "parchi e natura", 90 }
            });

            POITermsDictionary.Add("fr",
                                   new Dictionary <string, int> {
                { "altre attrattive", 93 },
                { "beni culturali", 41 },
                { "centri storici", 40 },
                { "edifici religiosi", 42 },
                { "parchi e natura", 94 }
            });

            POITermsDictionary.Add("en",
                                   new Dictionary <string, int> {
                { "altre attrattive", 116 },
                { "beni culturali", 117 },
                { "centri storici", 118 },
                { "edifici religiosi", 119 },
                { "parchi e natura", 120 }
            });

            try {
                string URL = baseURL + "RPC2";
                request             = (HttpWebRequest)WebRequest.Create(URL);
                request.ContentType = "application/json; charset=utf-8";
                request.Method      = "POST";

                using (var streamWriter = new StreamWriter(request.GetRequestStream())) {
                    string json = "{\"id\":\"djangorpc\", \"method\" : \"resources.get_poicategory_visible_tree\", \"params\" : [\"it\"]}";

                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                response = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(response.GetResponseStream())) {
                    poi_tree_result   = streamReader.ReadToEnd();
                    POITreeDictionary = JsonConvert.DeserializeObject <Dictionary <dynamic, dynamic> >(poi_tree_result);
                }
            } catch (Exception e) {
                poi_tree_result = e.Message;
            }

            dynamic model = new ExpandoObject();

            model.TreeResult   = poi_tree_result;
            model.ImportResult = "";

            try {
                if (!String.IsNullOrWhiteSpace(POITreeDictionary["result"].ToString()))
                {
                    Newtonsoft.Json.Linq.JArray category = POITreeDictionary["result"];

                    foreach (Newtonsoft.Json.Linq.JToken item in category)
                    {
                        string parentCategory = item["name"].ToString().ToLower();

                        bool hasChildren = false;

                        foreach (Newtonsoft.Json.Linq.JToken child in item["children"])
                        {
                            hasChildren         = true;
                            model.ImportResult += importCategory(child, parentCategory) + "\n";
                        }

                        if (!hasChildren)
                        {
                            model.ImportResult += importCategory(item, parentCategory) + "\n";
                        }
                    }
                }
            } catch (Exception e) {
                model.ImportResult = e.Message;
            }

            return(View("Import", model));
        }
Example #14
0
        public static void SendTemplate( string template_name, Dictionary<string, object> data, TemplateOverrides overrides = null )
        {
            var template_path = System.Web.HttpContext.Current.Server.MapPath(Config.Manager.Framework.Email.Template.Path);
            var base_path = Path.Combine( template_path, template_name );

            if( !File.Exists( Path.Combine(base_path,"config.json") ) )
                throw new FileNotFoundException( "Could not find the specified config file." );

            var sr_config = new StreamReader( Path.Combine(base_path,"config.json") );
            var config = Newtonsoft.Json.Linq.JObject.Parse( sr_config.ReadToEnd() );
            sr_config.Close();

            if( !File.Exists(Path.Combine( base_path, (string)config["file"] )) )
                throw new FileNotFoundException( "The file [" + (string)config["file"] + "] referenced in the template config can not be found in [" + base_path + "]." );

            if( overrides != null )
            {
                if( !string.IsNullOrEmpty( overrides.Subject ) )
                    config["subject"] = overrides.Subject;

                if( overrides.To != null )
                {
                    var arr = new Newtonsoft.Json.Linq.JArray();

                    foreach( var to in overrides.To )
                    {
                        arr.Add(new Newtonsoft.Json.Linq.JObject(new Newtonsoft.Json.Linq.JProperty("name", to.DisplayName), new Newtonsoft.Json.Linq.JProperty("email", to.Address)));
                    }

                    config["to"] = arr;
                }

                if( overrides.From != null )
                {
                    config["from"] = new Newtonsoft.Json.Linq.JObject( new Newtonsoft.Json.Linq.JProperty( "name", overrides.From.DisplayName ), new Newtonsoft.Json.Linq.JProperty( "email", overrides.From.Address ) );
                }
            }

            if( config["vars"] != null )
            {
                foreach( Newtonsoft.Json.Linq.JObject o in config["vars"] )
                {
                    string name = (string)o["name"];
                    string file = (string)o["file"];
                    string loop_over = (string)o["loop_over"];
                    string condition = (string)o["condition"];

                    if( !File.Exists( Path.Combine( base_path, file ) ) )
                        throw new FileNotFoundException( "The file ["+file+"] referenced in the template config can not be found in ["+base_path+"]." );

                    var sr_inner = new StreamReader( Path.Combine( base_path, file ) );
                    string inner_content = sr_inner.ReadToEnd();
                    sr_inner.Close();
                    data[name] = "";

                    if( !string.IsNullOrEmpty( condition ) )
                    {
                        // test condition, if true allow execution to continue, else continue
                    }

                    if( !string.IsNullOrEmpty( loop_over ) )
                    {
                        if( !data.ContainsKey( loop_over ) )
                            throw new ArgumentException( "The data dictionary is missing a required value called ["+loop_over+"].", "data" );

                        var list = data[loop_over] as IEnumerable;

                        if( list == null )
                            throw new ArgumentException( "The value called [" + loop_over + "] in the data dictionary must be castable to an IEnumerable.", "data" );

                        var regex_inner = new System.Text.RegularExpressions.Regex( @"\{\{([a-zA-Z0-9_\-\.]+)\}\}", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.CultureInvariant );
                        var matches_inner = regex_inner.Matches( inner_content );

                        var builder = new StringBuilder();
                        foreach( var item in list )
                        {
                            string t_content = inner_content;

                            foreach( System.Text.RegularExpressions.Match m in matches_inner )
                            {
                                var orig_match = m.Value;
                                var group = m.Groups[1];
                                var parts = group.Value.Split( '.' );

                                if( parts[0] == "Item" )
                                    t_content = t_content.Replace( orig_match, GetValue( item, parts, orig_match, 1 ) );
                                else
                                    t_content = t_content.Replace( orig_match, GetValue( data[parts[0]], parts, orig_match, 1 ) );
                            }

                            builder.AppendLine( t_content );
                        }

                        inner_content = builder.ToString();
                    }

                    data[name] = inner_content;
                }
            }

            var sr = new StreamReader( Path.Combine( base_path, (string)config["file"] ) );
            string content = sr.ReadToEnd();
            sr.Close();

            var regex = new System.Text.RegularExpressions.Regex( @"\{\{([a-zA-Z0-9_\-\.]+)\}\}", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.CultureInvariant );
            var matches = regex.Matches( content );

            foreach( System.Text.RegularExpressions.Match m in matches )
            {
                var orig_match = m.Value;
                var group = m.Groups[1];
                var parts = group.Value.Split( '.' );

                content = content.Replace( orig_match, GetValue(data[parts[0]], parts, orig_match, 1) );
            }

            // MJL 2014-01-13 - If you use the "To" field in the overrides, then the config["to"] is an array
            // the original code seems to assume it's not a collection.  I've added a simple check to see
            // if the object is a collection, of so, loop.
            if(!(config["to"] is ICollection))
                SendEmail((string)(config["to"]["email"]), (string)(config["subject"]), content, (string)(config["from"]["email"]), (string)(config["from"]["name"]));
            else
                foreach(var item in config["to"])
                    SendEmail((string)(item["email"]), (string)(config["subject"]), content, (string)(config["from"]["email"]), (string)(config["from"]["name"]));
        }
Example #15
0
 public static TradingHoursCommand createTradingHoursCommand(LinkedList<string> symbols, bool prettyPrint)
 {
     JSONObject args = new JSONObject();
     JSONArray arr = new JSONArray();
     foreach (string symbol in symbols)
     {
         arr.Add(symbol);
     }
     args.Add("symbols", arr);
     return new TradingHoursCommand(args, prettyPrint);
 }
Example #16
0
        public async Task <string> BuildPublicTourXml(bool webclient)
        {
            var adminCommunityId = 596915;
            var adminId          = 184331;
            var tourDetailList   = await _communityService.GetCommunityContents(adminCommunityId, adminId);

            var tourContentList = new List <ContentInputViewModel>();

            foreach (var item in tourDetailList)
            {
                var contentInputViewModel = new ContentInputViewModel();
                contentInputViewModel.SetValuesFrom(item);
                tourContentList.Add(contentInputViewModel);
            }
            var children = await _communityService.GetChildCommunities(adminCommunityId, adminId);

            var folders = new List <CommunityViewModel>();

            foreach (var child in children)
            {
                var communityViewModel = new CommunityViewModel();
                Mapper.Map(child, communityViewModel);
                folders.Add(communityViewModel);
            }
            using (var sw = new StringWriter())
            {
                using (var xmlWriter = new XmlTextWriter(sw))
                {
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
                    xmlWriter.WriteStartElement("Folder");
                    foreach (var folder in folders)
                    {
                        var tourIds = folder.Description != null?folder.Description.Split(',') : new string[0];

                        var toursInFolder = false;
                        foreach (var tourId in tourIds)
                        {
                            try
                            {
                                var id          = Convert.ToInt32(tourId);
                                var tourDetails = tourDetailList.Find(details => details.ID == id);
                                if (tourDetails == null || tourDetails.IsDeleted)
                                {
                                    continue;
                                }
                                var tourContents = tourContentList.Find(model => model.ID == id);
                                var json         = tourDetails.Citation.Replace("json://", "");
                                var extData      = JsonConvert.DeserializeObject <dynamic>(json);
                                if (webclient && (extData.webclient == null || extData.webclient != true))
                                {
                                    continue;
                                }
                                Newtonsoft.Json.Linq.JArray related = extData.related;
                                var relatedTours = string.Empty;
                                if (webclient)
                                {
                                    foreach (Guid guid in related)
                                    {
                                        var relatedTour    = tourContentList.Find(t => t.ContentDataID == guid);
                                        var relatedJson    = relatedTour.Citation.Replace("json://", "");
                                        var relatedExtData = JsonConvert.DeserializeObject <dynamic>(relatedJson);
                                        // only include related tours that are also webclient friendly
                                        if (relatedExtData.webclient == null || relatedExtData.webclient != true)
                                        {
                                            continue;
                                        }
                                        if (relatedTours.Length > 0)
                                        {
                                            relatedTours += ";";
                                        }
                                        relatedTours += guid.ToString();
                                    }
                                }
                                else
                                {
                                    relatedTours = string.Join(";", related);
                                }
                                // write folder xml ONLY after first viable tour obj is found
                                if (!toursInFolder)
                                {
                                    xmlWriter.WriteStartElement("Folder");
                                    xmlWriter.WriteAttributeString("Name", folder.Name);
                                    xmlWriter.WriteAttributeString("Group", "Tour");
                                    xmlWriter.WriteAttributeString("Thumbnail", "");
                                    toursInFolder = true;
                                }
                                xmlWriter.WriteStartElement("Tour");
                                xmlWriter.WriteAttributeString("Title", tourDetails.Name.Replace("&", "&amp;"));
                                xmlWriter.WriteAttributeString("ID", tourContents.ContentDataID.ToString());
                                xmlWriter.WriteAttributeString("Description",
                                                               tourDetails.Description.Replace("&", "&amp;"));
                                xmlWriter.WriteAttributeString("Classification",
                                                               extData["classification"] != null ? extData["classification"].ToString() : "Other");
                                xmlWriter.WriteAttributeString("AuthorEmail",
                                                               extData.authorEmail != null ? extData.authorEmail.ToString() : "");
                                xmlWriter.WriteAttributeString("Author",
                                                               extData.author != null ? extData.author.ToString().Replace("&", "&amp;") : "");
                                xmlWriter.WriteAttributeString("AverageRating",
                                                               tourDetails.AverageRating.ToString(CultureInfo.InvariantCulture));
                                xmlWriter.WriteAttributeString("LengthInSecs", tourContents.TourLength);
                                xmlWriter.WriteAttributeString("OrganizationUrl",
                                                               extData.organizationUrl != null
                                        ? extData.organizationUrl.ToString().Replace("&", "&amp;")
                                        : "");
                                xmlWriter.WriteAttributeString("OrganizationName",
                                                               extData.organization != null
                                        ? extData.organization.ToString().Replace("&", "&amp;")
                                        : "");
                                xmlWriter.WriteAttributeString("ITHList",
                                                               extData.ithList != null
                                        ? extData.ithList.ToString()
                                        : extData.taxonomy != null ? extData.taxonomy.ToString() : "");
                                xmlWriter.WriteAttributeString("AstroObjectsList", string.Empty);
                                xmlWriter.WriteAttributeString("Keywords",
                                                               tourDetails.Tags.Replace(',', ';').Replace(" ", ""));
                                xmlWriter.WriteAttributeString("RelatedTours", relatedTours);
                                xmlWriter.WriteEndElement();
                            }
                            catch (NullReferenceException)
                            {
                                //ignore - deleted tour
                            }
                        }
                        if (toursInFolder)
                        {
                            xmlWriter.WriteEndElement();
                        }
                    }

                    xmlWriter.WriteEndElement();

                    xmlWriter.Close();
                }
                sw.Close();
                var xml            = sw.ToString();
                var storageAccount =
                    Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(
                        ConfigReader <string> .GetSetting("WWTWebBlobs"));

                var blobClient         = storageAccount.CreateCloudBlobClient();
                var cloudBlobContainer = blobClient.GetContainerReference("tours");
                var toursBlob          = cloudBlobContainer.GetBlobReferenceFromServer(webclient? "webclienttours.wtml" : "alltours.wtml");
                var bytes = new byte[xml.Length * sizeof(char)];
                Buffer.BlockCopy(xml.ToCharArray(), 0, bytes, 0, bytes.Length);
                toursBlob.UploadFromByteArray(bytes, 0, bytes.Length);
                return(toursBlob.StorageUri.PrimaryUri.AbsoluteUri);
            }
        }
Example #17
0
        public static List <MarketTick> GetMarketTicks(string marketName, int ticksNeeded, PTMagicConfiguration systemConfiguration, LogHelper log)
        {
            List <MarketTick> result = new List <MarketTick>();

            try
            {
                Int64  endTime      = (Int64)Math.Ceiling(DateTime.Now.ToUniversalTime().Subtract(Constants.Epoch).TotalMilliseconds);
                int    ticksLimit   = 500;
                string baseUrl      = "";
                int    ticksFetched = 0;

                if (ticksNeeded < ticksLimit)
                {
                    ticksLimit = ticksNeeded;
                }

                bool go = true;
                while (ticksFetched < ticksNeeded && go)
                {
                    baseUrl = "https://api.binance.com/api/v1/klines?interval=1m&symbol=" + marketName + "&endTime=" + endTime.ToString() + "&limit=" + ticksLimit.ToString();

                    log.DoLogDebug("Binance - Getting " + ticksLimit.ToString() + " ticks for '" + marketName + "'...");
                    Newtonsoft.Json.Linq.JArray jsonArray = GetSimpleJsonArrayFromURL(baseUrl, log);
                    if (jsonArray.Count > 0)
                    {
                        log.DoLogDebug("Binance - " + jsonArray.Count.ToString() + " ticks received.");

                        foreach (Newtonsoft.Json.Linq.JArray marketTick in jsonArray)
                        {
                            MarketTick tick = new MarketTick();
                            tick.Price     = (double)marketTick[4];
                            tick.Volume24h = (double)marketTick[7];
                            tick.Time      = Constants.Epoch.AddMilliseconds((Int64)marketTick[0]);

                            result.Add(tick);
                        }

                        ticksFetched = ticksFetched + jsonArray.Count;
                        endTime      = endTime - ticksLimit * 60 * 1000;
                        if (ticksNeeded - ticksFetched < ticksLimit)
                        {
                            ticksLimit = ticksNeeded - ticksFetched;
                        }
                    }
                    else
                    {
                        log.DoLogDebug("Binance - No ticks received.");
                        go = false;
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
                    {
                        using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            Dictionary <string, string> errorData = JsonConvert.DeserializeObject <Dictionary <string, string> >(reader.ReadToEnd());
                            if (errorData != null)
                            {
                                string errorMessage = "Unable to get data from Binance with URL '" + errorResponse.ResponseUri + "'!";
                                if (errorData.ContainsKey("code"))
                                {
                                    errorMessage += " - Code: " + errorData["code"];
                                }

                                if (errorData.ContainsKey("msg"))
                                {
                                    errorMessage += " - Message: " + errorData["msg"];
                                }

                                log.DoLogError(errorMessage);
                            }
                        }
                    }
                }
                result = null;
            }
            catch (Exception ex)
            {
                log.DoLogCritical(ex.Message, ex);
            }

            return(result);
        }
Example #18
0
        public string InsertBatch(Newtonsoft.Json.Linq.JArray param, string serverName)
        {
            StringBuilder result = new StringBuilder();

            result.Append("{");
            string code = "\"code\":{{\"id\":{0},\"msg\":\"{1}\"}}";

            try
            {
                if (collection != null)
                {
                    var val = collection[serverName];
                    if (val.Count > 0)
                    {
                        //"{xx:xx},{xx:xx}"
                        //Dictionary<string, string> list = new Dictionary<string, string>();
                        List <Dictionary <string, string> > list   = new List <Dictionary <string, string> >();
                        Dictionary <string, string>         kvPair = null;


                        foreach (var arry in param)
                        {
                            kvPair = new Dictionary <string, string>();
                            foreach (var o in Newtonsoft.Json.Linq.JObject.FromObject(arry))
                            {
                                foreach (Dictionary <string, string> k in val.Keys)
                                {
                                    foreach (var i in k)
                                    {
                                        if (i.Key.Trim().ToLower() == o.Key.Trim().ToLower())
                                        {
                                            kvPair.Add(i.Value.Trim(), o.Value.ToString().Trim());
                                            break;
                                        }
                                    }
                                }
                            }

                            if (kvPair.Count > 0)
                            {
                                list.Add(kvPair);
                            }
                        }

                        //替换后的sql语句
                        List <string> repSql = new List <string>();
                        foreach (var item in val)
                        {
                            foreach (var s in item.Value)
                            {
                                foreach (var i in list)
                                {
                                    string sql = s.Value;
                                    foreach (var o in i)
                                    {
                                        if (s.Value.Contains(o.Key))
                                        {
                                            sql = sql.Replace(o.Key, o.Value);
                                        }
                                    }
                                    repSql.Add(sql);
                                }
                            }
                        }

                        if (repSql.Count > 0)
                        {
                            result.Append(Database.InsertBatch(repSql));
                            result.Append(",");
                            code = string.Format(code, 1, "成功");
                        }
                    }
                }
            }
            catch (Exception er)
            {
                code = string.Format(code, 3, "数据库错误");
                //code = "\"code\":[{\"id\":3,\"msg\":\"数据库错误\"}]";
                FileLog.WriteLog(er.ToString());
            }

            result.Append(code);
            result.Append("}");
            return(result.ToString());
        }
Example #19
0
        // ***********************************************************************************************************************
        // GET TRACKRESULT
        // ***********************************************************************************************************************
        public TrackResult GetTrackResult(int id)
        {
            try
            {
                var cd = SetGetMemoryCache();

                TrackResult tr = new Models.TrackResult();
                foreach (CachedDataClass.Track.Feature f in cd.track.features)
                {
                    if (f.properties.SERIAL_NO == id.ToString())
                    {
                        tr.result.id          = id.ToString();
                        tr.result.name        = f.properties.NAME;
                        tr.result.description = f.properties.originalComments;
                        foreach (string s in f.trackFeatures)
                        {
                            if (!tr.result.features.Contains(s))
                            {
                                tr.result.features.Add(s);
                            }
                        }
                        tr.result.accessDescription = f.properties.ACCESS_DSC;


                        //get bounding box
                        double neLng = -9999999999;
                        double swLng = 9999999999;
                        double neLat = -9999999999;
                        double swLat = 9999999999;

                        bool firstpoint = false;

                        double x = 0;
                        double y = 0;
                        if (f.geometry.type == "MultiLineString")
                        {
                            foreach (List <object> g in f.geometry.coordinates)
                            {
                                foreach (object o in g)
                                {
                                    Newtonsoft.Json.Linq.JArray h = (Newtonsoft.Json.Linq.JArray)o;
                                    x = (double)h[0];
                                    y = (double)h[1];
                                    if (x > neLng)
                                    {
                                        neLng = x;
                                    }
                                    if (x < swLng)
                                    {
                                        swLng = x;
                                    }
                                    if (y > neLat)
                                    {
                                        neLat = y;
                                    }
                                    if (y < swLat)
                                    {
                                        swLat = y;
                                    }

                                    if (!firstpoint)
                                    {
                                        tr.result.startLocation           = new TrackResult.Location();
                                        tr.result.startLocation.latitude  = y;
                                        tr.result.startLocation.longitude = x;
                                        firstpoint = true;
                                    }
                                }

                                tr.result.endLocation           = new TrackResult.Location();
                                tr.result.endLocation.latitude  = y;
                                tr.result.endLocation.longitude = x;
                            }
                        }
                        if (f.geometry.type == "LineString")
                        {
                            foreach (List <object> h in f.geometry.coordinates)
                            {
                                x = (double)h[0];
                                y = (double)h[1];
                                if (x > neLng)
                                {
                                    neLng = x;
                                }
                                if (x < swLng)
                                {
                                    swLng = x;
                                }
                                if (y > neLat)
                                {
                                    neLat = y;
                                }
                                if (y < swLat)
                                {
                                    swLat = y;
                                }

                                if (!firstpoint)
                                {
                                    tr.result.startLocation           = new TrackResult.Location();
                                    tr.result.startLocation.latitude  = y;
                                    tr.result.startLocation.longitude = x;
                                    firstpoint = true;
                                }
                            }

                            tr.result.endLocation           = new TrackResult.Location();
                            tr.result.endLocation.latitude  = y;
                            tr.result.endLocation.longitude = x;
                        }
                        if (neLng != 9999999999)
                        {
                            tr.result.boundingBox.neLat = neLat;
                            tr.result.boundingBox.neLng = neLng;
                            tr.result.boundingBox.swLat = swLat;
                            tr.result.boundingBox.swLng = swLng;
                        }


                        /*
                         * foreach (List<List<double>> g in f.geometry.coordinates)
                         * {
                         *  foreach (List<double> h in g)
                         *  {
                         *      double x = h[0];
                         *      double y = h[1];
                         *      if (x > neLng) neLng = x;
                         *      if (x < swLng) swLng = x;
                         *      if (y > neLat) neLat = y;
                         *      if (y < swLat) swLat = y;
                         *
                         *      if(!firstpoint)
                         *      {
                         *          tr.result.location = new TrackResult.Location();
                         *          tr.result.location.latitude = y;
                         *          tr.result.location.longitude = x;
                         *          firstpoint = true;
                         *      }
                         *  }
                         *
                         *  if (neLng != 9999999999)
                         *  {
                         *      tr.result.boundingBox.neLat = neLat;
                         *      tr.result.boundingBox.neLng = neLng;
                         *      tr.result.boundingBox.swLat = swLat;
                         *      tr.result.boundingBox.swLng = swLng;
                         *  }
                         * }
                         */


                        //get activities
                        foreach (CachedDataClass.Track.Activity trAct in f.activities)
                        {
                            TrackResult.Activity a = new TrackResult.Activity();
                            a.activityType = trAct.activityType;
                            a.comment      = trAct.comment;
                            a.gradeComment = trAct.grade_comment;
                            //scott 20112017
                            a.grade           = trAct.grade;
                            a.distance        = trAct.distance;
                            a.duration        = trAct.duration;
                            a.durationMeasure = trAct.duration_measure;
                            tr.result.activities.Add(a);
                        }


                        tr.result.qualities.trackClass = f.qualities.track_class;
                        tr.result.qualities.quality    = f.qualities.quality;
                        tr.result.qualities.markings   = f.qualities.markings;

                        foreach (int pid in f.photos)
                        {
                            string p = getImageString(pid);
                            tr.result.images.Add(p);
                        }

                        tr.result.closure.description = f.properties.CLOS_DESC;
                        tr.result.closure.closureDate = ncdatestr(f.properties.CLOS_START);
                        tr.result.closure.openDate    = ncdatestr(f.properties.CLOS_OPEN);
                        tr.result.closure.reason      = f.properties.CLOS_REAS;
                        tr.result.closure.status      = f.properties.CLOS_STAT;

                        tr.meta.links.self = _appsettings.BaseURL + "/tracks/" + id.ToString();


                        if (tr.result.features.Count == 0)
                        {
                            tr.result.features = null;
                        }
                        if (tr.result.activities.Count == 0)
                        {
                            tr.result.activities = null;
                        }
                        if (tr.result.images.Count == 0)
                        {
                            tr.result.images = null;
                        }
                        break;
                    }
                }


                /*
                 * if(String.IsNullOrEmpty(tr.result.description))
                 * {
                 *  foreach(TrackResult.Activity a  in tr.result.activities)
                 *  {
                 *      if(a.comment != null && String.IsNullOrEmpty(a.comment.ToString()))
                 *      {
                 *          tr.result.description = a.comment.ToString();
                 *          break;
                 *      }
                 *  }
                 * }
                 */

                return(tr);
                //JsonResult jsonresult = new JsonResult(tr);
                //return jsonresult;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #20
0
        /// <summary>
        /// author:Alcedo
        /// </summary>
        /// <param name="param"></param>
        /// <param name="serverName"></param>
        /// <returns></returns>
        public string UpdatePassWord(Newtonsoft.Json.Linq.JArray param, string serverName)
        {
            StringBuilder result = new StringBuilder();

            result.Append("{");
            string code = "\"code\":{{\"id\":{0},\"msg\":\"{1}\"}}";

            try
            {
                if (collection != null)
                {
                    var val = collection[serverName];
                    if (val.Count > 0)
                    {
                        List <Dictionary <string, string> > list   = new List <Dictionary <string, string> >();
                        Dictionary <string, string>         kvPair = null;

                        foreach (var arry in param)
                        {
                            kvPair = new Dictionary <string, string>();
                            foreach (var o in Newtonsoft.Json.Linq.JObject.FromObject(arry))
                            {
                                foreach (Dictionary <string, string> k in val.Keys)
                                {
                                    foreach (var i in k)
                                    {
                                        if (i.Key.Trim().ToLower() == o.Key.Trim().ToLower())
                                        {
                                            kvPair.Add(i.Value.Trim(), o.Value.ToString().Trim());
                                            break;
                                        }
                                    }
                                }
                            }
                            if (kvPair.Count > 0)
                            {
                                list.Add(kvPair);
                            }
                        }

                        //替换后的sql语句
                        List <string> repSql = new List <string>();
                        foreach (var item in val)
                        {
                            foreach (var s in item.Value)
                            {
                                foreach (var i in list)
                                {
                                    string sql = s.Value;
                                    foreach (var o in i)
                                    {
                                        if (s.Value.Contains(o.Key))
                                        {
                                            sql = sql.Replace(o.Key, o.Value);
                                        }
                                    }
                                    repSql.Add(sql);
                                }
                            }
                        }
                        List <string> sqlArray = new List <string>();
                        if (repSql.Count > 0)
                        {
                            object obj = Database.ExecuteScalar(repSql.First());
                            if (Convert.ToInt32(obj) == 0)
                            {
                                code = string.Format(code, 2, "原密码错误");
                            }
                            else
                            {
                                foreach (var sql in repSql)
                                {
                                    if (sql.Equals(repSql.First()) == false)
                                    {
                                        sqlArray.Add(sql);
                                    }
                                }
                                Database.InsertBatch(sqlArray);
                                code = string.Format(code, 1, "成功");
                            }
                        }
                    }
                }
            }
            catch (Exception er)
            {
                code = string.Format(code, 3, "数据库错误");
                FileLog.WriteLog(er.ToString());
            }
            result.Append(code);
            result.Append("}");
            return(result.ToString());
        }
Example #21
0
        private Newtonsoft.Json.Linq.JToken parseField(OEIShared.IO.GFF.GFFField gffField)
        {
            Newtonsoft.Json.Linq.JToken j = null;

            switch (gffField.Type)
            {
                case OEIShared.IO.GFF.GFFFieldType.Byte:
                    j = gffField.ValueByte;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.CExoLocString:
                    j = gffField.ValueCExoLocString.StringRef;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.CExoString:
                    j = gffField.ValueCExoString.Value;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Char:
                    j = gffField.ValueChar;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.CResRef:
                    j = gffField.ValueCResRef.Value;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Double:
                    j = gffField.ValueDouble;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Dword:
                    j = gffField.ValueDword;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Dword64:
                    j = gffField.ValueDword64;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Float:
                    j = gffField.ValueFloat;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.GFFList:
                    //j = gffField.ValueList;
                    var a = new Newtonsoft.Json.Linq.JArray();
                    foreach (OEIShared.IO.GFF.GFFStruct gffStruct in gffField.ValueList.StructList)
                        a.Add(parseStruct(gffStruct));
                    j = a;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.GFFStruct:
                    j = parseStruct(gffField.ValueStruct);
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Int:
                    j = gffField.ValueInt;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Int64:
                    j = gffField.ValueInt64;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Short:
                    j = gffField.ValueShort;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.VoidData:
                    j = gffField.ValueVoidData;
                    break;
                case OEIShared.IO.GFF.GFFFieldType.Word:
                    j = gffField.ValueWord;
                    break;
            }

            return j;
        }
Example #22
0
        public override void PerformDBAction()
        {
            ValueExpression VE = new ValueExpression(Db.ProjEnvironment, Db.BusinessFlow, Db.DSList);

            VE.Value = Act.SQL;
            string SQLCalculated  = VE.ValueCalculated;
            string collectionName = "";

            if (Action == Actions.ActDBValidation.eDBValidationType.SimpleSQLOneValue)
            {
                collectionName = Act.Table;
            }
            else
            {
                collectionName = GetCollectionName(SQLCalculated);
            }
            var DB         = mMongoClient.GetDatabase(DbName);
            var collection = DB.GetCollection <BsonDocument>(collectionName);

            try
            {
                switch (Action)
                {
                case Actions.ActDBValidation.eDBValidationType.FreeSQL:

                    if (SQLCalculated.Contains("insertMany"))
                    {
                        string queryParam = GetUpdateQueryParams(SQLCalculated).ToString();
                        Newtonsoft.Json.Linq.JArray jsonArray = Newtonsoft.Json.Linq.JArray.Parse(queryParam);
                        List <BsonDocument>         documents = new List <BsonDocument>();
                        foreach (Newtonsoft.Json.Linq.JObject obj in jsonArray.Children <Newtonsoft.Json.Linq.JObject>())
                        {
                            BsonDocument document = BsonDocument.Parse(obj.ToString());
                            documents.Add(document);
                        }
                        collection.InsertMany(documents);
                    }
                    else if (SQLCalculated.Contains("insertOne") || SQLCalculated.Contains("insert"))
                    {
                        BsonDocument insertDocumnet = BsonDocument.Parse(GetUpdateQueryParams(SQLCalculated));
                        collection.InsertOne(insertDocumnet);
                    }
                    else
                    {
                        var result = collection.Find(GetQueryParamater(SQLCalculated, "find")).
                                     Project(GetQueryParamater(SQLCalculated, "project")).
                                     Sort(BsonDocument.Parse(GetQueryParamater(SQLCalculated, "sort"))).
                                     Limit(Convert.ToInt32(GetQueryParamater(SQLCalculated, "limit"))).
                                     ToList();

                        AddValuesFromResult(result);
                    }
                    break;

                case Actions.ActDBValidation.eDBValidationType.RecordCount:
                    var count = collection.Count(new BsonDocument());
                    Act.AddOrUpdateReturnParamActual("Record Count", count.ToString());
                    break;

                case Actions.ActDBValidation.eDBValidationType.UpdateDB:

                    //do commit
                    if (Act.CommitDB_Value == true)
                    {
                        var session = mMongoClient.StartSession();
                        session.StartTransaction();
                        UpdateCollection(SQLCalculated, collection);
                        session.CommitTransaction();
                    }
                    else
                    {
                        UpdateCollection(SQLCalculated, collection);
                    }
                    break;

                case Actions.ActDBValidation.eDBValidationType.SimpleSQLOneValue:
                    string col = Act.Column;
                    string where = Act.Where;
                    string filter    = "";
                    var    isNumeric = double.TryParse(where, out double n);

                    //Simply matches on specific column type int
                    //For ex where contains any int value
                    if (isNumeric)
                    {
                        filter = "{" + col + ":" + where + "}";
                    }
                    else
                    {
                        //Equality matches on the whole embedded document require an exact match of the specified <value> document, including the field order
                        //For ex where contains value = {field1:_value1,field2:_value2,field3:"_value3",...}
                        if (where.Contains(","))
                        {
                            filter = "{" + col + ":" + where + "}";
                        }
                        //Simply matches on specific column
                        //For ex where contains any string value
                        else
                        {
                            filter = "{" + col + ":\"" + where + "\"}";
                        }
                    }

                    var resultSimpleSQLOne = collection.Find(filter).Project(Builders <BsonDocument> .Projection.Exclude("_id")).ToList();

                    AddValuesFromResult(resultSimpleSQLOne);
                    break;

                default:
                    Act.Error += "Operation Type " + Action + " is not yes supported for Mongo DB";
                    break;
                }
            }
            catch (Exception e)
            {
                Act.Error = "Failed to execute. Error :" + e.Message;
                Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {e.Message}", e);
            }
            if (!Db.KeepConnectionOpen)
            {
                Disconnect();
            }
        }
Example #23
0
        public string[] getTouristAttraction(string latitude, string longitude)
        {
            string    baseurl  = "https://api.foursquare.com/v2/venues/explore?client_id=UVUDLYG1NY1SU1HT52FE13H0N3VMOPVKOK52BP4Z1VJ1540K&client_secret=Z3YHCONZOHQ5G3DVGKDOXIQ3CWAVPOU5S2KIQVY54F4FZPQK&v=20141018&limit=10&ll=";
            string    location = latitude + "," + longitude;
            string    finalURL = baseurl + location + "&section=sights";
            WebClient wc       = new WebClient();

            try
            {
                string  jsonStr        = wc.DownloadString(finalURL);
                dynamic nearestResults = JsonConvert.DeserializeObject(jsonStr);
                Newtonsoft.Json.Linq.JArray itemresults = nearestResults.response.groups[0].items;

                if (itemresults != null)
                {
                    int      numResults = itemresults.Count;
                    string[] result     = new string[numResults];
                    for (int i = 0; i < numResults; i++)
                    {
                        if (nearestResults.response.groups[0].items[i].venue.name != null)
                        {
                            string   name  = nearestResults.response.groups[0].items[i].venue.name;
                            string[] names = name.Split('|');
                            name      = names[0];
                            result[i] = result[i] + name + "|";
                        }
                        if (nearestResults.response.groups[0].items[i].venue.location.formattedAddress != null)
                        {
                            Newtonsoft.Json.Linq.JArray address = nearestResults.response.groups[0].items[i].venue.location.formattedAddress;
                            int    lenaddr  = address.Count;
                            string vaddress = "";
                            for (int j = 0; j < lenaddr; j++)
                            {
                                vaddress = vaddress + address[j].ToString() + " ";
                            }
                            result[i] = result[i] + vaddress + "|";
                        }
                        if (nearestResults.response.groups[0].items[i].venue.categories[0].name != null)
                        {
                            string categories = nearestResults.response.groups[0].items[i].venue.categories[0].name;
                            result[i] = result[i] + categories + "|";
                        }
                        if (nearestResults.response.groups[0].items[i].venue.rating != null)
                        {
                            string rating = nearestResults.response.groups[0].items[i].venue.rating;
                            result[i] = result[i] + rating;
                        }
                    }
                    return(result);
                }
                else
                {
                    string[] r = new string[1];
                    r[0] = "error";
                    return(r);
                }
            }
            catch (Exception e)
            {
                string[] r = new string[1];
                r[0] = "error";
                return(r);
            }
        }
Example #24
0
        private static void MergeJsonObjects(Newtonsoft.Json.Linq.JObject self, Newtonsoft.Json.Linq.JObject other)
        {
            foreach(var p in other.Properties())
            {
                var sp = self.Property(p.Name);
                if (sp == null)
                    self.Add(p);
                else
                {
                    switch (p.Type)
                    {
                        // Primitives override
                        case Newtonsoft.Json.Linq.JTokenType.Boolean:
                        case Newtonsoft.Json.Linq.JTokenType.Bytes:
                        case Newtonsoft.Json.Linq.JTokenType.Comment:
                        case Newtonsoft.Json.Linq.JTokenType.Constructor:
                        case Newtonsoft.Json.Linq.JTokenType.Date:
                        case Newtonsoft.Json.Linq.JTokenType.Float:
                        case Newtonsoft.Json.Linq.JTokenType.Guid:
                        case Newtonsoft.Json.Linq.JTokenType.Integer:
                        case Newtonsoft.Json.Linq.JTokenType.String:
                        case Newtonsoft.Json.Linq.JTokenType.TimeSpan:
                        case Newtonsoft.Json.Linq.JTokenType.Uri:
                        case Newtonsoft.Json.Linq.JTokenType.None:
                        case Newtonsoft.Json.Linq.JTokenType.Null:
                        case Newtonsoft.Json.Linq.JTokenType.Undefined:
                            self.Replace(p);
                            break;

                            // Arrays merge
                        case Newtonsoft.Json.Linq.JTokenType.Array:
                            if (sp.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                                sp.Value = new Newtonsoft.Json.Linq.JArray(((Newtonsoft.Json.Linq.JArray)sp.Value).Union((Newtonsoft.Json.Linq.JArray)p.Value));
                            else
                            {
                                var a = new Newtonsoft.Json.Linq.JArray(sp.Value);
                                sp.Value = new Newtonsoft.Json.Linq.JArray(a.Union((Newtonsoft.Json.Linq.JArray)p.Value));
                            }

                            break;

                            // Objects merge
                        case Newtonsoft.Json.Linq.JTokenType.Object:
                            if (sp.Type == Newtonsoft.Json.Linq.JTokenType.Object)
                                MergeJsonObjects((Newtonsoft.Json.Linq.JObject)sp.Value, (Newtonsoft.Json.Linq.JObject)p.Value);
                            else
                                sp.Value = p.Value;
                            break;

                            // Ignore other stuff
                        default:
                            break;
                    }
                }
            }
        }
Example #25
0
        private void Form1_Load(object sender, EventArgs e)
        {
            DataColumn dcSno            = new DataColumn("Sno");
            DataColumn dcstart_time     = new DataColumn("start_time");
            DataColumn dcsell_price     = new DataColumn("sell_price");
            DataColumn dcduration       = new DataColumn("duration");
            DataColumn dcdisplay_name   = new DataColumn("employee_name");
            DataColumn dcservice_name   = new DataColumn("service_name");
            DataColumn dcscheduled_date = new DataColumn("scheduled_date");

            dtData.Columns.Add(dcstart_time);
            dtData.Columns.Add(dcsell_price);
            dtData.Columns.Add(dcduration);
            dtData.Columns.Add(dcdisplay_name);
            dtData.Columns.Add(dcservice_name);
            dtData.Columns.Add(dcscheduled_date);
            string Path    = AppDomain.CurrentDomain.BaseDirectory;
            string Section = string.Empty;

            webBrowser1 = new WebBrowser();
            webBrowser1.ObjectForScripting = new ScriptManager(this);
            this.webBrowser1.Navigate(Path + "HTMLPage1.html");
            int sno = 1;

            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            object result = this.webBrowser1.Document.InvokeScript("timestamp");

            object result1 = this.webBrowser1.Document.InvokeScript("getnonce");

            object resul2 = this.webBrowser1.Document.InvokeScript("signature");

            List <Newtonsoft.Json.Linq.JToken> lstValServices  = new List <Newtonsoft.Json.Linq.JToken>();
            List <Newtonsoft.Json.Linq.JToken> lstHrefServices = new List <Newtonsoft.Json.Linq.JToken>();

            Newtonsoft.Json.Linq.JArray lstServices = new Newtonsoft.Json.Linq.JArray();
            PostDataIRCTC.PostData.FetchAllServices(@"https://pos.shortcutssoftware.com/webapi/site/7966d291-1b12-dd11-a234-0050563fff01/services?limit=5000&is_active=true&fields=display%2Cdescription%2Cprice%2Clinks%2Cdefault_duration_minutes%2Cbreak_duration_minutes&is_customer_bookable=true", TimeStamp, Nonce, signatureVal, ref lstValServices, ref lstHrefServices, ref lstServices);
            foreach (Newtonsoft.Json.Linq.JObject objService in lstServices)
            {
                foreach (System.Collections.Generic.KeyValuePair <string, Newtonsoft.Json.Linq.JToken> keyVal in objService)
                {
                    if (keyVal.Key == "href")
                    {
                        webBrowser1.ObjectForScripting = new ScriptManager(this);
                        this.webBrowser1.Navigate(Path + "HTMLPage1.html");
                        while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                        {
                            Application.DoEvents();
                        }

                        this.webBrowser1.Document.InvokeScript("timestamp");

                        this.webBrowser1.Document.InvokeScript("getnonce");

                        this.webBrowser1.Document.InvokeScript("signatureEmployeePricing", new object[] { keyVal.Value + "/employee_pricing" });
                        lstServices = new Newtonsoft.Json.Linq.JArray();
                        PostDataIRCTC.PostData.FetchAllEmployeePricing(keyVal.Value + "/employee_pricing", TimeStamp, Nonce, signatureVal, ref lstValServices, ref lstHrefServices, ref lstServices);
                        foreach (Newtonsoft.Json.Linq.JObject objEmployee in lstServices)
                        {
                            foreach (System.Collections.Generic.KeyValuePair <string, Newtonsoft.Json.Linq.JToken> keyValEmployee in objEmployee)
                            {
                                if (keyValEmployee.Key == "href")
                                {
                                    PostDataIRCTC.PostData.FetchAvailableSlots("https://www.ulta.com/bookonline/availableTimes.html");
                                    webBrowser1.ObjectForScripting = new ScriptManager(this);
                                    this.webBrowser1.Navigate(Path + "HTMLPage1.html");
                                    while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                                    {
                                        Application.DoEvents();
                                    }

                                    this.webBrowser1.Document.InvokeScript("timestamp");
                                    this.webBrowser1.Document.InvokeScript("getnonce");
                                    this.webBrowser1.Document.InvokeScript("signatureEmployeePricingCalculate", new object[] { "https://pos.shortcutssoftware.com/webapi/site/7966d291-1b12-dd11-a234-0050563fff01/calculate_available_appointments" });
                                    lstServices = new Newtonsoft.Json.Linq.JArray();
                                    ReturnValue = PostDataIRCTC.PostData.FetchAllEmployeeAppointments("https://pos.shortcutssoftware.com/webapi/site/7966d291-1b12-dd11-a234-0050563fff01/calculate_available_appointments", TimeStamp, Nonce, signatureVal, ref lstValServices, ref lstHrefServices, ref lstServices, keyVal.Value + "/employee_pricing");
                                    if (ReturnValue != "true")
                                    {
                                        label1.Text = ReturnValue;
                                        break;
                                    }
                                    foreach (Newtonsoft.Json.Linq.JObject objEmployeeEmployment in lstServices)
                                    {
                                        Newtonsoft.Json.Linq.JToken keyValEmployeeApp = objEmployeeEmployment as Newtonsoft.Json.Linq.JToken;
                                        //foreach (System.Collections.Generic.KeyValuePair<string, Newtonsoft.Json.Linq.JToken> keyValEmployeeApp in objEmployeeEmployment)
                                        //{
                                        string objDate = ((Newtonsoft.Json.Linq.JValue)(objEmployeeEmployment["scheduled_date"])).Value.ToString();
                                        if (objDate == "2016-10-29")
                                        {
                                            //if (keyValEmployeeApp.Key == "services")
                                            //{
                                            //    Newtonsoft.Json.Linq.JArray objArray = Newtonsoft.Json.Linq.JArray.Parse(keyValEmployeeApp.Value.ToString());
                                            //    foreach (Newtonsoft.Json.Linq.JToken EmployeeToken in objArray)
                                            //    {
                                            //        Newtonsoft.Json.Linq.JObject detailskeyValEmployeeAppObj = EmployeeToken as Newtonsoft.Json.Linq.JObject;


                                            Newtonsoft.Json.Linq.JArray objArray = objEmployeeEmployment["services"] as Newtonsoft.Json.Linq.JArray;
                                            foreach (Newtonsoft.Json.Linq.JToken EmployeeToken in objArray)
                                            {
                                                DataRow dr = dtData.NewRow();
                                                Newtonsoft.Json.Linq.JObject detailskeyValEmployeeAppObj = EmployeeToken as Newtonsoft.Json.Linq.JObject;
                                                if (((Newtonsoft.Json.Linq.JValue)(EmployeeToken["start_time"])).Value.ToString() == "10:00:00")
                                                {
                                                }
                                                dr["start_time"] = ((Newtonsoft.Json.Linq.JValue)(EmployeeToken["start_time"])).Value;
                                                if (EmployeeToken["sell_price"] != null)
                                                {
                                                    dr["sell_price"] = ((Newtonsoft.Json.Linq.JValue)(EmployeeToken["sell_price"])).Value;
                                                }
                                                dr["duration"] = ((Newtonsoft.Json.Linq.JValue)(EmployeeToken["duration"])).Value;
                                                Newtonsoft.Json.Linq.JArray detailskeyValEmployeeLinkObj = ((Newtonsoft.Json.Linq.JArray)(EmployeeToken["links"]));
                                                int count = 1;
                                                foreach (Newtonsoft.Json.Linq.JObject objEmployeeEmploymentLink in detailskeyValEmployeeLinkObj)
                                                {
                                                    if (count == 1)
                                                    {
                                                        foreach (System.Collections.Generic.KeyValuePair <string, Newtonsoft.Json.Linq.JToken> keyValEmployeeLink in objEmployeeEmploymentLink)
                                                        {
                                                            if (keyValEmployeeLink.Key == "display_name")
                                                            {
                                                                dr["service_name"] = ((Newtonsoft.Json.Linq.JValue)(keyValEmployeeLink.Value)).Value;
                                                            }
                                                        }
                                                    }
                                                    if (count == 2)
                                                    {
                                                        foreach (System.Collections.Generic.KeyValuePair <string, Newtonsoft.Json.Linq.JToken> keyValEmployeeLink in objEmployeeEmploymentLink)
                                                        {
                                                            if (keyValEmployeeLink.Key == "display_name")
                                                            {
                                                                dr["employee_name"] = ((Newtonsoft.Json.Linq.JValue)(keyValEmployeeLink.Value)).Value;
                                                            }
                                                        }
                                                    }
                                                    count++;
                                                }
                                                dr["scheduled_date"] = objDate;
                                                sno++;
                                                dtData.Rows.Add(dr);
                                            }
                                        }

                                        //}
                                        //}
                                    }
                                }
                            }
                            if (ReturnValue != "true")
                            {
                                break;
                            }
                        }
                        if (ReturnValue != "true")
                        {
                            break;
                        }
                    }
                    if (ReturnValue != "true")
                    {
                        break;
                    }
                }
                dtData = dtData.DefaultView.ToTable(true, "start_time", "service_name", "employee_name", "duration", "sell_price", "scheduled_date");

                backgroundWorker1.RunWorkerAsync(0);
            }
        }
        public async Task MoreIntent(IDialogContext context, LuisResult result)
        {
            int BillNumber = Continuity.GetSavedBillNumber(context);

            if (BillNumber < 0)
            {
                // none left
                await context.PostAsync("Not anymore bills to show.");

                context.Wait(MessageReceived);
                return;
            }
            string CurVoter = Continuity.GetSavedLegislator(context);

            Newtonsoft.Json.Linq.JArray arr = Continuity.GetSavedBills(context);
            string State = Continuity.GetSavedState(context);

            if (arr == null)
            {
                await context.PostAsync("No bills saved to show.");

                context.Wait(MessageReceived);
                return;
            }
            int NumLeft = arr.Count;

            if (BillNumber >= NumLeft)
            {
                // none left
                await context.PostAsync("No more bills to show.");

                context.Wait(MessageReceived);
                return;
            }
            int NumToShow = NumLeft;

            if (NumToShow > Continuity.NumBillsToShowInGroup)
            {
                NumToShow = Continuity.NumBillsToShowInGroup;
            }


            for (int i = BillNumber; i < BillNumber + NumToShow; i++)
            {
                if (arr != null && i < arr.Count)
                {
                    await BillDialogUtil.DisplayOneBill(context, arr[i], State, CurVoter);
                }
            }

            BillNumber += NumToShow;
            if (BillNumber < arr.Count)
            {
                Continuity.SetSavedBillNumber(context, BillNumber);
                await context.PostAsync("Type 'More' to see more bills.\n");
            }
            else
            {
                Continuity.SetSavedBills(context, null);
                Continuity.SetSavedBillNumber(context, -1);
            }
        }
        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="obj">异步的socket对象</param>
        protected override void ThreadPoolLogin(object obj)
        {
            if (obj is Socket socket)
            {
                OperateResult result = new OperateResult( );
                // 获取ip地址
                string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( );

                // 接收操作信息
                OperateResult infoResult = ReceiveInformationHead(
                    socket,
                    out int customer,
                    out string fileName,
                    out string Factory,
                    out string Group,
                    out string Identify);

                if (!infoResult.IsSuccess)
                {
                    Console.WriteLine(infoResult.ToMessageShowString( ));
                    return;
                }

                string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName);

                // 操作分流

                if (customer == HslProtocol.ProtocolFileDownload)
                {
                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                    // 发送文件数据
                    OperateResult sendFile = SendFileAndCheckReceive(socket, fullFileName, fileName, "", "");
                    if (!sendFile.IsSuccess)
                    {
                        LogNet?.WriteError(ToString( ), $"{StringResources.Language.FileDownloadFailed}:{relativeName} ip:{IpAddress} reason:{sendFile.Message}");
                        return;
                    }
                    else
                    {
                        socket?.Close( );
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDownloadSuccess + ":" + relativeName);
                    }
                }
                else if (customer == HslProtocol.ProtocolFileUpload)
                {
                    string tempFileName = FilesDirectoryPathTemp + "\\" + CreateRandomFileName( );

                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                    // 上传文件
                    CheckFolderAndCreate( );

                    // 创建新的文件夹
                    try
                    {
                        FileInfo info = new FileInfo(fullFileName);
                        if (!Directory.Exists(info.DirectoryName))
                        {
                            Directory.CreateDirectory(info.DirectoryName);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogNet?.WriteException(ToString( ), StringResources.Language.FilePathCreateFailed + fullFileName, ex);
                        socket?.Close( );
                        return;
                    }

                    OperateResult receiveFile = ReceiveFileFromSocketAndMoveFile(
                        socket,                                 // 网络套接字
                        tempFileName,                           // 临时保存文件路径
                        fullFileName,                           // 最终保存文件路径
                        out string FileName,                    // 文件名称,从客户端上传到服务器时,为上传人
                        out long FileSize,
                        out string FileTag,
                        out string FileUpload
                        );

                    if (receiveFile.IsSuccess)
                    {
                        socket?.Close( );
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadSuccess + ":" + relativeName);
                    }
                    else
                    {
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadFailed + ":" + relativeName + " " + StringResources.Language.TextDescription + receiveFile.Message);
                    }
                }
                else if (customer == HslProtocol.ProtocolFileDelete)
                {
                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                    bool deleteResult = DeleteFileByName(fullFileName);

                    // 回发消息
                    if (SendStringAndCheckReceive(
                            socket,                                                            // 网络套接字
                            deleteResult ? 1 : 0,                                              // 是否移动成功
                            deleteResult ? StringResources.Language.FileDeleteSuccess : StringResources.Language.FileDeleteFailed
                            ).IsSuccess)
                    {
                        socket?.Close( );
                    }

                    if (deleteResult)
                    {
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDeleteSuccess + ":" + relativeName);
                    }
                }
                else if (customer == HslProtocol.ProtocolFileDirectoryFiles)
                {
                    List <GroupFileItem> fileNames = new List <GroupFileItem>( );
                    foreach (var m in GetDirectoryFiles(Factory, Group, Identify))
                    {
                        FileInfo fileInfo = new FileInfo(m);
                        fileNames.Add(new GroupFileItem( )
                        {
                            FileName = fileInfo.Name,
                            FileSize = fileInfo.Length,
                        });
                    }

                    Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(fileNames.ToArray( ));
                    if (SendStringAndCheckReceive(
                            socket,
                            HslProtocol.ProtocolFileDirectoryFiles,
                            jArray.ToString( )).IsSuccess)
                    {
                        socket?.Close( );
                    }
                }
                else if (customer == HslProtocol.ProtocolFileDirectories)
                {
                    List <string> folders = new List <string>( );
                    foreach (var m in GetDirectories(Factory, Group, Identify))
                    {
                        DirectoryInfo directory = new DirectoryInfo(m);
                        folders.Add(directory.Name);
                    }

                    Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( ));
                    if (SendStringAndCheckReceive(
                            socket,
                            HslProtocol.ProtocolFileDirectoryFiles,
                            jArray.ToString( )).IsSuccess)
                    {
                        socket?.Close( );
                    }
                }
                else
                {
                    socket?.Close( );
                }
            }
        }
        public async Task FindIntent(IDialogContext context, LuisResult result)
        {
            try
            {
                string CurState;
                CurState = Continuity.GetSavedState(context);
                string SearchTerm = BillDialogUtil.GetSearchTerm(result);

                string CurVoter;
                CurVoter = Continuity.GetSavedLegislator(context);

                DateTime MinTime;
                DateTime MaxTime;
                bool     Ok = BillDialogUtil.GetEntityDateRange(result, out MinTime, out MaxTime);
                // if (Ok)
                {
                    // await context.PostAsync($"SearchTerm = {SearchTerm} MinTime = {MinTime}, MaxTime = {MaxTime}");
                    // // context.Wait(MessageReceived);

                    OpenStateClientLib.OpenStateClient cli = new OpenStateClientLib.OpenStateClient();

                    Newtonsoft.Json.Linq.JArray arr = await cli.GetBillsFilteredAsync(CurState, MinTime, MaxTime, SearchTerm, null, ExtraGuiActionBill);

                    int CurrentBill = 0;

                    bool WillBeMore;
                    int  MaxToShow = Continuity.NumBillsToShowInGroup;
                    if (MaxToShow >= arr.Count)
                    {
                        MaxToShow  = arr.Count;
                        WillBeMore = false;
                    }
                    else
                    {
                        WillBeMore = true;
                    }

                    bool MoreToDisplay = false;
                    for (int ii = 0; ii < MaxToShow; ii++)
                    {
                        CurrentBill   = ii;
                        MoreToDisplay = (ii >= (arr.Count - 1));
                        await BillDialogUtil.DisplayOneBill(context, arr[ii], CurState, CurVoter);
                    }
                    if (MoreToDisplay)
                    {
                        await context.PostAsync("Type 'More' to see more bills.\n");
                    }
                    // context.ConversationData.SetValue(KeyBillNumber, CurrentBill + 1);
                    Continuity.SetSavedBillNumber(context, CurrentBill + 1);
                    if (WillBeMore)
                    {
                        // context.ConversationData.SetValue(KeyBillResults, arr);
                        Continuity.SetSavedBills(context, arr);
                        if (SearchTerm != null && SearchTerm != "")
                        {
                            await context.PostAsync($"Type 'More' to see more '{SearchTerm}' bills.\n");
                        }
                        else
                        {
                            await context.PostAsync("Type 'More' to see more bills.\n");
                        }
                    }
                    else
                    {
                        Continuity.RemoveSavedBills(context);
                    }
                }
                context.Wait(MessageReceived);
            }
            catch (System.Exception)
            {
            }
        }
 protected virtual Catel.Runtime.Serialization.ISerializationContext <Catel.Runtime.Serialization.Json.JsonSerializationContextInfo> GetSerializationContextInfo(object model, System.Type modelType, Newtonsoft.Json.JsonReader jsonReader, Newtonsoft.Json.JsonWriter jsonWriter, Catel.Runtime.Serialization.SerializationContextMode contextMode, System.Collections.Generic.Dictionary <string, Newtonsoft.Json.Linq.JProperty> jsonProperties, Newtonsoft.Json.Linq.JArray jsonArray, Catel.Runtime.Serialization.ISerializationConfiguration configuration)
 {
 }
Example #30
0
        private void readJson(int month) /* 读取动画详细信息json */
        {
            Newtonsoft.Json.Linq.JArray jsonList1;
            string url = "";
            int t_month = month >= 10 ? 10 : month >= 7 ? 7 : month >= 4 ? 4 : month >= 1 ? 1 : 1;
            int t_year = comboBox3.SelectedIndex == -1 ? year : Int32.Parse(comboBox3.Items[comboBox3.SelectedIndex].ToString());
            foreach (archive a in archiveList)
            {
                if (a.year == t_year + "")
                {
                    foreach (months m in a.months)
                    {
                        if (m.month == t_month + "")
                        {
                            url = bgmlist + m.json;
                        }
                    }
                }
            }
            int adasd = "http://bgmlist.com/json/".Length;
            jsonName = url.Substring(adasd, url.Length - adasd);

            /* **   本地json没有创建的话 */
            if (System.IO.File.Exists(Path.Combine(appdataFAPI, @jsonName)))
            {
                readLocalJson(Path.Combine(appdataFAPI, @jsonName));
            }
            else
            {
                try
                {
                    var pt = ProxyDetails.ProxyType;
                    ProxyDetails.ProxyType = (ProxyType)System.Enum.Parse(typeof(ProxyType), "None");

                    MyWebClient webClient = new MyWebClient();
                    byte[] b = webClient.DownloadData(url);
                    string jsonText = Encoding.UTF8.GetString(b, 0, b.Length);
                    Newtonsoft.Json.Linq.JObject aaaa = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(jsonText);
                    jsonList1=new Newtonsoft.Json.Linq.JArray();
                    foreach (var item in aaaa)
                    {
                        jsonList1.Add(item.Value);
                        //Console.WriteLine(item.Key + item.Value);
                    }
                    //jsonList1 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(jsonText);
                    foreach (Newtonsoft.Json.Linq.JObject a in jsonList1)
                    {
                        a.Add("isOrderRabbit", "0");                                          /* 是否订阅 */
                        a.Add("episode", "01");                                               /* 集数 默认01 */
                        a.Add("searchKeyword", a["titleCN"].ToString().Replace("-", " "));  /* 搜索用关键字 默认用json提供的 */
                        a.Add("fansub", " ");                                                 /* 字幕组 */
                        a.Add("longepisode", "0");                                            /* 长期连载 */
                        a.Add("lastDate", "");                                                /* 上一次完成时间 */
                    }
                    useDmhyKeyword(jsonList1);
                    writeLocalJson(jsonList1, jsonName);
                    readLocalJson(Path.Combine(appdataFAPI, @jsonName));
                    checkBox1.Checked = false;

                    ProxyDetails.ProxyType = pt;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            dataGridView1.DataSource = (from a in jsonList
                                        where Convert.ToInt32(a.weekDayCN) == day
                                        select a).ToList(); ;
        }
Example #31
0
        public void CutWoBySNId(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JToken Data, MESStationReturn StationReturn)
        {
            OleExec sfcdb = null;

            try
            {
                string wo        = Data["WO"].ToString().ToUpper().Trim();
                string closeFlag = Data["CLOSEFLAG"].ToString().ToUpper().Trim();
                Newtonsoft.Json.Linq.JArray arrayId = (Newtonsoft.Json.Linq.JArray)Data["ID"];

                sfcdb = this.DBPools["SFCDB"].Borrow();
                sfcdb.ThrowSqlExeception = true;
                T_R_WO_BASE t_r_wo_base = new T_R_WO_BASE(sfcdb, DBTYPE);
                R_WO_BASE   r_wo_base   = t_r_wo_base.GetWoByWoNo(wo, sfcdb);
                if (r_wo_base == null)
                {
                    throw new Exception(MESReturnMessage.GetMESReturnMessage("MES00000164", new string[] { wo }));
                }

                T_R_SN   t_r_sn = new T_R_SN(sfcdb, DBTYPE);
                Row_R_SN rowSN;
                for (int i = 0; i < arrayId.Count; i++)
                {
                    rowSN             = (Row_R_SN)t_r_sn.GetObjByID(arrayId[i].ToString(), sfcdb);
                    rowSN.SN          = "CUT_" + rowSN.SN;
                    rowSN.WORKORDERNO = "CUT_" + rowSN.WORKORDERNO;
                    rowSN.SKUNO       = "CUT_" + rowSN.SKUNO;
                    rowSN.EDIT_EMP    = LoginUser.EMP_NO;
                    rowSN.EDIT_TIME   = GetDBDateTime();
                    sfcdb.ExecSQL(rowSN.GetUpdateString(DBTYPE));
                }

                Row_R_WO_BASE rowWoBase = (Row_R_WO_BASE)t_r_wo_base.GetObjByID(r_wo_base.ID, sfcdb);
                rowWoBase.WORKORDER_QTY = r_wo_base.WORKORDER_QTY - Convert.ToDouble(arrayId.Count);
                rowWoBase.INPUT_QTY     = r_wo_base.INPUT_QTY - Convert.ToDouble(arrayId.Count);
                rowWoBase.EDIT_EMP      = LoginUser.EMP_NO;
                rowWoBase.EDIT_TIME     = GetDBDateTime();
                if (closeFlag == "1")
                {
                    rowWoBase.CLOSED_FLAG = closeFlag;
                    rowWoBase.CLOSE_DATE  = GetDBDateTime();
                }
                sfcdb.ExecSQL(rowWoBase.GetUpdateString(DBTYPE));

                this.DBPools["SFCDB"].Return(sfcdb);
                StationReturn.Data        = r_wo_base;
                StationReturn.Status      = StationReturnStatusValue.Pass;
                StationReturn.MessageCode = "MES00000210";
                StationReturn.MessagePara.Add(wo);
                StationReturn.MessagePara.Add(arrayId.Count);
            }
            catch (Exception exception)
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000037";
                StationReturn.MessagePara.Add(exception.Message);
                StationReturn.Data = exception.Message;
                if (sfcdb != null)
                {
                    this.DBPools["SFCDB"].Return(sfcdb);
                }
            }
        }
Example #32
0
        public void GetSearchData(object parameters)
        {
            #region Facebook
            try
            {
                Array arrayParams = (Array)parameters;

                DiscoverySearch           dissearch       = (DiscoverySearch)arrayParams.GetValue(0);
                DiscoverySearchRepository dissearchrepo   = (DiscoverySearchRepository)arrayParams.GetValue(1);
                DiscoverySearch           discoverySearch = (DiscoverySearch)arrayParams.GetValue(2);


                #region FacebookSearch

                string accesstoken = string.Empty;

                FacebookAccountRepository fbAccRepo = new FacebookAccountRepository();
                //ArrayList asltFbAccount = fbAccRepo.getAllFacebookAccounts();
                ArrayList asltFbAccount = fbAccRepo.getAllFacebookAccountsOfUser(discoverySearch.UserId);

                foreach (FacebookAccount item in asltFbAccount)
                {
                    accesstoken = item.AccessToken;
                    if (FacebookHelper.CheckFacebookToken(accesstoken, discoverySearch.SearchKeyword))
                    {
                        break;
                    }
                }

                string facebookSearchUrl = "https://graph.facebook.com/search?q=" + discoverySearch.SearchKeyword + " &type=post&access_token=" + accesstoken;
                var    facerequest       = (HttpWebRequest)WebRequest.Create(facebookSearchUrl);
                facerequest.Method = "GET";
                string outputface = string.Empty;
                using (var response = facerequest.GetResponse())
                {
                    using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1252)))
                    {
                        outputface = stream.ReadToEnd();
                    }
                }
                if (!outputface.StartsWith("["))
                {
                    outputface = "[" + outputface + "]";
                }


                Newtonsoft.Json.Linq.JArray facebookSearchResult = Newtonsoft.Json.Linq.JArray.Parse(outputface);

                foreach (var item in facebookSearchResult)
                {
                    var data = item["data"];

                    foreach (var chile in data)
                    {
                        try
                        {
                            dissearch.CreatedTime = DateTime.Parse(chile["created_time"].ToString());

                            dissearch.EntryDate = DateTime.Now;

                            dissearch.FromId = chile["from"]["id"].ToString();

                            dissearch.FromName = chile["from"]["name"].ToString();

                            try
                            {
                                dissearch.ProfileImageUrl = "http://graph.facebook.com/" + chile["from"]["id"] + "/picture?type=small";
                            }
                            catch { }

                            dissearch.SearchKeyword = discoverySearch.SearchKeyword;

                            dissearch.Network = "facebook";

                            try
                            {
                                dissearch.Message = chile["message"].ToString();
                            }
                            catch { }
                            try
                            {
                                dissearch.Message = chile["story"].ToString();
                            }
                            catch { }

                            dissearch.MessageId = chile["id"].ToString();

                            dissearch.Id = Guid.NewGuid();

                            dissearch.UserId = discoverySearch.UserId;

                            if (!dissearchrepo.isKeywordPresent(dissearch.SearchKeyword, dissearch.MessageId))
                            {
                                dissearchrepo.addNewSearchResult(dissearch);
                            }
                        }
                        catch (Exception ex)
                        {
                            //logger.Error(ex.StackTrace);
                            Console.WriteLine(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //logger.Error(ex.StackTrace);
                Console.WriteLine(ex.StackTrace);
            }
            #endregion

            #endregion
        }
        string HandlePostHelper(Newtonsoft.Json.Linq.JArray ja, Dictionary <string, string> returnModifiers)
        {
            int tokenCount = ja == null ? 0 : ja.Count;

            if (_methods != null)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new ArchivableDictionaryResolver());
                int methodIndex = -1;
                foreach (var method in _methods)
                {
                    methodIndex++;
                    int paramCount = method.GetParameters().Length;
                    if (!method.IsStatic)
                    {
                        paramCount++;
                    }
                    foreach (var parameter in method.GetParameters())
                    {
                        if (parameter.IsOut)
                        {
                            paramCount--;
                        }
                    }
                    if (paramCount == tokenCount)
                    {
                        var      methodParameters = method.GetParameters();
                        object   invokeObj        = null;
                        object[] invokeParameters = new object[methodParameters.Length];
                        int      currentJa        = 0;
                        if (!method.IsStatic)
                        {
                            invokeObj = ja[currentJa++].ToObject(_classType);
                        }

                        int outParamCount = 0;
                        try
                        {
                            for (int i = 0; i < methodParameters.Length; i++)
                            {
                                if (!methodParameters[i].IsOut)
                                {
                                    var jsonobject = ja[currentJa++];
                                    var generics   = methodParameters[i].ParameterType.GetGenericArguments();

                                    Type objectType    = null;
                                    bool useSerializer = true;
                                    if (generics == null || generics.Length != 1)
                                    {
                                        objectType    = methodParameters[i].ParameterType;
                                        useSerializer = true;
                                    }
                                    else
                                    {
                                        objectType    = generics[0].MakeArrayType();
                                        useSerializer = false;
                                    }


                                    invokeParameters[i] = DataCache.GetCachedItem(jsonobject, objectType, useSerializer ? serializer : null);


                                    if (invokeParameters[i] == null)
                                    {
                                        if (useSerializer)
                                        {
                                            invokeParameters[i] = jsonobject.ToObject(objectType, serializer);
                                        }
                                        else
                                        {
                                            if (objectType == typeof(GeometryBase[]))
                                            {
                                                // 6 Sept 2020 S. Baer
                                                // This needs to be tuned up. Json.Net is having issues creating arrays of
                                                // GeometryBase since that class is abstract. I think we need to generalize this
                                                // solution, but for now I can repeat the issue when calling
                                                // AreaMassProperties.Compute(IEnumerable<GeometryBase>)
                                                // from an endpoint
                                                GeometryBase[] items = new GeometryBase[jsonobject.Count()];
                                                for (int itemIndex = 0; itemIndex < items.Length; itemIndex++)
                                                {
                                                    var    jsonElement = jsonobject[itemIndex];
                                                    int    archive3dm  = (int)jsonElement["archive3dm"];
                                                    int    opennurbs   = (int)jsonElement["opennurbs"];
                                                    string data        = (string)jsonElement["data"];
                                                    items[itemIndex] = CommonObject.FromBase64String(archive3dm, opennurbs, data) as GeometryBase;
                                                }
                                                invokeParameters[i] = items;
                                            }
                                            else
                                            {
                                                invokeParameters[i] = jsonobject.ToObject(objectType);
                                            }
                                        }
                                    }
                                }

                                if (methodParameters[i].IsOut || methodParameters[i].ParameterType.IsByRef)
                                {
                                    outParamCount++;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (methodIndex < (_methods.Count() - 1))
                            {
                                continue;
                            }
                            throw ex;
                        }
                        bool isConst = false;
                        if (!method.IsStatic)
                        {
                            object[] methodAttrs = method.GetCustomAttributes(true);
                            if (methodAttrs != null)
                            {
                                for (int i = 0; i < methodAttrs.Length; i++)
                                {
                                    Attribute attr = methodAttrs[i] as Attribute;
                                    if (attr != null && attr.ToString().Contains("ConstOperationAttribute"))
                                    {
                                        isConst = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (method.ReturnType != typeof(void) || (!method.IsStatic && !isConst))
                        {
                            outParamCount++;
                        }
                        var invokeResult = method.Invoke(invokeObj, invokeParameters);
                        if (outParamCount < 1)
                        {
                            return("");
                        }
                        object[] rc         = new object[outParamCount];
                        int      outputSlot = 0;
                        if (method.ReturnType != typeof(void))
                        {
                            rc[outputSlot++] = invokeResult;
                        }
                        else if (!method.IsStatic && !isConst)
                        {
                            rc[outputSlot++] = invokeObj;
                        }
                        for (int i = 0; i < methodParameters.Length; i++)
                        {
                            if (methodParameters[i].IsOut || methodParameters[i].ParameterType.IsByRef)
                            {
                                rc[outputSlot++] = invokeParameters[i];
                            }
                        }

                        if (returnModifiers != null && returnModifiers.Count > 0)
                        {
                            for (int i = 0; i < rc.Length; i++)
                            {
                                rc[i] = ProcessModifiers(rc[i], returnModifiers);
                            }
                        }

                        if (rc.Length == 1)
                        {
                            return(Newtonsoft.Json.JsonConvert.SerializeObject(rc[0], GeometryResolver.Settings));
                        }
                        return(Newtonsoft.Json.JsonConvert.SerializeObject(rc, GeometryResolver.Settings));
                    }
                }
            }

            if (_constructors != null)
            {
                for (int k = 0; k < _constructors.Length; k++)
                {
                    var constructor = _constructors[k];
                    int paramCount  = constructor.GetParameters().Length;
                    if (paramCount == tokenCount)
                    {
                        object[] parameters = new object[tokenCount];
                        var      p          = constructor.GetParameters();
                        try
                        {
                            bool skipThisConstructor = false;
                            for (int ip = 0; ip < tokenCount; ip++)
                            {
                                var generics = p[ip].ParameterType.GetGenericArguments();
                                if (generics == null || generics.Length != 1)
                                {
                                    if (_constructors.Length > 0 && p[ip].ParameterType == typeof(Rhino.Geometry.Plane))
                                    {
                                        if (ja[ip].Count() < 4)
                                        {
                                            skipThisConstructor = true;
                                            ip = tokenCount;
                                            continue;
                                        }
                                    }
                                    parameters[ip] = ja[ip].ToObject(p[ip].ParameterType);
                                }
                                else
                                {
                                    var arrayType = generics[0].MakeArrayType();
                                    parameters[ip] = ja[ip].ToObject(arrayType);
                                }
                            }
                            if (skipThisConstructor)
                            {
                                continue;
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        var rc = constructor.Invoke(parameters);
                        rc = ProcessModifiers(rc, returnModifiers);
                        return(Newtonsoft.Json.JsonConvert.SerializeObject(rc, GeometryResolver.Settings));
                    }
                }
            }

            return("");
        }
Example #34
0
        public async void MakeAPICall(string call, Action <Newtonsoft.Json.Linq.JArray> callback)
        {
            if (Token == null)
            {
                GenerateNewToken((bool success) =>
                {
                    if (success)
                    {
                        MakeAPICall(call, callback);
                    }
                    else
                    {
                        callback(null);
                    }
                });
                return;
            }
            HttpWebRequest request;

            //string call = Uri.EscapeDataString(callf);

            /*if (method == HTTPMethod.POST)
             * {
             *  string[] split = call.Split('?'); // 0 is url, 1 is data
             *  byte[] data = Encoding.ASCII.GetBytes(split[1]);
             *  request = (HttpWebRequest)WebRequest.Create(BASE_URL + "api/" + split[0]);
             *  request.ContentLength = data.Length;
             *  request.Method = "POST";
             *  request.ContentType = "application/x-www-form-urlencoded";
             *  using (Stream stream = request.GetRequestStream())
             *  {
             *      stream.Write(data, 0, data.Length);
             *  }
             * }
             * else
             * {*/
            request        = (HttpWebRequest)WebRequest.Create(BASE_URL + "api/" + call);
            request.Method = "GET";
            //request.ContentType = "application/json; charset=utf-8";
            //request.ContentLength = 0;
            //request.Accept = "*/*";
            //request.Host = "sjs.myschoolapp.com";
            //request.Accept = "*/*";
            //request.Headers.Add("Accept-Encoding", "deflate, gzip");
            //request.AutomaticDecompression = DecompressionMethods.GZip;
            //request.UserAgent = "test test test test";
            //request.UseDefaultCredentials = true;
            //}
            request.Headers.Add("Cookie", Token);


            string responseContent = null;

            Newtonsoft.Json.Linq.JArray o = null;

            bool fail = false;

            try
            {
                using (WebResponse response = await request.GetResponseAsync())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader sr99 = new StreamReader(stream))
                        {
                            responseContent = sr99.ReadToEnd();
                        }
                    }
                    o = JsonConvert.DeserializeObject <dynamic>(responseContent);
                    try
                    {
                        if (o["Error"] != null)
                        {
                            fail = true;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
                fail = true;
            }
            if (fail)
            {
                //token is invalid
                GenerateNewToken((bool success) =>
                {
                    if (success)
                    {
                        MakeAPICall(call, callback);
                    }
                    else
                    {
                        callback(null);
                    }
                });
                return;
            }
            else
            {
                callback(o);
            }
        }
Example #35
0
        public static List <string> GetMarketData(string mainMarket, Dictionary <string, MarketInfo> marketInfos, PTMagicConfiguration systemConfiguration, LogHelper log)
        {
            List <string> result = new List <string>();

            string lastMarket = "";

            Newtonsoft.Json.Linq.JObject lastTicker = null;
            try
            {
                string baseUrl = "https://api.binance.com/api/v1/ticker/24hr";

                log.DoLogInfo("Binance - Getting market data...");
                Newtonsoft.Json.Linq.JArray jsonArray = GetSimpleJsonArrayFromURL(baseUrl, log);
                if (jsonArray.Count > 0)
                {
                    double mainCurrencyPrice = 1;
                    if (!mainMarket.Equals("USDT", StringComparison.InvariantCultureIgnoreCase))
                    {
                        mainCurrencyPrice = Binance.GetMainCurrencyPrice(mainMarket, systemConfiguration, log);
                    }

                    log.DoLogInfo("Binance - Market data received for " + jsonArray.Count.ToString() + " currencies");

                    if (mainCurrencyPrice > 0)
                    {
                        Dictionary <string, Market> markets = new Dictionary <string, Market>();
                        foreach (Newtonsoft.Json.Linq.JObject currencyTicker in jsonArray)
                        {
                            string marketName = currencyTicker["symbol"].ToString();
                            //New variables for filtering out bad markets
                            float marketLastPrice = currencyTicker["lastPrice"].ToObject <float>();
                            float marketVolume    = currencyTicker["volume"].ToObject <float>();
                            if (marketName.EndsWith(mainMarket, StringComparison.InvariantCultureIgnoreCase))
                            {
                                if (marketLastPrice > 0 && marketVolume > 0)
                                {
                                    // Set last values in case any error occurs
                                    lastMarket = marketName;
                                    lastTicker = currencyTicker;

                                    Market market = new Market();
                                    market.Position             = markets.Count + 1;
                                    market.Name                 = marketName;
                                    market.Symbol               = currencyTicker["symbol"].ToString();
                                    market.Price                = SystemHelper.TextToDouble(currencyTicker["lastPrice"].ToString(), 0, "en-US");
                                    market.Volume24h            = SystemHelper.TextToDouble(currencyTicker["quoteVolume"].ToString(), 0, "en-US");
                                    market.MainCurrencyPriceUSD = mainCurrencyPrice;

                                    markets.Add(market.Name, market);

                                    result.Add(market.Name);
                                }
                                else
                                {
                                    //Let the user know that the problem market was ignored.
                                    log.DoLogInfo("Binance - Ignoring bad market data for " + marketName);
                                }
                            }
                        }

                        Binance.CheckFirstSeenDates(markets, ref marketInfos, systemConfiguration, log);

                        BaseAnalyzer.SaveMarketInfosToFile(marketInfos, systemConfiguration, log);

                        Binance.CheckForMarketDataRecreation(mainMarket, markets, systemConfiguration, log);

                        DateTime fileDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0).ToUniversalTime();

                        FileHelper.WriteTextToFile(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathExchange + Path.DirectorySeparatorChar, "MarketData_" + fileDateTime.ToString("yyyy-MM-dd_HH.mm") + ".json", JsonConvert.SerializeObject(markets), fileDateTime, fileDateTime);

                        log.DoLogInfo("Binance - Market data saved for " + markets.Count.ToString() + " markets with " + mainMarket + ".");

                        FileHelper.CleanupFiles(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathExchange + Path.DirectorySeparatorChar, systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours);
                        log.DoLogInfo("Binance - Market data cleaned.");
                    }
                    else
                    {
                        log.DoLogError("Binance - Failed to get main market price for " + mainMarket + ".");
                        result = null;
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
                    {
                        using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            Dictionary <string, string> errorData = JsonConvert.DeserializeObject <Dictionary <string, string> >(reader.ReadToEnd());
                            if (errorData != null)
                            {
                                string errorMessage = "Unable to get data from Binance with URL '" + errorResponse.ResponseUri + "'!";
                                if (errorData.ContainsKey("code"))
                                {
                                    errorMessage += " - Code: " + errorData["code"];
                                }

                                if (errorData.ContainsKey("msg"))
                                {
                                    errorMessage += " - Message: " + errorData["msg"];
                                }

                                log.DoLogError(errorMessage);
                            }
                        }
                    }
                }
                result = null;
            }
            catch (Exception ex)
            {
                log.DoLogCritical("Exception while getting data for '" + lastMarket + "': " + ex.Message, ex);
                result = null;
            }

            return(result);
        }
 public ActionResult SubmitStoreEvent(StoreEvent entity, string keyValue = "")
 {
     if (entity.EventConfigString.Equals("[[]]"))
     {
         return(Error("满减条件不可为空!"));
     }
     if (string.IsNullOrEmpty(keyValue))
     {
         entity.EventType = 0;
         int res = GoodsBLL.instance.AddStoreEvent(entity);
         if (!string.IsNullOrEmpty(entity.EventConfigString))
         {
             var json = Newtonsoft.Json.JsonConvert.DeserializeObject(entity.EventConfigString);
             Newtonsoft.Json.Linq.JArray arr = json as Newtonsoft.Json.Linq.JArray;
             if (res > 0 && arr.Count > 0)
             {
                 arr.ToList().ForEach(item =>
                 {
                     StoreEventConfig cfg = new StoreEventConfig
                     {
                         ConditionName  = item["ConditionName"].ToString(),
                         ConditionValue = item["ConditionValue"].ToString(),
                         StoreEventID   = res.ToString()
                     };
                     cfg.Description = $"满{cfg.ConditionName},减{cfg.ConditionValue}";
                     SysBLL.Instance.Insert(cfg);
                 });
             }
         }
     }
     else
     {
         StoreEvent evt = SysBLL.Instance.GetALL <StoreEvent>(where : $"ID='{keyValue}'").FirstOrDefault();
         evt.StartTime = entity.StartTime;
         evt.EndTime   = entity.EndTime;
         evt.Name      = entity.Name;
         evt.Remark    = entity.Remark;
         evt.StoreIds  = entity.StoreIds;
         var res = SysBLL.Instance.UpdateByKey(evt);
         if (res)
         {
             if (!string.IsNullOrEmpty(entity.EventConfigString))
             {
                 var effectRow = 0;
                 var json      = Newtonsoft.Json.JsonConvert.DeserializeObject(entity.EventConfigString);
                 Newtonsoft.Json.Linq.JArray arr = json as Newtonsoft.Json.Linq.JArray;
                 if (arr.Count > 0)
                 {
                     SysBLL.Instance.DeleteByWhere <StoreEventConfig>($"StoreEventID='{keyValue}'");
                     arr.ToList().ForEach(item =>
                     {
                         StoreEventConfig cfg = new StoreEventConfig
                         {
                             ConditionName  = item["ConditionName"].ToString(),
                             ConditionValue = item["ConditionValue"].ToString(),
                             StoreEventID   = evt.ID.ToString()
                         };
                         cfg.Description = $"满{cfg.ConditionName},减{cfg.ConditionValue}";
                         bool result     = SysBLL.Instance.Insert(cfg);
                         effectRow      += (result ? 1 : 0);
                     });
                 }
                 return(effectRow > 0 ? Success("更新成功!") : Error("更新失败!"));
             }
         }
     }
     return(Success("操作成功!"));
 }
Example #37
0
        //GET TRACKS
        public JsonResult GetFeatures(double neLat, double neLng, double swLat, double swLng, string fullurl, int pagesize, int page, string trackType, string difficulty, string duration, string amenities, string activities, string access, string query)
        {
            try
            {
                var          cd = SetGetMemoryCache();
                PreviewItems p  = new PreviewItems();

                //Filter items
                bool filtered         = false;
                bool thisfilteredok   = false;
                bool trackTypeFilter  = false;
                bool difficultyFilter = false;
                bool durationFilter   = false;
                bool amenitiesFilter  = false;
                bool activitiesFilter = false;
                bool accessFilter     = false;


                if (trackType != "" && trackType != "all")
                {
                    filtered        = true;
                    trackTypeFilter = true;
                }
                if (difficulty != "" && difficulty != "all")
                {
                    filtered         = true;
                    difficultyFilter = true;
                }
                if (duration != "" && duration != "all")
                {
                    filtered       = true;
                    durationFilter = true;
                }
                if (amenities != "" && amenities != "all")
                {
                    filtered        = true;
                    amenitiesFilter = true;
                }
                if (activities != "" && activities != "all")
                {
                    filtered         = true;
                    activitiesFilter = true;
                }
                if (access != "" && access != "all")
                {
                    filtered     = true;
                    accessFilter = true;
                }

                foreach (CachedDataClass.Track.Feature f in cd.track.features)
                {
                    bool found = false;

                    if (query.Length > 0)
                    {
                        if (ncstr(f.properties.NAME).ToLower().Contains(query.ToLower()))
                        {
                            found = true;
                        }
                    }
                    else
                    {
                        if (f.geometry.type == "MultiLineString")
                        {
                            foreach (List <object> g in f.geometry.coordinates)
                            {
                                foreach (object o in g)
                                {
                                    Newtonsoft.Json.Linq.JArray h = (Newtonsoft.Json.Linq.JArray)o;
                                    double x = (double)h[0];
                                    double y = (double)h[1];
                                    if (((x >= neLng && x <= swLng) || (x <= neLng && x >= swLng)) && ((y >= neLat && y <= swLat) || (y <= neLat && y >= swLat)))
                                    {
                                        found = true;
                                        break;
                                    }
                                    if (found)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        if (f.geometry.type == "LineString")
                        {
                            foreach (List <object> h in f.geometry.coordinates)
                            {
                                double x = (double)h[0];
                                double y = (double)h[1];
                                if (((x >= neLng && x <= swLng) || (x <= neLng && x >= swLng)) && ((y >= neLat && y <= swLat) || (y <= neLat && y >= swLat)))
                                {
                                    found = true;
                                    break;
                                }
                                if (found)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    if (found)
                    {
                        PreviewItems.Result result = new PreviewItems.Result();
                        result.links = new PreviewItems.Links();
                        string serialno = "0000";
                        if (f.properties.SERIAL_NO != null)
                        {
                            serialno = f.properties.SERIAL_NO;
                        }
                        result.id          = serialno;
                        result.name        = f.properties.NAME;
                        result.description = f.properties.COMMENTS;
                        if (f.properties.COMMENTS == null && f.properties.W_COMMENT != null)
                        {
                            result.description = f.properties.W_COMMENT.ToString();
                        }
                        if (f.properties.COMMENTS != null && f.properties.W_COMMENT != null)
                        {
                            result.description = f.properties.COMMENTS + ' ' + f.properties.W_COMMENT.ToString();
                        }
                        result.featureType = "track";
                        result.closed      = false;
                        if (f.properties.CLOS_STAT != null)
                        {
                            result.closed = true;
                        }
                        result.features      = new List <string>();
                        result.links.details = _appsettings.BaseURL + "/tracks/" + serialno;


                        if (f.photos.Count > 0)
                        {
                            result.image = getImageString(f.photos[0]);
                        }


                        //Get Features
                        foreach (string s in f.trackFeatures)
                        {
                            if (!result.features.Contains(s))
                            {
                                result.features.Add(s);
                            }
                        }


                        if (trackTypeFilter || difficultyFilter || durationFilter || activitiesFilter || amenitiesFilter || accessFilter)
                        {
                            thisfilteredok = true;
                            bool filter1ok = true;
                            bool filter2ok = true;
                            bool filter3ok = true;
                            bool filter4ok = true;
                            bool filter5ok = true;
                            bool filter6ok = true;
                            bool debugtest = false;

                            if (trackTypeFilter)
                            {
                                if (f.properties.SERIAL_NO == "1764")
                                {
                                    debugtest = false;
                                }
                                if (!filterCompare(f.filters.trackType, trackType))
                                {
                                    filter1ok = false;
                                }
                            }

                            if (difficultyFilter && !filterCompare(f.filters.difficulty, difficulty))
                            {
                                filter2ok = false;
                            }


                            if (durationFilter)
                            {
                                if (!filterCompare(f.filters.duration, duration))
                                {
                                    filter3ok = false;
                                }
                                else
                                {
                                    debugtest = true;
                                }
                            }

                            /*
                             * if (activitiesFilter)
                             * {
                             *  if (!filterCompare(f.filters.activities, activities))
                             *  {
                             *      filter4ok = false;
                             *  }
                             *  else
                             *  {
                             *      debugtest = true;
                             *  }
                             * }
                             *
                             * if (amenitiesFilter)
                             * {
                             *  if (!filterCompare(f.filters.amenities, amenities))
                             *  {
                             *      filter5ok = false;
                             *  }
                             *  else
                             *  {
                             *      debugtest = true;
                             *  }
                             * }
                             *
                             * if (accessFilter && !filterCompare(f.filters.access, access))
                             * {
                             *  filter6ok = false;
                             * }
                             */

                            //if (filter1ok) thisfilteredok = true;
                            if (!filter1ok || !filter2ok || !filter2ok || !filter3ok || !filter4ok || !filter5ok || !filter6ok)
                            {
                                thisfilteredok = false;
                            }
                        }


                        if (filtered)
                        {
                            if (thisfilteredok)
                            {
                                p.results.Add(result);
                            }
                        }
                        else
                        {
                            p.results.Add(result);
                        }
                    }
                }



                //GET SITES
                if (/*!trackTypeFilter  && !difficultyFilter && !durationFilter ||*/ true)
                {
                    foreach (CachedDataClass.Site.Feature f in cd.site.features)
                    {
                        bool   found       = false;
                        bool   filterFound = false;
                        double x           = f.geometry.coordinates[0];
                        double y           = f.geometry.coordinates[1];


                        if (query.Length > 0)
                        {
                            if (f.properties.NAME.ToLower().Contains(query.ToLower()))
                            {
                                found = true;
                            }
                        }
                        else
                        {
                            if (((x >= neLng && x <= swLng) || (x <= neLng && x >= swLng)) && ((y >= neLat && y <= swLat) || (y <= neLat && y >= swLat)))
                            {
                                found = true;
                            }
                        }

                        if (found)
                        {
                            if (f.properties.SERIAL_NO == "2118" || f.properties.SERIAL_NO == "10342" || f.properties.SERIAL_NO == "8540")
                            {
                                string debug = "test";
                            }
                            PreviewItems.Result result = new PreviewItems.Result();
                            result.links       = new PreviewItems.Links();
                            result.id          = f.properties.SERIAL_NO;
                            result.name        = f.properties.NAME;
                            result.description = f.siteDescriptrionFromFirstActivity;

                            result.featureType = "site";
                            result.closed      = false;
                            if (f.properties.CLOS_STAT != null)
                            {
                                result.closed = true;
                            }

                            if (f.properties.PHOTO_ID_1 != null)
                            {
                                int pid = 0;
                                int.TryParse(f.properties.PHOTO_ID_1, out pid);
                                if (pid > 0)
                                {
                                    result.image = getImageString(pid);
                                }
                            }

                            result.features      = new List <string>();
                            result.links.details = _appsettings.BaseURL + "/sites/" + f.properties.SERIAL_NO;

                            //Get Features and filters
                            filterFound = false;
                            foreach (string s in f.siteFeatures)
                            {
                                if (!result.features.Contains(s))
                                {
                                    result.features.Add(s);
                                }
                                filterFound = ff(s, trackType, filterFound);
                            }


                            if (/*trackTypeFilter || difficultyFilter || durationFilter ||*/ activitiesFilter || amenitiesFilter || accessFilter)
                            {
                                thisfilteredok = true;
                                bool filter4ok = true;
                                bool filter5ok = true;
                                bool filter6ok = true;
                                bool debugtest = false;

                                if (activitiesFilter && !filterCompare(f.filters.activities, activities))
                                {
                                    filter4ok = false;
                                }

                                if (amenitiesFilter)
                                {
                                    if (!filterCompare(f.filters.amenities, amenities))
                                    {
                                        filter5ok = false;
                                    }
                                    else
                                    {
                                        debugtest = true;
                                    }
                                }

                                if (accessFilter && !filterCompare(f.filters.access, access))
                                {
                                    filter6ok = false;
                                }

                                if (!filter4ok || !filter5ok || !filter6ok)
                                {
                                    thisfilteredok = false;
                                }

                                if (thisfilteredok)
                                {
                                    p.results.Add(result);
                                }
                            }
                            else
                            {
                                p.results.Add(result);
                            }
                        }
                    }
                }


                //GET RELICS
                if (!filtered)
                {
                    foreach (CachedDataClass.Relic.Feature f in cd.relic.features)
                    {
                        bool   found = false;
                        double x     = f.geometry.coordinates[0];
                        double y     = f.geometry.coordinates[1];


                        if (query.Length > 0)
                        {
                            if (f.properties.NAME.ToLower().Contains(query.ToLower()))
                            {
                                found = true;
                            }
                        }
                        else
                        {
                            if (((x >= neLng && x <= swLng) || (x <= neLng && x >= swLng)) && ((y >= neLat && y <= swLat) || (y <= neLat && y >= swLat)))
                            {
                                found = true;
                            }
                        }

                        if (found)
                        {
                            PreviewItems.Result result = new PreviewItems.Result();
                            result.links       = new PreviewItems.Links();
                            result.id          = f.properties.SERIAL_NO;
                            result.name        = f.properties.NAME;
                            result.description = f.properties.COMMENTS;
                            result.featureType = "relic";
                            result.closed      = false;
                            if (f.properties.PHOTO_ID_1 != null)
                            {
                                int pid = 0;
                                int.TryParse(f.properties.PHOTO_ID_1, out pid);
                                if (pid > 0)
                                {
                                    result.image = getImageString(pid);
                                }
                            }
                            result.features = new List <string>();
                            result.features.Add("historicRelic");

                            foreach (string rf in f.relicFeatures)
                            {
                                result.features.Add(rf);
                            }

                            result.links.details = _appsettings.BaseURL + "/relics/" + f.properties.SERIAL_NO;
                            p.results.Add(result);
                        }
                    }
                }

                int totalcount = p.results.Count();

                if (pagesize > 0 && p.results.Count() > pagesize)
                {
                    PreviewItems ppaged = new PreviewItems();

                    int i = 0;
                    foreach (PreviewItems.Result r in p.results)
                    {
                        int mini = pagesize * (page - 1);
                        int maxi = (pagesize * page) - 1;

                        if (i >= mini && i <= maxi)
                        {
                            ppaged.results.Add(r);
                        }

                        if (maxi >= totalcount - 1)
                        {
                            ppaged.meta.links.next = null;
                        }
                        else
                        {
                            string s = fullurl.ToLower().Replace("page=" + page.ToString(), "");
                            s += "&page=" + (page + 1).ToString();
                            s  = s.Replace("&&", "&");
                            ppaged.meta.links.next = s;
                        }
                        i++;
                    }


                    ppaged.meta.totalResults = totalcount;
                    ppaged.meta.links.self   = fullurl.ToLower();

                    JsonResult jsonresult = new JsonResult(ppaged);
                    return(jsonresult);
                }
                else
                {
                    p.meta.totalResults = totalcount;
                    p.meta.links.self   = fullurl.ToLower();

                    JsonResult jsonresult = new JsonResult(p);
                    return(jsonresult);
                }
            }
            catch (Exception ex)
            {
                JsonResult jsonresult = new JsonResult("Error: " + ex.ToString());
                return(jsonresult);
            }
        }
        //this is for updating the webpage and should be removed if the webpage gets an actual webhost
        //and can do this automatically
        public async void UpdateAll(System.Windows.Forms.Control log)
        {
            if (!Directory.Exists("images"))
            {
                Directory.CreateDirectory("images");
            }
            await AwaitHttpLock();

            String length = items.Values.Count.ToString();
            int    num    = 0;

            foreach (Dictionary <String, String> item in items.Values)
            {
                if (!item.TryGetValue("url_name", out String url_name))
                {
                    continue;
                }
                if (!item.TryGetValue("thumb", out String thumb_url))
                {
                    log.Text = num.ToString() + "/" + length + "  Updating " + url_name + " data";
                    log.Refresh();
                    try
                    {
                        using (HttpResponseMessage responce = await client.GetAsync(@"items/" + url_name))
                        {
                            var str = await responce.Content.ReadAsStringAsync();

                            dynamic payload = Newtonsoft.Json.JsonConvert.DeserializeObject(str);
                            Newtonsoft.Json.Linq.JArray jitems = payload.payload.item.items_in_set;
                            foreach (Newtonsoft.Json.Linq.JObject jitem in jitems)
                            {
                                String iname = jitem.Value <Newtonsoft.Json.Linq.JObject>("en").Value <String>("item_name").ToUpper();

                                if (items.TryGetValue(iname, out Dictionary <String, String> possible_data))
                                {
                                    if (jitem.TryGetValue("ducats", out Newtonsoft.Json.Linq.JToken ducats))
                                    {
                                        possible_data["ducats"] = ducats.ToString();
                                    }
                                    if (jitem.TryGetValue("thumb", out Newtonsoft.Json.Linq.JToken thumb))
                                    {
                                        possible_data["thumb"] = thumb.ToString();
                                    }
                                    if (jitem.TryGetValue("rarity", out Newtonsoft.Json.Linq.JToken rarity))
                                    {
                                        possible_data["rarity"] = rarity.ToString();
                                    }
                                }
                            }
                        }
                        item.TryGetValue("thumb", out thumb_url);
                        await Task.Delay(1000);
                    }
                    catch (Exception e) { }
                }
                try
                {
                    log.Text = num.ToString() + "/" + length + "  Updating " + url_name + " price";
                    log.Refresh();
                    using (HttpResponseMessage responce = await client.GetAsync(@"items/" + url_name + "/statistics"))
                    {
                        var str = await responce.Content.ReadAsStringAsync();

                        Newtonsoft.Json.Linq.JObject payload = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(str).payload;
                        Newtonsoft.Json.Linq.JArray  jitems  = payload.Value <Newtonsoft.Json.Linq.JObject>("statistics").Value <Newtonsoft.Json.Linq.JArray>("90days");
                        if (jitems.HasValues)
                        {
                            Dictionary <String, String> stats = jitems.Last.ToObject <Dictionary <String, String> >();
                            foreach (var i in stats)
                            {
                                item[i.Key] = i.Value;
                            }
                        }
                        item["Price Last Updated"] = DateTime.UtcNow.ToString();
                    }
                }
                catch (Exception e)
                { }
                await Task.Delay(1000);

                if ((!item.TryGetValue("local_thumb", out string file_name) || !File.Exists(file_name)) && thumb_url != "")
                {
                    try
                    {
                        log.Text = num.ToString() + "/" + length + "  Updating " + url_name + " thumbnail";
                        log.Refresh();
                        Stream s = await image_client.GetStreamAsync(thumb_url);

                        Bitmap thumb = new Bitmap(Image.FromStream(s));
                        String fname = "images/" + item["item_name"].ToUpper() + "thumb.bmp";
                        thumb.Save(fname);
                        item["local_thumb"] = fname;
                        await Task.Delay(1000);
                    }
                    catch (Exception e)
                    { }
                }
                ++num;
            }
            http_lock = false;
            Save();
            log.Text = "Done!";
        }
        public ActionResult Create()
        {
            int contactId = -1;
            ViewModels.Tasks.CreateTaskViewModel viewModel;
            Common.Models.Matters.Matter matter;
            List<ViewModels.Account.UsersViewModel> userList;
            List<ViewModels.Contacts.ContactViewModel> employeeContactList;
            Newtonsoft.Json.Linq.JArray taskTemplates;

            userList = new List<ViewModels.Account.UsersViewModel>();
            employeeContactList = new List<ViewModels.Contacts.ContactViewModel>();
            
            dynamic profile = ProfileBase.Create(Membership.GetUser().UserName);
            if (profile.ContactId != null && !string.IsNullOrEmpty(profile.ContactId))
                contactId = int.Parse(profile.ContactId);

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                Data.Account.Users.List(conn, false).ForEach(x =>
                {
                    userList.Add(Mapper.Map<ViewModels.Account.UsersViewModel>(x));
                });

                Data.Contacts.Contact.ListEmployeesOnly(conn, false).ForEach(x =>
                {
                    employeeContactList.Add(Mapper.Map<ViewModels.Contacts.ContactViewModel>(x));
                });

                viewModel = new ViewModels.Tasks.CreateTaskViewModel();
                viewModel.TaskTemplates = new List<ViewModels.Tasks.TaskTemplateViewModel>();
                taskTemplates = new Newtonsoft.Json.Linq.JArray();
                Data.Tasks.TaskTemplate.List(conn, false).ForEach(x =>
                {
                    viewModel.TaskTemplates.Add(Mapper.Map<ViewModels.Tasks.TaskTemplateViewModel>(x));
                    Newtonsoft.Json.Linq.JObject template = new Newtonsoft.Json.Linq.JObject();
                    template.Add(new Newtonsoft.Json.Linq.JProperty("Id", x.Id.Value));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("TaskTemplateTitle", x.TaskTemplateTitle));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("Title", x.Title));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("Description", x.Description));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("ProjectedStart", DTProp(x.ProjectedStart)));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("DueDate", DTProp(x.DueDate)));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("ProjectedEnd", DTProp(x.ProjectedEnd)));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("ActualEnd", DTProp(x.ActualEnd)));
                    template.Add(new Newtonsoft.Json.Linq.JProperty("Active", x.Active));
                    taskTemplates.Add(template);
                });

                if (contactId > 0)
                {
                    viewModel.TaskContact = new ViewModels.Tasks.TaskAssignedContactViewModel()
                    {
                        Contact = new ViewModels.Contacts.ContactViewModel()
                        {
                            Id = contactId
                        }
                    };
                }

                matter = Data.Matters.Matter.Get(Guid.Parse(Request["MatterId"]), conn, false);
            }

            ViewBag.Matter = matter;
            ViewBag.UserList = userList;
            ViewBag.EmployeeContactList = employeeContactList;
            ViewBag.TemplateJson = taskTemplates.ToString();

            return View(new ViewModels.Tasks.CreateTaskViewModel()
            {
                TaskTemplates = viewModel.TaskTemplates,               
                TaskContact = new ViewModels.Tasks.TaskAssignedContactViewModel()
                {
                    AssignmentType = ViewModels.AssignmentTypeViewModel.Direct,
                    Contact = viewModel.TaskContact.Contact
                }
            });
        }
        string HandlePostHelper(Newtonsoft.Json.Linq.JArray ja, Dictionary <string, string> returnModifiers)
        {
            int tokenCount = ja == null ? 0 : ja.Count;

            if (_methods != null)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new ArchivableDictionaryResolver());
                int methodIndex = -1;
                foreach (var method in _methods)
                {
                    methodIndex++;
                    int paramCount = method.GetParameters().Length;
                    if (!method.IsStatic)
                    {
                        paramCount++;
                    }
                    foreach (var parameter in method.GetParameters())
                    {
                        if (parameter.IsOut)
                        {
                            paramCount--;
                        }
                    }
                    if (paramCount == tokenCount)
                    {
                        var      methodParameters = method.GetParameters();
                        object   invokeObj        = null;
                        object[] invokeParameters = new object[methodParameters.Length];
                        int      currentJa        = 0;
                        if (!method.IsStatic)
                        {
                            invokeObj = ja[currentJa++].ToObject(_classType);
                        }

                        int outParamCount = 0;
                        try
                        {
                            for (int i = 0; i < methodParameters.Length; i++)
                            {
                                if (!methodParameters[i].IsOut)
                                {
                                    var jsonobject = ja[currentJa++];
                                    var generics   = methodParameters[i].ParameterType.GetGenericArguments();

                                    Type objectType    = null;
                                    bool useSerializer = true;
                                    if (generics == null || generics.Length != 1)
                                    {
                                        objectType    = methodParameters[i].ParameterType;
                                        useSerializer = true;
                                    }
                                    else
                                    {
                                        objectType    = generics[0].MakeArrayType();
                                        useSerializer = false;
                                    }


                                    invokeParameters[i] = DataCache.GetCachedItem(jsonobject, objectType, useSerializer ? serializer : null);


                                    if (invokeParameters[i] == null)
                                    {
                                        if (useSerializer)
                                        {
                                            invokeParameters[i] = jsonobject.ToObject(objectType, serializer);
                                        }
                                        else
                                        {
                                            invokeParameters[i] = jsonobject.ToObject(objectType);
                                        }
                                    }
                                }

                                if (methodParameters[i].IsOut || methodParameters[i].ParameterType.IsByRef)
                                {
                                    outParamCount++;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (methodIndex < (_methods.Count() - 1))
                            {
                                continue;
                            }
                            throw ex;
                        }
                        bool isConst = false;
                        if (!method.IsStatic)
                        {
                            object[] methodAttrs = method.GetCustomAttributes(true);
                            if (methodAttrs != null)
                            {
                                for (int i = 0; i < methodAttrs.Length; i++)
                                {
                                    Attribute attr = methodAttrs[i] as Attribute;
                                    if (attr != null && attr.ToString().Contains("ConstOperationAttribute"))
                                    {
                                        isConst = true;
                                        break;
                                    }
                                }
                                if (!isConst)
                                {
                                    outParamCount++;
                                }
                            }
                        }
                        if (method.ReturnType != typeof(void))
                        {
                            outParamCount++;
                        }
                        var invokeResult = method.Invoke(invokeObj, invokeParameters);
                        if (outParamCount < 1)
                        {
                            return("");
                        }
                        object[] rc         = new object[outParamCount];
                        int      outputSlot = 0;
                        if (method.ReturnType != typeof(void))
                        {
                            rc[outputSlot++] = invokeResult;
                        }
                        else if (!method.IsStatic && !isConst)
                        {
                            rc[outputSlot++] = invokeObj;
                        }
                        for (int i = 0; i < methodParameters.Length; i++)
                        {
                            if (methodParameters[i].IsOut || methodParameters[i].ParameterType.IsByRef)
                            {
                                rc[outputSlot++] = invokeParameters[i];
                            }
                        }

                        if (returnModifiers != null && returnModifiers.Count > 0)
                        {
                            for (int i = 0; i < rc.Length; i++)
                            {
                                rc[i] = ProcessModifiers(rc[i], returnModifiers);
                            }
                        }

                        if (rc.Length == 1)
                        {
                            return(Newtonsoft.Json.JsonConvert.SerializeObject(rc[0], GeometryResolver.Settings));
                        }
                        return(Newtonsoft.Json.JsonConvert.SerializeObject(rc, GeometryResolver.Settings));
                    }
                }
            }

            if (_constructors != null)
            {
                for (int k = 0; k < _constructors.Length; k++)
                {
                    var constructor = _constructors[k];
                    int paramCount  = constructor.GetParameters().Length;
                    if (paramCount == tokenCount)
                    {
                        object[] parameters = new object[tokenCount];
                        var      p          = constructor.GetParameters();
                        try
                        {
                            bool skipThisConstructor = false;
                            for (int ip = 0; ip < tokenCount; ip++)
                            {
                                var generics = p[ip].ParameterType.GetGenericArguments();
                                if (generics == null || generics.Length != 1)
                                {
                                    if (_constructors.Length > 0 && p[ip].ParameterType == typeof(Rhino.Geometry.Plane))
                                    {
                                        if (ja[ip].Count() < 4)
                                        {
                                            skipThisConstructor = true;
                                            ip = tokenCount;
                                            continue;
                                        }
                                    }
                                    parameters[ip] = ja[ip].ToObject(p[ip].ParameterType);
                                }
                                else
                                {
                                    var arrayType = generics[0].MakeArrayType();
                                    parameters[ip] = ja[ip].ToObject(arrayType);
                                }
                            }
                            if (skipThisConstructor)
                            {
                                continue;
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        var rc = constructor.Invoke(parameters);
                        rc = ProcessModifiers(rc, returnModifiers);
                        return(Newtonsoft.Json.JsonConvert.SerializeObject(rc, GeometryResolver.Settings));
                    }
                }
            }

            return("");
        }
Example #41
0
        public void Deploy()
        {
            Console.WriteLine("");
            Console.WriteLine("Deploying JSON");

            Console.WriteLine("Loading Module directory " + sModulePath + "...");
            DirectoryResourceRepository directoryResourceRepository = new DirectoryResourceRepository(sModulePath);

            ContentManager contentManager = new ContentManager(sClientPath, sServerPath);
            NWN2ResourceManager manager = new NWN2ResourceManager();

            contentManager.ServerContentItemScanning += (name, status, bBegin) =>
            {
                if (!bBegin)
                    Console.Write(" -> Staging (" + status.ToString() + ")");
                else
                    Console.Write("\nScanning: " + name);
            };

            contentManager.InitializeModule(directoryResourceRepository);
            contentManager.ResetAllResourcesToDefaultServer();
            contentManager.ResetScanResults();

            checked
            {
                manager.AddRepository(directoryResourceRepository);

                string sModuleName = Path.GetFileNameWithoutExtension(sModulePath);
                string sTlkPath = "";

                foreach (DownloadableResource d in contentManager.GetDownloadableResources())
                {
                    switch (d.Type)
                    {
                        case DownloadableResource.FileType.Hak:
                            string hakPath = sHomePath + "\\hak\\" + d.Name;
                            Console.WriteLine("Adding Hak: " + d.Name);
                            if (File.Exists(hakPath))
                                manager.AddRepository(new ERFResourceRepository(hakPath));
                            else
                                Console.WriteLine("ERROR - Hak file not found in " + hakPath);
                            break;

                        case DownloadableResource.FileType.Tlk:
                            sTlkPath = sHomePath + "\\tlk\\" + d.Name;
                            if (File.Exists(sTlkPath))
                                Console.WriteLine("Found TLK: " + d.Name);
                            else
                                Console.WriteLine("ERROR - Tlk not found in " + sTlkPath);
                            break;
                    }
                }

                KeyValuePair<String, ushort>[] resourceTypes = { new KeyValuePair<String, ushort>("creature", ResUTC),
                                                               new KeyValuePair<String, ushort>("door", ResUTD),
                                                               new KeyValuePair<String, ushort>("encounter", ResUTE),
                                                               new KeyValuePair<String, ushort>("item", ResUTI),
                                                               new KeyValuePair<String, ushort>("store", ResUTM),
                                                               new KeyValuePair<String, ushort>("placeable", ResUTP),
                                                               new KeyValuePair<String, ushort>("tree", ResUTR),
                                                               new KeyValuePair<String, ushort>("sound", ResUTS),
                                                               new KeyValuePair<String, ushort>("trigger", ResUTT),
                                                               new KeyValuePair<String, ushort>("waypoint", ResUTW),
                                                               new KeyValuePair<String, ushort>("light", ResULT),
                                                               new KeyValuePair<String, ushort>("prefab", ResPFB) };

                //ushort[] resourceTypes = { ResUTC, ResUTD, ResUTE, ResUTI, ResUTM, ResUTP, ResUTR, ResUTS, ResUTT, ResUTW, ResULT, ResPFB };

                var json = new Newtonsoft.Json.Linq.JObject();

                foreach (KeyValuePair<String, ushort> rType in resourceTypes)
                {
                    var jsonArray = new Newtonsoft.Json.Linq.JArray();

                    foreach (IResourceEntry resource in manager.FindEntriesByType(rType.Value))
                    {
                        Console.WriteLine(rType.Key + ": " + resource.FullName);

                        var gff = new OEIShared.IO.GFF.GFFFile(resource.GetStream(false));

                        if (gff != null)
                        {
                            Newtonsoft.Json.Linq.JObject jsonData = null;

                            jsonData = new Newtonsoft.Json.Linq.JObject(parseGFF(gff));
                            //Console.WriteLine(jsonData);
                            /*
                            switch (rType.Value)
                            {
                                case ResUTC:
                                    var creature = new NWN2Toolset.NWN2.Data.Blueprints.NWN2CreatureBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(creature);
                                    break;
                                case ResUTD:
                                    var door = new NWN2Toolset.NWN2.Data.Blueprints.NWN2DoorBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(door);
                                    break;
                                case ResUTE:
                                    var encounter = new NWN2Toolset.NWN2.Data.Blueprints.NWN2EncounterBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(encounter);
                                    break;
                                case ResUTI:
                                    var item = new NWN2Toolset.NWN2.Data.Blueprints.NWN2ItemBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(item);
                                    break;
                                case ResUTM:
                                    var store = new NWN2Toolset.NWN2.Data.Blueprints.NWN2StoreBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(store);
                                    break;
                                case ResUTP:
                                    var placeable = new NWN2Toolset.NWN2.Data.Blueprints.NWN2PlaceableBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(placeable);
                                    break;
                                case ResUTR:
                                    var tree = new NWN2Toolset.NWN2.Data.Blueprints.NWN2TreeBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(tree);
                                    break;
                                case ResUTS:
                                    var sound = new NWN2Toolset.NWN2.Data.Blueprints.NWN2SoundBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(sound);
                                    break;
                                case ResUTT:
                                    var trigger = new NWN2Toolset.NWN2.Data.Blueprints.NWN2TriggerBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(trigger);
                                    break;
                                case ResUTW:
                                    var waypoint = new NWN2Toolset.NWN2.Data.Blueprints.NWN2WaypointBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(waypoint);
                                    break;
                                case ResULT:
                                    var light = new NWN2Toolset.NWN2.Data.Blueprints.NWN2LightBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(light);
                                    break;
                                case ResPFB:
                                    //blueprint = new NWN2Toolset.NWN2.Data.Blueprints.NWN2BlueprintSet(gff.TopLevelStruct);
                                    break;
                                default:
                                    break;
                            }
                            */
                            if (jsonData != null) jsonArray.Add(jsonData);
                        }
                    }

                    if (jsonArray.Count > 0) json.Add(rType.Key,jsonArray);
                }

                Console.WriteLine("");
                Console.WriteLine("Staging JSON Complete.");
                Console.WriteLine("");
                Console.WriteLine(json);

                System.IO.File.WriteAllText(@".\nwn2.json", json.ToString());
            }
        }
        private static void MergeJsonObjects(Newtonsoft.Json.Linq.JObject self, Newtonsoft.Json.Linq.JObject other)
        {
            foreach (var p in other.Properties())
            {
                var sp = self.Property(p.Name);
                if (sp == null)
                {
                    self.Add(p);
                }
                else
                {
                    switch (p.Type)
                    {
                    // Primitives override
                    case Newtonsoft.Json.Linq.JTokenType.Boolean:
                    case Newtonsoft.Json.Linq.JTokenType.Bytes:
                    case Newtonsoft.Json.Linq.JTokenType.Comment:
                    case Newtonsoft.Json.Linq.JTokenType.Constructor:
                    case Newtonsoft.Json.Linq.JTokenType.Date:
                    case Newtonsoft.Json.Linq.JTokenType.Float:
                    case Newtonsoft.Json.Linq.JTokenType.Guid:
                    case Newtonsoft.Json.Linq.JTokenType.Integer:
                    case Newtonsoft.Json.Linq.JTokenType.String:
                    case Newtonsoft.Json.Linq.JTokenType.TimeSpan:
                    case Newtonsoft.Json.Linq.JTokenType.Uri:
                    case Newtonsoft.Json.Linq.JTokenType.None:
                    case Newtonsoft.Json.Linq.JTokenType.Null:
                    case Newtonsoft.Json.Linq.JTokenType.Undefined:
                        self.Replace(p);
                        break;

                    // Arrays merge
                    case Newtonsoft.Json.Linq.JTokenType.Array:
                        if (sp.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                        {
                            sp.Value = new Newtonsoft.Json.Linq.JArray(((Newtonsoft.Json.Linq.JArray)sp.Value).Union((Newtonsoft.Json.Linq.JArray)p.Value));
                        }
                        else
                        {
                            var a = new Newtonsoft.Json.Linq.JArray(sp.Value);
                            sp.Value = new Newtonsoft.Json.Linq.JArray(a.Union((Newtonsoft.Json.Linq.JArray)p.Value));
                        }

                        break;

                    // Objects merge
                    case Newtonsoft.Json.Linq.JTokenType.Object:
                        if (sp.Type == Newtonsoft.Json.Linq.JTokenType.Object)
                        {
                            MergeJsonObjects((Newtonsoft.Json.Linq.JObject)sp.Value, (Newtonsoft.Json.Linq.JObject)p.Value);
                        }
                        else
                        {
                            sp.Value = p.Value;
                        }
                        break;

                    // Ignore other stuff
                    default:
                        break;
                    }
                }
            }
        }
Example #43
0
        private void translationButton_ButtonClick(object sender, EventArgs e)
        {
            if (!textBox1.Text.IsNotNullOrWhiteSpace())
            {
                textBox1.SelectAll();
                textBox1.Paste();
            }
            if (string.IsNullOrWhiteSpace(textBox1.Text))
            {
                return;
            }
            var query = textBox1.Text.Split('\n').First().Trim().ToLower();


            var c = GetHTMLByHttpRequest("http://fanyi.youdao.com/openapi.do?keyfrom=asdsadasd&key=1271366606&type=data&doctype=json&version=1.1&q=" + query, null);

            Newtonsoft.Json.Linq.JObject rss = Newtonsoft.Json.Linq.JObject.Parse(c);
            string cs = query + "\r\n";

            try
            {
                cs += "/" + rss["basic"].Value <string>("phonetic") + "/" + "\r\n";
            }
            catch { }
            try
            {
                var postTitles =
                    from p in rss["translation"]
                    select(string) p;
                cs += postTitles.First() + "\r\n";
            }
            catch { }

            try
            {
                var basic =
                    from p in rss["basic"]["explains"]
                    select(string) p;
                cs += basic.ToStringBy();
            }
            catch { }

            try
            {
                var sss = rss["web"];
                foreach (var item in sss)
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JArray iii = (Newtonsoft.Json.Linq.JArray)item.ToList().First().First();
                        cs += item.Value <string>("key") + "\r\n";

                        foreach (Newtonsoft.Json.Linq.JValue i1 in iii)
                        {
                            cs += i1.Value + " ";
                        }
                        cs += "\r\n";
                    }
                    catch { }
                }
            }
            catch { }

            textBox1.Text = cs;
        }
Example #44
0
        public static TickPricesCommand createTickPricesCommand(LinkedList<string> symbols, long? timestamp, bool prettyPrint)
        {
            JSONObject args = new JSONObject();
            JSONArray arr = new JSONArray();
            foreach (string symbol in symbols)
            {
                arr.Add(symbol);
            }

            args.Add("symbols", arr);
            args.Add("timestamp", timestamp);
            return new TickPricesCommand(args, prettyPrint);
        }