コード例 #1
0
        private BudgetViewItem LinkTransactionsItem(BudgetViewItem item, List <Transaction> transactions)
        {
            var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            float sum   = 0;
            int   count = 0;

            foreach (var iTransaction in transactions)
            {
                if (item.CategoryId == iTransaction.CategoryId)
                {
                    if (iTransaction.TypeTransactionId == 1 || iTransaction.TypeTransactionId == 4)
                    {
                        sum -= iTransaction.Amount;  //  Deposits are negative spending
                        count++;
                    }

                    if (iTransaction.TypeTransactionId == 2 || iTransaction.TypeTransactionId == 3)
                    {
                        sum += iTransaction.Amount;  //  Withdrawls are positive spending
                        count++;
                    }
                }
            }

            sum                   = (sum / item.BudgetTotal) * 100;
            item.SumValue         = javaScriptSerializer.Serialize(sum);
            item.TransactionCount = count;
            item.TotalValue       = javaScriptSerializer.Serialize(100);
            return(item);
        }
コード例 #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            if (tp == 1)
            {
                List <string> lstCampos = new List <string>();
                List <string> lstFiltos = new List <string>();
                IDictionary <string, List <string> > Resultado = new Dictionary <string, List <string> >();
                foreach (Object item in listBox1.SelectedItems)
                {
                    lstCampos.Add(item.ToString());
                }
                foreach (Object item in listBox3.SelectedItems)
                {
                    lstFiltos.Add(item.ToString());
                }
                Resultado.Add("Campos", lstCampos);
                Resultado.Add("Filtros", lstFiltos);
                var campo = serializer.Serialize(Resultado);
                controlesTableAdapter1.DeleteQuery(comboBox1.Text.ToString(), "3");
                controlesTableAdapter1.InsertQuery(comboBox1.Text.ToString(), "3", campo);
                MessageBox.Show("Consulta Salva.", "Atenção");
            }
            else
            {
                List <string> lstCampos = new List <string>();
                List <string> lstFiltos = new List <string>();
                List <string> lstQuebra = new List <string>();
                List <string> lstOrdena = new List <string>();
                IDictionary <string, List <string> > Resultado = new Dictionary <string, List <string> >();
                foreach (Object item in listBox1.SelectedItems)
                {
                    lstCampos.Add(item.ToString());
                }
                foreach (Object item in listBox3.SelectedItems)
                {
                    lstFiltos.Add(item.ToString());
                }
                foreach (Object item in listBox5.SelectedItems)
                {
                    lstQuebra.Add(item.ToString());
                }
                foreach (Object item in listBox7.SelectedItems)
                {
                    lstOrdena.Add(item.ToString());
                }
                Resultado.Add("Campos", lstCampos);
                Resultado.Add("Filtros", lstFiltos);
                Resultado.Add("Quebra", lstQuebra);
                Resultado.Add("Ordena", lstOrdena);
                var campo = serializer.Serialize(Resultado);
                controlesTableAdapter1.DeleteQuery(comboBox1.Text.ToString(), "4");
                controlesTableAdapter1.InsertQuery(comboBox1.Text.ToString(), "4", campo);
                MessageBox.Show("Relatório Salvo.", "Atenção");
            }
        }
コード例 #3
0
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="object">源对象</param>
        /// <returns></returns>
        public string SerializeObject(object @object)
        {
            if (@object == null)
            {
                return(string.Empty);
            }

            return(ser.Serialize(@object));
        }
コード例 #4
0
        //Controle de login deus me ajuda OMG :O
        public static bool Login(LoginViewModel user)
        {
            user.idCliente = IDCliente;

            using (var client = new WebClient())
            {
                var jss    = new System.Web.Script.Serialization.JavaScriptSerializer();
                var keyUrl = ConfigurationManager.AppSettings["UrlAPI"].ToString();
                var url    = keyUrl + "/Seguranca/Principal/loginUsuario/" + IDCliente + "/" + 999;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                object           envio   = new { ObjLogin = user };
                var              data    = jss.Serialize(envio);
                var              result  = client.UploadString(url, "POST", data);
                UsuarioViewModel Usuario = jss.Deserialize <UsuarioViewModel>(result);

                Usuario.UsuarioXPerfil = GetPerfilUsuario(Usuario.ID);

                var    current = HttpContext.Current;
                string cookievalue;
                if (Usuario.ID != 0 && Usuario.Ativo && Usuario.Status != 9)
                {
                    if (Convert.ToBoolean(Usuario.VAdmin))
                    {
                        user.idCliente = Usuario.idCliente;
                        user.IdUsuario = Usuario.ID;
                        user.idEmpresa = Usuario.IdEmpresa;
                        user.Nome      = Usuario.Nome;
                        user.Avatar    = Usuario.Avatar;
                        user.idPerfil  = Usuario.UsuarioXPerfil.IdPerfil;

                        if (current.Request.Cookies["UsuarioLogadoStaff"] != null)
                        {
                            current.Request.Cookies["UsuarioLogadoStaff"].Value = string.Empty;
                        }

                        //if (current.Request.Cookies["UsuarioLogadoStaff"] != null)
                        //{
                        //    cookievalue = current.Request.Cookies["UsuarioLogadoStaff"].ToString();
                        //}
                        //else
                        //{
                        current.Response.Cookies["UsuarioLogadoStaff"].Value   = jss.Serialize(user);
                        current.Response.Cookies["UsuarioLogadoStaff"].Expires = DateTime.Now.AddMinutes(30); // add expiry time
                        //}
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="context"></param>
        private void GetPage(HttpContext context)
        {
            string               result    = "";
            JsonModel            jsonModel = null;
            JavaScriptSerializer jss       = new System.Web.Script.Serialization.JavaScriptSerializer();

            try
            {
                MyResource resource = new MyResource();
                Hashtable  ht       = new Hashtable();
                ht.Add("PageIndex", context.Request["PageIndex"].SafeToString());
                ht.Add("PageSize", context.Request["PageSize"].SafeToString());
                ht.Add("TableName", "MyResource");
                ht.Add("Pid", context.Request["Pid"].SafeToString());
                ht.Add("DocName", context.Request["DocName"].SafeToString());
                ht.Add("Postfixs", context.Request["Postfixs"].SafeToString());
                ht.Add("CreateUID", context.Request["CreateUID"].SafeToString());
                DateTime datetime = DateTime.Now;
                string   Time     = context.Request["CreateTime"].SafeToString();
                switch (Time)
                {
                case "Week":
                    datetime = datetime.AddDays(-7);
                    break;

                case "Month":
                    datetime = datetime.AddMonths(-1);
                    break;

                case "Year":
                    datetime = datetime.AddMonths(-6);
                    break;

                default:
                    datetime = datetime.AddYears(-1);
                    break;
                }
                ht.Add("CreateTime", datetime);
                jsonModel = Bll.GetPage(ht);
                result    = "{\"result\":" + jss.Serialize(jsonModel) + "}";
            }
            catch (Exception ex)
            {
                jsonModel = new JsonModel()
                {
                    errNum  = 400,
                    errMsg  = ex.Message,
                    retData = ""
                };
                LogService.WriteErrorLog(ex.Message);
            }
            result = "{\"result\":" + jss.Serialize(jsonModel) + "}";
            context.Response.Write(result);
            context.Response.End();
        }
コード例 #6
0
        public void LoadMultipleTable(MultiTableLoadData data)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            serializer.MaxJsonLength = int.MaxValue;

            Socket socket = buildSocket(SocketResourcePath + "/multiple_load/");

            socket.OnMessage += (sender, e) =>
            {
                SaveInfo info = deserializeSaveInfo(e.Data);
                if (info != null)
                {
                    if (LoadMultipleTableHandler != null)
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke(() => LoadMultipleTableHandler(info, null));
                    }
                    if (info.isEnd)
                    {
                        socket.Close(CloseStatusCode.Normal);
                    }
                    return;
                }

                TableSaveIssue issue = deserializeIssue(e.Data);
                if (issue != null)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        ModelModificationDialog dialog = new ModelModificationDialog();
                        dialog.Display(this, issue);
                        dialog.ShowDialog();
                        issue       = dialog.tableSaveIssue;
                        string json = serializer.Serialize(issue);
                        socket.Send(json);
                    });
                    return;
                }
                logger.Debug("Recieve unreconized message : " + e.Data);
            };

            socket.OnOpen  += (sender, e) => { logger.Debug("Socket opened!"); };
            socket.OnError += (sender, e) => {
                logger.Debug("Socket error : " + e.Message);
            };
            socket.OnClose += (sender, e) => { logger.Debug("Socket closed : " + e.Reason); };

            socket.Connect();
            string text = serializer.Serialize(data);

            socket.Send(text);
        }
コード例 #7
0
        public void setBorrowRecord(HttpContext context)
        {
            string    callback = context.Request["jsoncallback"];
            Hashtable ht       = new Hashtable();


            ht.Add("Id", context.Request["Id"]);
            ht.Add("UserIDCard", context.Request["UserIDCard"]);
            ht.Add("BeginDate", context.Request["BeginDate"]);
            ht.Add("EndDate", context.Request["EndDate"]);
            ht.Add("BorrowReason", context.Request["BorrowReason"]);
            ht.Add("Notes", context.Request["Notes"]);
            ht.Add("operator", context.Request["operator"]);
            string equipJson = context.Request["equipJson"];

            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            List <string> equips = jss.Deserialize <List <string> >(equipJson);

            ht.Add("equips", equips);


            EmsModel.JsonModel Model = BLLBR.SetBorrowRecord(ht);
            context.Response.Write(callback + "({\"result\":" + jss.Serialize(Model) + "})");
            context.Response.End();
        }
コード例 #8
0
        private void button3_Click(object sender, EventArgs e)
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            List <estrutura> ls = new List <estrutura>();

            string[] SQLTipo = new string[dataGridView2.Rows.Count];
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                estrutura estrut = new estrutura(dataGridView2.Rows[i].Cells[0].EditedFormattedValue.ToString(),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[1].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[2].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[3].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[4].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[5].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[6].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[7].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[8].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[9].EditedFormattedValue.ToString()),
                                                 Convert.ToBoolean(dataGridView2.Rows[i].Cells[10].EditedFormattedValue.ToString()));
                ls.Add(estrut);
            }

            resultado = serializer.Serialize(ls);
            usuarioTableAdapter.UpdateQuery(textBox1.Text, textBox2.Text, textBox3.Text, resultado, Convert.ToInt32(textBox4.Text));
            this.usuarioTableAdapter.Fill(this.d12rnams4f6a7nDataSet.usuario);
        }
コード例 #9
0
ファイル: Service.cs プロジェクト: jovill/giswebcomitagem
    public string GetIlu(string prefix)
    {
        DataTable dt = new DataTable();

        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                                    .ConnectionStrings["MyConnString"].ConnectionString;

            using (SqlCommand cmd = new SqlCommand(" SELECT ID_ILUMINACAO_PUBLICA,COD_ILUM_FK,LOCALIDADE,ILUM_PUB.SHAPE.STX as X,ILUM_PUB.SHAPE.STY as Y FROM sde.ILUM_PUB LEFT JOIN sde.INFO_ILUM on sde.ILUM_PUB.OBJECTID=sde.INFO_ILUM.COD_ILUM_FK INNER JOIN sde.ILUM_PUB_KML ON sde.ILUM_PUB.OBJECTID=sde.ILUM_PUB_KML.COD_ILUM_PUB_FK   INNER JOIN sde.KML_TRATADO ON KML_TRATADO.OBJECTID=sde.ILUM_PUB_KML.COD_KML_FK", conn))
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                serializer.MaxJsonLength  = 2147483647;
                serializer.RecursionLimit = 2147483647;
                List <Dictionary <string, object> > rows = new List <Dictionary <string, object> >();
                Dictionary <string, object>         row;
                foreach (DataRow dr in dt.Rows)
                {
                    row = new Dictionary <string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
                    rows.Add(row);
                }
                return(serializer.Serialize(rows));
            }
        }
    }
コード例 #10
0
ファイル: Login.cs プロジェクト: ohm1110/HMSWebserviceDemo
        public string  GetLoginAdminDetailsJSONFormat(string UserName, string Password)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());

            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select * from HotelRegistration where UserName='******' and Password='******' ", con);
            DataSet        ds = new DataSet();

            da.Fill(ds);
            ArrayList root = new ArrayList();
            List <Dictionary <string, object> > table;
            Dictionary <string, object>         data;

            foreach (DataTable dt in ds.Tables)
            {
                table = new List <Dictionary <string, object> >();
                foreach (DataRow dr in dt.Rows)
                {
                    data = new Dictionary <string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        data.Add(col.ColumnName, dr[col]);
                    }
                    table.Add(data);
                }
                root.Add(table);
            }

            return(serializer.Serialize(root));
        }
コード例 #11
0
        public void GetPageEquipDetailNew(HttpContext context)
        {
            string    callback = context.Request["jsoncallback"];
            Hashtable ht       = new Hashtable();

            if (!string.IsNullOrWhiteSpace(Convert.ToString(context.Request["Type"])))
            {
                ht.Add("Type", context.Request["Type"]);
            }
            if (!string.IsNullOrWhiteSpace(Convert.ToString(context.Request["UserRoleID"])))
            {
                ht.Add("RoleID", context.Request["UserRoleID"]);
            }
            if (!string.IsNullOrWhiteSpace(Convert.ToString(context.Request["StorageLocation"])))
            {
                ht.Add("StorageLocation", context.Request["StorageLocation"]);
            }
            if (!string.IsNullOrWhiteSpace(Convert.ToString(context.Request["EquipStatus"])))
            {
                ht.Add("EquipStatus", context.Request["EquipStatus"]);
            }
            string operation = context.Request["Operation"].ToString();

            ht.Add("PageIndex", context.Request["PageIndex"].ToString());
            ht.Add("PageSize", context.Request["PageSize"].ToString());
            ht.Add("AdminRoleID", System.Configuration.ConfigurationManager.ConnectionStrings["AdminRoleID"].ToString());
            EmsModel.JsonModel Model = BLLED.GetPage(ht);

            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            context.Response.Write(callback + "({\"result\":" + jss.Serialize(Model) + "})");
            context.Response.End();
        }
コード例 #12
0
        /// <summary>
        /// For table parametrization
        /// </summary>
        /// <param name="tableName">Table that contains the cellproperty</param>
        /// <param name="range">the cellproperties range</param>
        /// <param name="cellparams">the cell params {Measure, Target,Tag,Period}</param>
        /// <returns>true=> cells well parametrized ; false => no parametrization done.</returns>
        public InputTable parametrizeTable(Kernel.Domain.Parameter parameter)
        {
            try
            {
                if (parameter == null)
                {
                    return(null);
                }
                var request = new RestRequest(ResourcePath + "/parametrize/table/", Method.POST);
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                request.RequestFormat    = DataFormat.Json;
                serializer.MaxJsonLength = int.MaxValue;

                string json = serializer.Serialize(parameter);
                request.AddParameter("application/json", json, ParameterType.RequestBody);

                var          response    = RestClient.ExecuteTaskAsync(request);
                RestResponse queryResult = (RestResponse)response.Result;

                bool valid = ValidateResponse(queryResult);
                System.Web.Script.Serialization.JavaScriptSerializer Serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                Serializer.MaxJsonLength = int.MaxValue;
                InputTable result = Serializer.Deserialize <InputTable>(queryResult.Content);
                return(result);
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
                throw new BcephalException("Unable to parametrize cell ", e);
            }
        }
コード例 #13
0
ファイル: Client.cs プロジェクト: nekosaur/Haytham
        public void ProcessJson_test(myJsonClass mjson)
        {
            string folder = @"fromGlass\Jsons\";

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }


            if (mjson.img != null)
            {
                String SuspiciousPath = Path.Combine(folder, mjson.name + ".jpg");
                mjson.img.Save(SuspiciousPath);
            }
            myJsonClass_test temp = new myJsonClass_test(mjson);


            System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            String s = jSearializer.Serialize(temp);

            System.IO.File.WriteAllText(Path.Combine(folder, temp.name + ".txt"), s);

            METState.Current.METCoreObject.SendToForm(mjson.img, "imScene");
            METState.Current.METCoreObject.SendToForm("", "Update Glass Picturebox");
        }
コード例 #14
0
        /// <summary>
        /// 导出设备Excel
        /// </summary>
        /// <returns></returns>

        public void ExportEquipExcel(HttpContext context)
        {
            string    callback = context.Request["jsoncallback"];
            Hashtable ht       = new Hashtable();

            if (!string.IsNullOrEmpty(context.Request["Id"]))
            {
                ht.Add("Id", context.Request["Id"].ToString());
            }
            if (!string.IsNullOrEmpty(context.Request["ColumnsName"]))
            {
                ht.Add("ColumnsName", context.Request["ColumnsName"].ToString());
            }
            if (!string.IsNullOrEmpty(context.Request["EquipSource"]))
            {
                ht.Add("EquipSource", context.Request["EquipSource"].ToString());
            }
            if (!string.IsNullOrEmpty(context.Request["ClassName"]))
            {
                ht.Add("ClassName", context.Request["ClassName"].ToString());
            }
            EmsModel.JsonModel Model = BLLED.ExportEquipExcel(ht);

            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue; //取得最大数值
            //jss.Serialize(ModelPlan);

            context.Response.Write(callback + "({\"result\":" + jss.Serialize(Model) + "})");
            context.Response.End();
        }
コード例 #15
0
        public bool applyDesign(int designOid, bool forReport, Kernel.Ui.Office.Range currentRange)
        {
            try
            {
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var request = new RestRequest(ResourcePath + "/applydesign/" + designOid + "/" + forReport, Method.POST);
                serializer.MaxJsonLength = int.MaxValue;
                string json = serializer.Serialize(currentRange);
                request.AddParameter("application/json", json, ParameterType.RequestBody);
                RestResponse queryResult = (RestResponse)RestClient.Execute(request);
                try
                {
                    bool result = RestSharp.SimpleJson.DeserializeObject <bool>(queryResult.Content);

                    return(result);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #16
0
        public string GetPortalFeeds(string secretKey)
        {
            try
            {
                string jsonString = string.Empty;

                if (secretKey != null)
                {
                    byte[] data = Convert.FromBase64String(secretKey);
                    if (DataStatics.SecretKey == System.Text.Encoding.UTF8.GetString(data))
                    {
                        #region Retrieve Social Feeds
                        List <PortalFeedsModel.PortalFeed> latestPortalFeeds = PortalFeedsService.QueryPortalFeedsLight();
                        #endregion

                        System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        jsonString = jsonSerializer.Serialize(latestPortalFeeds);
                    }
                }

                return(jsonString);
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
コード例 #17
0
        public static string FillComboGrid(string SQL)
        {
            if (HttpContext.Current.Session["UserName"] == null)
            {
                return "Error: You are not logged-in.";
            }

            DBClass db = new DBClass("Accounts");
            db.Con.Open();
            db.Com.CommandText = SQL;
            SqlDataAdapter da = new SqlDataAdapter(db.Com);
            DataTable dt = new DataTable();
            da.Fill(dt);
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<String, Object>();

                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);

                }

                rows.Add(row);
            }

            db.Con.Close();
            db = null;
            return String.Format("{{\"total\":{0},\"rows\":{1}}}", dt.Rows.Count, serializer.Serialize(rows));
        }
コード例 #18
0
 public virtual bool changeTableExcelFile(string tableName, string newExcelFile)
 {
     try
     {
         System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         var request = new RestRequest(ResourcePath + "/changeexcelFile/table/" + tableName, Method.POST);
         serializer.MaxJsonLength = int.MaxValue;
         string json = serializer.Serialize(newExcelFile);
         request.AddParameter("application/json", json, ParameterType.RequestBody);
         var response = RestClient.ExecuteTaskAsync(request);
         try
         {
             bool result = RestSharp.SimpleJson.DeserializeObject <bool>(response.Result.Content);
             return(result);
         }
         catch (Exception)
         {
             return(false);
         }
     }
     catch (Exception e)
     {
         throw new BcephalException("Unable to close table : " + newExcelFile, e);
     }
 }
コード例 #19
0
ファイル: MeasureService.cs プロジェクト: schifflee/bcephal2
        public bool isMeasureUseAllocation(Kernel.Domain.Measure measure)
        {
            try
            {
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var request = new RestRequest(ResourcePath + "/useallocation", Method.POST);
                request.RequestFormat = DataFormat.Json;
                string json = serializer.Serialize(measure);
                request.AddParameter("application/json", json, ParameterType.RequestBody);
                RestResponse queryResult = (RestResponse)RestClient.Execute(request);

                try
                {
                    bool isUseallocation = RestSharp.SimpleJson.DeserializeObject <bool>(queryResult.Content);
                    return(isUseallocation);
                }
                catch (Exception)
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                throw new BcephalException("Unable to verify measure in allocations ", e);
            }
        }
コード例 #20
0
        /// <summary>
        /// 序列化游戏设置
        /// </summary>
        /// <param name="config"></param>
        /// <param name="configFilePath"></param>
        private static void SerializaConfig(GameConfig config, string configFilePath)
        {
            JsonSerializer serializer = new JsonSerializer();
            string         configJson = serializer.Serialize(config);

            FileHelper.SaveStringToFile(configFilePath, configJson);
        }
コード例 #21
0
 /// <summary>
 /// 把对象转成json字符串
 /// </summary>
 /// <param name="o">对象</param>
 /// <returns>json字符串</returns>
 public static string Serialize(object o)
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
     json.Serialize(o, sb);
     return(sb.ToString());
 }
コード例 #22
0
        public void ClearTree(TableActionData actionData)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            serializer.MaxJsonLength = int.MaxValue;
            Socket socket = buildSocket(SocketResourcePath + "/clear/");

            socket.OnOpen  += (sender, e) => { logger.Debug("Socket opened"); };
            socket.OnError += (sender, e) => { logger.Debug("Socket error  : " + e.Message); };
            socket.OnClose += (sender, e) => { logger.Debug("Socket closed : " + e.Reason); };

            socket.OnMessage += (sender, e) =>
            {
                AllocationRunInfo runInfo = deserializeAllocationRunInfo(e.Data);
                if (runInfo != null)
                {
                    if (ClearTreeHandler != null)
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke(() => ClearTreeHandler(runInfo));
                    }
                    if (runInfo.runEnded)
                    {
                        socket.Close(CloseStatusCode.Normal);
                    }
                    return;
                }
            };

            socket.Connect();
            string text = serializer.Serialize(actionData);

            socket.Send(text);
        }
コード例 #23
0
 public CellProperty getActiveCell(String tableName, GroupProperty group, int row, int col, String sheetName)
 {
     try
     {
         var request = new RestRequest(ResourcePath + "/cell/active/" + tableName + "/" + row + "/" + col + "/" + sheetName, Method.POST);
         System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         serializer.MaxJsonLength = int.MaxValue;
         string json = serializer.Serialize(group);
         request.AddParameter("application/json", json, ParameterType.RequestBody);
         var response = RestClient.ExecuteTaskAsync(request);
         try
         {
             CellProperty result = RestSharp.SimpleJson.DeserializeObject <CellProperty>(response.Result.Content);
             return(result);
         }
         catch (Exception)
         {
             return(null);
         }
     }
     catch (Exception e)
     {
         throw new BcephalException("Unable to close table : " + tableName, e);
     }
 }
コード例 #24
0
        public static string Get_LostEnquiriesDetails(string dealerCode)
        {
            string json                = "";
            var    Serializer          = new System.Web.Script.Serialization.JavaScriptSerializer();
            List <EnquiryDetailVM> lst = new List <EnquiryDetailVM>();

            try
            {
                SqlParameter[] sqlParam =
                {
                    new SqlParameter("@DealerCode", dealerCode),                   //1
                };

                dt = DataAccess.getDataTable("SP_SelectLostFollowUpDetails", sqlParam, General.GetBMSConString());
                if (dt.Rows.Count > 0)
                {
                    lst = EnumerableExtension.ToList <EnquiryDetailVM>(dt);
                }
                json = Serializer.Serialize(lst);
            }
            catch (Exception ex)
            {
                throw;
            }

            return(json);
        }
コード例 #25
0
        /// <summary>
        /// 文件评价
        /// </summary>
        /// <param name="context"></param>
        private void Evalue(HttpContext context)
        {
            JsonModel            jsonModel = null;
            string               result    = "";
            JavaScriptSerializer jss       = new System.Web.Script.Serialization.JavaScriptSerializer();

            try
            {
                string ID        = context.Request.Form["ID"].SafeToString();
                string ClickType = context.Request.Form["ClickType"].SafeToString();
                string IDCard    = context.Request["IDCard"].SafeToString();
                string Evalue    = context.Request["Evalue"].SafeToString();
                UpdateClick(ID, ClickType, IDCard, Evalue);
                UpdateClick(ID, Evalue);
                jsonModel = new JsonModel()
                {
                    errNum  = 0,
                    errMsg  = "",
                    retData = ""
                };
            }
            catch (Exception ex)
            {
                jsonModel = new JsonModel()
                {
                    errNum  = 400,
                    errMsg  = ex.Message,
                    retData = ""
                };
            }
            result = "{\"result\":" + jss.Serialize(jsonModel) + "}";
            context.Response.Write(result);
            context.Response.End();
        }
コード例 #26
0
        public ICustomActivityResult Execute()
        {
            System.IO.StringReader sr = new System.IO.StringReader(tableVariable);

            DataSet ds = new DataSet();

            ds.ReadXml(sr);

            DataTable dt = new DataTable();

            dt = ds.Tables[0];

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List <Dictionary <string, object> > rows = new List <Dictionary <string, object> >();
            Dictionary <string, object>         row;

            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary <string, object>();

                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }

                rows.Add(row);
            }

            return(this.GenerateActivityResult(serializer.Serialize(rows)));
        }
コード例 #27
0
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="context"></param>
        private void ResourceType(HttpContext context)
        {
            ResourceTypeService reType = new ResourceTypeService();

            string               result    = "";
            JsonModel            jsonModel = null;
            JavaScriptSerializer jss       = new System.Web.Script.Serialization.JavaScriptSerializer();
            Hashtable            ht        = new Hashtable();

            ht.Add("TableName", "ResourceType");
            try
            {
                ResourceType resource = new ResourceType();

                jsonModel = reType.GetPage(ht, false);
                // result = "{\"result\":" + jss.Serialize(jsonModel) + "}";
            }
            catch (Exception ex)
            {
                jsonModel = new JsonModel()
                {
                    errNum  = 400,
                    errMsg  = ex.Message,
                    retData = ""
                };
                LogService.WriteErrorLog(ex.Message);
            }
            result = "{\"result\":" + jss.Serialize(jsonModel) + "}";
            context.Response.Write(result);
            context.Response.End();
        }
コード例 #28
0
        static void LerArquivoJson(string pathJson)
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            using (StreamReader r = new StreamReader(pathJson))
            {
                string  json  = r.ReadToEnd();
                dynamic array = serializer.DeserializeObject(json);


                var conexao = new NpgsqlConnection("User ID=postgres;Password=123;Host=localhost;Port=5432;Database=Desafio;Pooling=true;");
                Console.Write("Iniciado");

                conexao.Open();

                Console.WriteLine();
                Console.WriteLine("");
                Console.WriteLine(serializer.Serialize(array));
                Console.WriteLine("");
                Console.WriteLine();

                conexao.Close();
            }
            Console.Write("Execução Finalizada!");
        }
コード例 #29
0
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="context"></param>
        private void GetDowDetail(HttpContext context)
        {
            GetUserNameHandler   common    = new GetUserNameHandler();
            ClickDetailService   Clickbll  = new ClickDetailService();
            string               result    = "";
            JsonModel            jsonModel = null;
            JavaScriptSerializer jss       = new System.Web.Script.Serialization.JavaScriptSerializer();

            try
            {
                ResourcesInfo resource = new ResourcesInfo();
                Hashtable     ht       = new Hashtable();
                ht.Add("PageIndex", context.Request["PageIndex"].SafeToString());
                ht.Add("PageSize", context.Request["PageSize"].SafeToString());

                jsonModel = common.AddCreateNameForData(Clickbll.GetPage(ht, true), 1, true);

                //result = "{\"result\":" + jss.Serialize(jsonModel) + "}";
            }
            catch (Exception ex)
            {
                jsonModel = new JsonModel()
                {
                    errNum  = 400,
                    errMsg  = ex.Message,
                    retData = ""
                };
                LogService.WriteErrorLog(ex.Message);
            }
            result = "{\"result\":" + jss.Serialize(jsonModel) + "}";
            context.Response.Write(result);
            context.Response.End();
        }
コード例 #30
0
    public string UpdateGenUserTracks(int UserID, int PgID, int PgObjID, int PgNbr, int PgSize, string StatusCode, string ProdType, string Prod, string Reg, string Loc, string Species, string Thick, string Grade,
                                      string Seasoning, string Surface, string Width, string Len, string Color, string fSort, string Milling, string NoPrint, string Cust, string Vendor, string Supplier, int ShowWks, int HideComments, int Excl0s, int IncHist,
                                      int Sort, int FontSz, string ItemCode, string ItemName, string ItemDesc, int MainID, int MgrID, int CustID, int OrderID, int ShipID, int OtherID, int LoadID, int Setting1, int Setting2, int Setting3, int Setting4, int Setting5,
                                      string sBeginDt, string sEndDt, string sTargetDT, int ByID)
    {
        Commands cmd = new Commands();

        try
        {
            DateTime?sdate = null;
            DateTime?edate = null;
            DateTime?tdate = null;
            if (!String.IsNullOrWhiteSpace(sBeginDt))
            {
                sdate = Convert.ToDateTime(sBeginDt);
            }
            if (!String.IsNullOrWhiteSpace(sEndDt))
            {
                edate = Convert.ToDateTime(sEndDt);
            }
            if (!String.IsNullOrWhiteSpace(sTargetDT))
            {
                tdate = Convert.ToDateTime(sTargetDT);
            }
            DataTable dt = cmd.UpdateUserTracks(UserID, PgID, PgObjID, PgNbr, PgSize, StatusCode, ProdType, Prod, Reg, Loc, Species, Thick, Grade, Seasoning, Surface, Width, Len, Color, fSort, Milling, NoPrint, Cust, Vendor, Supplier,
                                                ShowWks, HideComments, Excl0s, IncHist, Sort, FontSz, ItemCode, ItemName, ItemDesc, MainID, MgrID, CustID, OrderID, ShipID, OtherID, LoadID, Setting1, Setting2, Setting3, Setting4, Setting5, sdate, edate, tdate, ByID);
            return(JsonHelper.toJSONfmTbl(dt));
        }
        catch (Exception ex)
        {
            int iResult = cmd.LogApplicationError("User Tracks", UserID, ByID, "Err: " + ex.Message, 0, "UpdateGenUserTracks function", ByID);
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            return(js.Serialize(new { Success = false, Message = ex.Message }));
        }
    }
コード例 #31
0
 public string UpdateUIPageSettings(int PageID, int ObjID, int PgNbr, int PgSize, int MainID, int EmpID, int OrderID, int VendorID, int CustID, int SuppID, int SpeciesID, int LocID, int ShipID, int ItemID, int MgrID,
                                    int GroupID, int SortID, int LoadID, int OtherID, double Nbr, string StartDt, string EndDt, string TargetDt, string ItemCode, string ItemName, string TagNbr, string CustCode, string VendorCode, string LocCode, string SpeciesCode,
                                    string SuppCode, string ThickCode, string GradeCode, string StatusCode, int iType, int ByID)
 {
     try
     {
         DateTime?sdate = null;
         DateTime?edate = null;
         DateTime?tdate = null;
         if (!String.IsNullOrWhiteSpace(StartDt))
         {
             sdate = Convert.ToDateTime(StartDt);
         }
         if (!String.IsNullOrWhiteSpace(EndDt))
         {
             edate = Convert.ToDateTime(EndDt);
         }
         if (!String.IsNullOrWhiteSpace(TargetDt))
         {
             tdate = Convert.ToDateTime(TargetDt);
         }
         PaginationFn pg = new PaginationFn();
         DataTable    dt = pg.UpdateUIPageSettings(PageID, ObjID, PgNbr, PgSize, MainID, EmpID, OrderID, VendorID, CustID, SuppID, SpeciesID, LocID, ShipID, ItemID, MgrID, GroupID, SortID, LoadID, OtherID, Nbr, sdate, edate, tdate,
                                                   ItemCode, ItemName, TagNbr, CustCode, VendorCode, LocCode, SpeciesCode, SuppCode, ThickCode, GradeCode, StatusCode, iType, ByID);
         return(JsonHelper.toJSONfmTbl(dt));
     }
     catch (Exception ex)
     {
         Commands cmd     = new Commands();
         int      iResult = cmd.LogApplicationError("DataMngt", ObjID, ByID, "Err: " + ex.Message, 0, "UpdateUIPageSettings function", ByID);
         System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
         return(js.Serialize(new { Success = false, Message = ex.Message }));
     }
 }
コード例 #32
0
    public static string AddRequiredParameters(string Amount, string CurrencyCode, string SellerNote)
    {
        // Mandatory fields
        string sellerId = WebConfigurationManager.AppSettings["sellerId"];
        string accessKey = WebConfigurationManager.AppSettings["accessKey"];
        string secretKey = WebConfigurationManager.AppSettings["secretKey"];
        string lwaClientId = WebConfigurationManager.AppSettings["lwaClientId"];

        if (String.IsNullOrEmpty(sellerId))
            throw new ArgumentNullException("sellerId", "sellerId is NULL, set the value in the configuration file ");
        if (String.IsNullOrEmpty(accessKey))
            throw new ArgumentNullException("accessKey", "accessKey is NULL, set the value in the configuration file ");
        if (String.IsNullOrEmpty(secretKey))
            throw new ArgumentNullException("secretKey", "secretKey is NULL, set the value in the configuration file ");
        if (String.IsNullOrEmpty(lwaClientId))
            throw new ArgumentNullException("lwaClientId", "lwaClientId is NULL, set the value in the configuration file ");

        string amount = Amount;

        /* Add http:// or https:// before your Return URL
         * The webpage of your site where the buyer should be redirected to after the payment is made
         * In this example you can link it to the Result.jsp, which checks for the success or failure of the payment
         * and routes it to the appropriate URL defined
         */
        string returnURL = "http://yourdomain.com/Result.aspx";

        // Optional fields
        string currencyCode = CurrencyCode;
        string sellerNote = SellerNote;
        string sellerOrderId = "YOUR_CUSTOM_ORDER_REFERENCE_ID";
        string shippingAddressRequired = "true";
        string paymentAction = "AuthorizeAndCapture";

        IDictionary<String, String> parameters = new Dictionary<String, String>();
        parameters.Add("accessKey", accessKey);
        parameters.Add("sellerId", sellerId);
        parameters.Add("amount", amount);
        parameters.Add("returnURL", returnURL);
        parameters.Add("lwaClientId", lwaClientId);
        parameters.Add("sellerNote", sellerNote);
        parameters.Add("sellerOrderId", sellerOrderId);
        parameters.Add("currencyCode", currencyCode);
        parameters.Add("shippingAddressRequired", shippingAddressRequired);
        parameters.Add("paymentAction", paymentAction);

        string Signature = SignParameters(parameters, secretKey);

        IDictionary<String, String> SortedParameters =
                  new SortedDictionary<String, String>(parameters, StringComparer.Ordinal);
        SortedParameters.Add("signature", UrlEncode(Signature, false));

        var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return (jsonSerializer.Serialize(SortedParameters));
    }
コード例 #33
0
    //truyen json data len form
    public static void WriteJsonData(HttpResponse response, Object obj)
    {
        response.Clear();
        response.ClearContent();
        response.ClearHeaders();
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

        string output = oSerializer.Serialize(obj);

        response.ContentType = "Application/Json";
        response.Write(output);
        response.End();
    }
コード例 #34
0
        public void register()
        {
            RegistrationControl rControl = new RegistrationControl(libr);
            DialogResult dlgResult = rControl.Run(form);

            if (dlgResult == DialogResult.OK)
            {
                System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                string sJSON = oSerializer.Serialize(rControl.getNewPerson());
                sJSON += "\n";
                File.AppendAllText(@"E:\Registration\Registration\Registration\DataBase.json", sJSON);

                libr.Add(rControl.getNewPerson());
            }
        }
コード例 #35
0
 public string ConvertDataTabletoString(DataTable dt)
 {
     System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
     Dictionary<string, object> row;
     foreach (DataRow dr in dt.Rows)
     {
         row = new Dictionary<string, object>();
         foreach (DataColumn col in dt.Columns)
         {
             row.Add(col.ColumnName, dr[col]);
         }
         rows.Add(row);
     }
     return serializer.Serialize(rows);
 }
コード例 #36
0
 public ActionResult ViewVisitRecordDetail(List<string> PostID)
 {
     try
     {
         string PatID = PostID[0];
         string VisitID = PostID[1];
         this.TempData["recordID"] = VisitID.ToString();
         ReportData Rdata = visitop.ViewDetail(PatID, VisitID);
         System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         string sJSON = oSerializer.Serialize(Rdata);
         return Json(sJSON, JsonRequestBehavior.AllowGet);
     }
     catch (System.Exception e)
     {
         return null;
     }
 }
コード例 #37
0
ファイル: NewLeads.aspx.cs プロジェクト: AAGJKPRT/LMT
 public static string getSupplierList()
 {
     List<SupplierList> IsupplierList = new List<SupplierList>();
     SupplierList supplier = new SupplierList();
     DataTable dtSupplier = new DataTable();
     dtSupplier = CrystalConnection.CreateDataTableWithoutTransaction("usp_GetAllSupplierList");
     foreach (DataRow dr in dtSupplier.Rows)
     {
         supplier = new SupplierList();
         supplier.SupplierId = Convert.ToInt32(dr["SupplierID"]);
         supplier.SupplierName = dr["SupplierName"].ToString();
         IsupplierList.Add(supplier);
     }
     string sJSON = "";
     var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     return sJSON = oSerializer.Serialize(IsupplierList);
 }
コード例 #38
0
ファイル: MainControl.cs プロジェクト: oleh111/Registration
 public void Admin()
 {
     AdminFormController aControl = new AdminFormController(libr);
     DialogResult dlgResult = aControl.Run(form);
     if (dlgResult==DialogResult.OK)
     {
         libr = aControl.getLibr();
         string path = "..\\..\\DataBase.json";
         File.WriteAllText(path, "");
         System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         for (int i = 0; i < libr.Bracket.Count; i++)
         {
             string sJSON = oSerializer.Serialize(libr.Bracket[i]);
             sJSON += "\n";
             File.AppendAllText(path, sJSON);
         }
     }
 }
コード例 #39
0
    public String ConvertDataTableTojSonString(DataTable dataTable)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer =
               new System.Web.Script.Serialization.JavaScriptSerializer();

        List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();

        Dictionary<String, Object> row;

        foreach (DataRow dr in dataTable.Rows)
        {
            row = new Dictionary<String, Object>();
            foreach (DataColumn col in dataTable.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            tableRows.Add(row);
        }
        return serializer.Serialize(tableRows);
    }
コード例 #40
0
        public JsonResult GetOldestOutstandingbyUserCount()
        {
            Home home = new Home();

            List<string> javascriptList = new List<string>();

            try
            {
                home.GetOldestOutstandingbyUserCount();
                var serialize = new System.Web.Script.Serialization.JavaScriptSerializer();

                foreach (Dictionary<string, string> dict in home.oldestPriorityTasksCount)
                {
                    javascriptList.Add(serialize.Serialize(dict));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return Json(javascriptList.ToArray(), JsonRequestBehavior.AllowGet);
        }
コード例 #41
0
        public string RankVideos(
string p_Search_keyword,
string p_rank_keyword)
        {
            SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YoutubeDashboardContext"].ConnectionString);

            Conn.Open();

            string user_id = "";
            string uname = Session["username"].ToString();
            string get_userid = "select  id from app_users where username ='******'";

            SqlCommand cmdselectUser = new SqlCommand(get_userid, Conn);

            SqlDataReader reader = cmdselectUser.ExecuteReader();

            while (reader.Read())
            {
                user_id = user_id + reader["id"];
            }
            reader.Close();

            //Query to insert data
            string query = "";
            if (p_rank_keyword == "Rank")
            {
                 query = "select * from video_search_log where rtrim(ltrim(Search_keyword))  ='" + p_Search_keyword + "' and user_id=" + user_id + " order by  view_count  desc , like_count desc, comment_count desc , dislike_count asc";
            }
            else
            {
                 query = "select * from video_search_log where rtrim(ltrim(Search_keyword))  ='" + p_Search_keyword + "'  and user_id =" + user_id + " order by " + p_rank_keyword + " desc";
            }
            //Conn.Close();
            SqlCommand cmd1 = new SqlCommand(query, Conn);
            //Build a command that will execute your SQL
            DataTable dt = new DataTable();
            cmd1.ExecuteNonQuery();
            SqlDataAdapter objDataAdapter = new SqlDataAdapter(cmd1);
            objDataAdapter.Fill(dt);
            Conn.Close();

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            String result = serializer.Serialize(rows);
            return result;
        }
コード例 #42
0
        public string userLogActivity()
        {
            SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YoutubeDashboardContext"].ConnectionString);

            Conn.Open();

            //Query to get recent search data
            string query = "select user_id , username , user_action , Login_count , case when Login_count>50 then 'Frequent User' when login_count > 0 then 'Normal User' when login_count = 0 then 'Idle User' end user_activity_type from ( select b.id user_id , b.username , user_action , count(action_result) Login_count from  app_users b  left outer join user_activity_log a on ( a.user_id=b.id)  group by b.id ,b.username ,  user_action)c order by login_count desc";
               SqlCommand cmd1 = new SqlCommand(query, Conn);
            DataTable dt = new DataTable();
            cmd1.ExecuteNonQuery();
            SqlDataAdapter objDataAdapter = new SqlDataAdapter(cmd1);
            objDataAdapter.Fill(dt);
            Conn.Close();

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            String result = serializer.Serialize(rows);
            return result;
        }
コード例 #43
0
        public static string GetTeam2Members()
        {

            TeamJson team = new TeamJson();

            try
            {
                team.teamId = GameViewModel.Instance.Team2.TeamId.ToString();

                if (GameViewModel.Instance.Team2.TeamName != null)
                {
                    team.teamName = GameViewModel.Instance.Team2.TeamName;
                }

                if (GameViewModel.Instance.CurrentJam != null)
                {
                    team.currentJam = GameViewModel.Instance.CurrentJam.JamNumber;
                    team.currentJamId = GameViewModel.Instance.CurrentJam.JamId.ToString();
                    team.totalJams = GameViewModel.Instance.Jams.Count;
                }

                for (int i = 0; i < GameViewModel.Instance.Team2.TeamMembers.Count; i++)
                {
                    try
                    {
                        TeamMemberJson member = new TeamMemberJson();
                        member.memberName = GameViewModel.Instance.Team2.TeamMembers[i].SkaterName;
                        member.memberId = GameViewModel.Instance.Team2.TeamMembers[i].SkaterId.ToString();
                        member.memberNumber = GameViewModel.Instance.Team2.TeamMembers[i].SkaterNumber;

                        var blocks = GameViewModel.Instance.BlocksForTeam2.Where(x => x.PlayerWhoBlocked != null).Where(x => x.PlayerWhoBlocked.SkaterId != null).Where(x => x.PlayerWhoBlocked.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId).Count();
                        member.totalBlocks = blocks;

                        if (GameViewModel.Instance.CurrentJam != null)
                        {

                            if (GameViewModel.Instance.BlocksForTeam2 != null)
                            {
                                var mem = GameViewModel.Instance.BlocksForTeam2.Where(x => x.PlayerWhoBlocked != null).Where(x => x.PlayerWhoBlocked.SkaterId != null).Where(x => x.PlayerWhoBlocked.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId);
                                if (mem != null && mem.Count() > 0)
                                    member.blocksForJam = mem.Where(x => x.JamId == GameViewModel.Instance.CurrentJam.JamId).Count();
                                else
                                    member.blocksForJam = 0;
                            }
                            else
                                member.blocksForJam = 0;


                            if (GameViewModel.Instance.AssistsForTeam2 != null)
                            {
                                var mem = GameViewModel.Instance.AssistsForTeam2.Where(x => x.PlayerWhoAssisted != null).Where(x => x.PlayerWhoAssisted.SkaterId != null).Where(x => x.PlayerWhoAssisted.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId);
                                if (mem != null && mem.Count() > 0)
                                    member.assistsForJam = mem.Where(x => x.JamId == GameViewModel.Instance.CurrentJam.JamId).Count();
                                else
                                    member.assistsForJam = 0;
                            }
                            else
                                member.assistsForJam = 0;


                            if (GameViewModel.Instance.PenaltiesForTeam2 != null)
                            {
                                var mem = GameViewModel.Instance.PenaltiesForTeam2.Where(x => x.PenaltyAgainstMember != null).Where(x => x.PenaltyAgainstMember.SkaterId != null).Where(x => x.PenaltyAgainstMember.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId);
                                if (mem != null && mem.Count() > 0)
                                    member.penaltiesForJam = mem.Where(x => x.JamId == GameViewModel.Instance.CurrentJam.JamId).Count();
                                else
                                    member.penaltiesForJam = 0;
                            }
                            else
                                member.penaltiesForJam = 0;


                            if (GameViewModel.Instance.ScoresTeam2 != null)
                            {
                                var mem = GameViewModel.Instance.ScoresTeam2.Where(x => x.PlayerWhoScored != null).Where(x => x.PlayerWhoScored.SkaterId != null).Where(x => x.PlayerWhoScored.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId);
                                if (mem != null && mem.Count() > 0)
                                    member.scoreForJam = mem.Where(x => x.JamId == GameViewModel.Instance.CurrentJam.JamId).Sum(x => x.Points);
                                else
                                    member.scoreForJam = 0;
                            }
                            else
                                member.scoreForJam = 0;
                        }
                        member.totalAssists = GameViewModel.Instance.AssistsForTeam2.Where(x => x.PlayerWhoAssisted != null).Where(x => x.PlayerWhoAssisted.SkaterId != null).Where(x => x.PlayerWhoAssisted.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId).Count();
                        member.totalPenalties = GameViewModel.Instance.PenaltiesForTeam2.Where(x => x.PenaltyAgainstMember != null).Where(x => x.PenaltyAgainstMember.SkaterId != null).Where(x => x.PenaltyAgainstMember.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId).Count();
                        member.totalScores = GameViewModel.Instance.ScoresTeam2.Where(x => x.PlayerWhoScored != null).Where(x => x.PlayerWhoScored.SkaterId != null).Where(x => x.PlayerWhoScored.SkaterId == GameViewModel.Instance.Team2.TeamMembers[i].SkaterId).Sum(x => x.Points);
                        member.isJammer = GameViewModel.Instance.Team2.TeamMembers[i].IsJammer;
                        member.isPivot = GameViewModel.Instance.Team2.TeamMembers[i].IsPivot;
                        member.isBlocker1 = GameViewModel.Instance.Team2.TeamMembers[i].IsBlocker1;
                        member.isBlocker2 = GameViewModel.Instance.Team2.TeamMembers[i].IsBlocker2;
                        member.isBlocker3 = GameViewModel.Instance.Team2.TeamMembers[i].IsBlocker3;
                        member.isBlocker4 = GameViewModel.Instance.Team2.TeamMembers[i].IsBlocker4;
                        member.linedUp = !GameViewModel.Instance.Team2.TeamMembers[i].IsBenched;
                        member.isPBox = GameViewModel.Instance.Team2.TeamMembers[i].IsInBox;
                        team.members.Add(member);
                    }
                    catch (Exception exception)
                    {
                        ErrorViewModel.Save(exception, exception.GetType(), additionalInformation: GameViewModel.Instance.Team2.TeamMembers[i].SkaterId + ":" + Logger.Instance.getLoggedMessages());
                    }
                }
                team.gameName = GameViewModel.Instance.GameName;
            }
            catch (Exception exception)
            {
                ErrorViewModel.Save(exception, exception.GetType(), additionalInformation: Logger.Instance.getLoggedMessages());
            }

            System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();

            return s.Serialize(team);
        }
コード例 #44
0
        public HttpResponseMessage listcontent(string area)
        {
            /*
             * select TABLE_NAME
                from INFORMATION_SCHEMA.COLUMNS
                where TABLE_CATALOG = 'civilgis'
                and TABLE_NAME like '%chicago%'
                group by TABLE_NAME;
             */

            var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];

            string sEcho = httpContext.Request.Params["draw"];

            int orderColumn = Convert.ToInt32(httpContext.Request.Params["order[0][column]"]);

            string iDisplayStart = httpContext.Request.Params["start"];
            string iDisplayLength = httpContext.Request.Params["length"];

            string orderDir = httpContext.Request.Params["order[0][dir]"];
            string searchValue = httpContext.Request.Params["search[value]"];

            //-------------------------------------------

            string result = "";
            int totalData = 0;
            int totalFiltered = 0;
            string sql = "";
            DataTable dt_tablename;

            string connectionString = ConfigurationManager.ConnectionStrings["SqlserverContext"].ConnectionString;

            using (SqlConnection con = new SqlConnection(connectionString))
            {

                con.Open();

                //  -----------------  just get total count --------------------

                //sql = "select table_name from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'civilgis' and table_name like '%" + area + "%'  group by table_name;";

                sql = "select count(table_name) from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'civilgis' and table_name like '%" + area + "%'  group by table_name;";

                using (SqlCommand commandRowCount = new SqlCommand(sql, con))

                {
                    commandRowCount.CommandType = CommandType.Text;

                    object countStart = commandRowCount.ExecuteScalar();
                    int? _count = (int?)(!Convert.IsDBNull(countStart) ? countStart : null);
                    //int _count = int.Parse(commandRowCount.ExecuteScalar().ToString());

                    totalData = Convert.ToInt32(_count);
                    totalFiltered = totalData;

                }  // sqlcommand

                //----------------------just get total count    ------------------

                // filtered result by search value
                if (!(string.IsNullOrEmpty(searchValue)))
                {

                    // if there is a search parameter

                    sql = "select table_name from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'civilgis' and table_name like '%" + area + "%' ";

                    sql = sql + " and TABLE_NAME like '%" + searchValue + "%' ";
                    sql = sql + " group by TABLE_NAME ";
                    sql = sql + " ORDER BY TABLE_NAME " + "   " + orderDir + "  OFFSET " + iDisplayStart + "  ROWS FETCH NEXT  " + iDisplayLength + "  ROWS ONLY  ";

                    /*
                     * select TABLE_NAME
                        from INFORMATION_SCHEMA.COLUMNS
                        where TABLE_CATALOG = 'civilgis'
                        and TABLE_NAME like '%area%'
                     *  and TABLE_NAME like '%searchValue%'
                     *  order by TABLE_NAME OFFSET  1 ROWS
                              FETCH NEXT 10 ROWS ONLY
                        group by TABLE_NAME;
                     */

                    using (SqlCommand cmd = new SqlCommand(sql, con))
                    {

                        dt_tablename = new DataTable();
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(dt_tablename);

                        totalFiltered = dt_tablename.Rows.Count;

                    }// sqlcommand

                }// if search value
                else
                {

                    sql = "select table_name from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'civilgis' and table_name like '%" + area + "%' ";

                    sql = sql + " group by TABLE_NAME ";
                    sql = sql + " ORDER BY TABLE_NAME " + "   " + orderDir + "  OFFSET " + iDisplayStart + "  ROWS FETCH NEXT  " + iDisplayLength + "  ROWS ONLY  ";

                           using (SqlCommand cmd = new SqlCommand(sql, con))
                           {
                               dt_tablename = new DataTable();
                               SqlDataAdapter da = new SqlDataAdapter(cmd);
                               da.Fill(dt_tablename);

                               totalFiltered = dt_tablename.Rows.Count;

                           }// sqlcommand

                }

            }//sqlconnection using

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            // use dynamic or object both works
            Dictionary<string, dynamic> _response = new Dictionary<string, dynamic>();
            //Dictionary<string, object> _response = new Dictionary<string, object>();

            _response["draw"] = Convert.ToInt16(sEcho);

            _response["recordsTotal"] = totalData;
            _response["recordsFiltered"] = totalFiltered;

            // datatable to list <dictionary> to Json
            // datatables use columns[0], columns[1] instead of columns[name].... must add index start from 0

            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt_tablename.Rows)
            {
                int k = 0;
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt_tablename.Columns)
                {

                    row.Add(Convert.ToString(k), dr[col]);
                    row.Add(col.ColumnName, dr[col]);
                    k = k + 1;
                }
                rows.Add(row);
            }

            _response["data"] = rows;

            result = serializer.Serialize(_response);

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result, "text/plain");

            return response;
        }
コード例 #45
0
        public HttpResponseMessage tableheader(string area, string subject)
        {
            string result = "";

            string  tabledata_name = area+"_"+ subject;
            string connectionString = ConfigurationManager.ConnectionStrings["SqlserverContext"].ConnectionString;

            string sql = "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='" + tabledata_name + "'";

            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);

                    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                    ArrayList arrayList = new ArrayList();
                               //create arraylsit from DataTable
                               foreach (DataRow dr in dt.Rows)
                               {
                                   arrayList.Add(dr["COLUMN_NAME"]);
                               }

                     Dictionary<string, ArrayList> dict = new Dictionary<string, ArrayList>();
                     dict["columns"] = arrayList;

                     result = serializer.Serialize(dict);

                    /*  loop through all rows all cells

                    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                    Dictionary<string, object> row;
                    foreach (DataRow dr in dt.Rows)
                    {
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dt.Columns)
                        {
                            row.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(row);
                    }// for

                    result = serializer.Serialize(rows);
                     */

                }// sqlcommand
            }//sqlconnection

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result, "text/plain");

            return response;
        }
コード例 #46
0
        public string recentSearchController()
        {
            SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YoutubeDashboardContext"].ConnectionString);

            Conn.Open();

            string user_id = "";
            string uname = Session["username"].ToString();
            string get_userid = "select  id from app_users where username ='******'";

            SqlCommand cmdselectUser = new SqlCommand(get_userid, Conn);

            SqlDataReader reader = cmdselectUser.ExecuteReader();

            while (reader.Read())
            {
                user_id = user_id + reader["id"];
            }
            reader.Close();

            //Query to get recent search data
            string query = "select top 10 b.* from (select a.* , rank() over (partition by user_id , Search_keyword  order by date_created desc , view_count desc) rnk from video_search_log a)b where user_id=" + user_id + " and rnk=1 order by date_created desc , view_count desc, like_count desc";
            SqlCommand cmd1 = new SqlCommand(query, Conn);
            DataTable dt = new DataTable();
            cmd1.ExecuteNonQuery();
            SqlDataAdapter objDataAdapter = new SqlDataAdapter(cmd1);
            objDataAdapter.Fill(dt);
            Conn.Close();

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            String result = serializer.Serialize(rows);
            return result;
        }
コード例 #47
0
        //[AcceptVerbs("GET", "POST")]
        public HttpResponseMessage tabledata(string area, string subject)
        {
            /* ---------  handle request from datatables post ajax call, api reference  ----------------
             * http://datatables.net/manual/server-side
             * http://coderexample.com/datatable-demo-server-side-in-phpmysql-and-ajax/
             *
             *  draw:2
                columns[0][data]:0
                columns[0][name]:
                columns[0][searchable]:true
                columns[0][orderable]:true
                columns[0][search][value]:
                columns[0][search][regex]:false
                columns[1][data]:1
                columns[1][name]:
                columns[1][searchable]:true
                columns[1][orderable]:true
                columns[1][search][value]:
                columns[1][search][regex]:false
                columns[2][data]:2
                columns[2][name]:
                columns[2][searchable]:true
                columns[2][orderable]:true
                columns[2][search][value]:
                columns[2][search][regex]:false
                columns[3][data]:3
                columns[3][name]:
                columns[3][searchable]:true
                columns[3][orderable]:true
                columns[3][search][value]:
                columns[3][search][regex]:false
                columns[4][data]:4
                columns[4][name]:
                columns[4][searchable]:true
                columns[4][orderable]:true
                columns[4][search][value]:
                columns[4][search][regex]:false
                order[0][column]:0
                order[0][dir]:asc
                start:964
                length:81
                search[value]:
                search[regex]:false
             *
             *
             *      For POST request:

                    string sEcho = Request.Params["draw"];
                    int iDisplayStart = Convert.ToInt32(Request.Params["start"]);
                    string searchValue = Request.Params["search[value]"];
                    int orderColumn = Convert.ToInt32(Request.Params["order[0][column]"]);
                    string orderDir = Request.Params["order[0][dir]"];

             * For GET request:

                    NameValueCollection nvc = HttpUtility.ParseQueryString(Request.Url.Query);
                    string sEcho = nvc["draw"];
                    int iDisplayStart = Convert.ToInt32(nvc["start"]);
                    string searchValue = nvc["search[value]"];
                    int orderColumn = Convert.ToInt32(nvc["order[0][column]"]);
                    string orderDir = nvc["order[0][dir]"];
             *
             *
             *
             *
            */

            //var parameters = HttpContext.Current.Request.Form;

            var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];

            string sEcho = httpContext.Request.Params["draw"];

            //int iDisplayStart = Convert.ToInt32(httpContext.Request.Params["start"]);
               // int iDisplayLength = Convert.ToInt32(httpContext.Request.Params["length"]);
            int orderColumn = Convert.ToInt32(httpContext.Request.Params["order[0][column]"]);

            string iDisplayStart = httpContext.Request.Params["start"];
            string iDisplayLength = httpContext.Request.Params["length"];
               // string orderColumn = httpContext.Request.Params["order[0][column]"];

            string orderDir = httpContext.Request.Params["order[0][dir]"];
            string searchValue = httpContext.Request.Params["search[value]"];

            //-------------------------------------------

            ArrayList columns;
            string result = "";
            int totalData = 0;
            int totalFiltered = 0;

            // get all the column name

            string tabledata_name = area + "_" + subject;
            string connectionString = ConfigurationManager.ConnectionStrings["SqlserverContext"].ConnectionString;

            DataTable dt_body;

            using (SqlConnection con = new SqlConnection(connectionString))
            {

                con.Open();

                        string sql = "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='" + tabledata_name + "'";
                        using (SqlCommand cmd = new SqlCommand(sql, con))
                        {
                            DataTable dt_header = new DataTable();
                            SqlDataAdapter da = new SqlDataAdapter(cmd);
                            da.Fill(dt_header);

                            columns = new ArrayList();

                            //create arraylsit from DataTable
                            foreach (DataRow dr in dt_header.Rows)
                            {
                                columns.Add(dr["COLUMN_NAME"]);
                            }

                        }// sqlcommand

                        //  -----------------  just get total count --------------------

                        sql = "SELECT count(*) FROM " + tabledata_name;
                        using (SqlCommand commandRowCount = new SqlCommand(sql, con))
                        {
                            commandRowCount.CommandType = CommandType.Text;

                            object countStart = commandRowCount.ExecuteScalar();
                            int? _count = (int?)(!Convert.IsDBNull(countStart) ? countStart : null);
                            //int _count = int.Parse(commandRowCount.ExecuteScalar().ToString());

                            totalData = Convert.ToInt32(_count);
                            totalFiltered = totalData;

                        }  // sqlcommand

                        //----------------------end just get total count    ------------------

                      // filtered result by search value
                      if (!(string.IsNullOrEmpty(searchValue)))
                        {

                                     // if there is a search parameter

                                                   sql = "SELECT * FROM " + tabledata_name +" WHERE ";

                                                   for (int i = 0; i < columns.Count; i++)
                                                   {

                                                        if (i > 0)
                                                               {
                                                                  sql= sql + " OR ";

                                                               }// if

                                                           sql= sql +  columns[i]+ " LIKE '%"+ searchValue +"%' ";

                                                       }// for

                                                                       /*
                                                                                select * from Chicago_Current_Employee_Salaries
                                                                                 where name like '%terry%'
                                                                                 order by Name OFFSET  5 ROWS
                                                                                 FETCH NEXT 5 ROWS ONLY
                                                                        */

                                          sql = sql + " ORDER BY " + columns[orderColumn] + "   " + orderDir  + "  OFFSET " + iDisplayStart + "  ROWS FETCH NEXT  " +iDisplayLength + "  ROWS ONLY  ";

                                        using (SqlCommand cmd = new SqlCommand(sql, con))
                                        {

                                            dt_body = new DataTable();
                                            SqlDataAdapter da = new SqlDataAdapter(cmd);
                                            da.Fill(dt_body);

                                            totalFiltered = dt_body.Rows.Count;

                                        }// sqlcommand

                            } else
                                 {

                                            sql = "SELECT * FROM " + tabledata_name +"  ";

                                            sql = sql + " ORDER BY " + columns[orderColumn] + "   " + orderDir + "  OFFSET " + iDisplayStart + "  ROWS FETCH NEXT  " + iDisplayLength + "  ROWS ONLY  ";

                                            using (SqlCommand cmd = new SqlCommand(sql, con))
                                            {

                                                dt_body = new DataTable();
                                                SqlDataAdapter da = new SqlDataAdapter(cmd);
                                                da.Fill(dt_body);

                                            }// sqlcommand

                                   }//else

                      }//sqlconnection using

                      System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                     // use dynamic or object both works
                      Dictionary<string, dynamic> _response = new Dictionary<string, dynamic>();
                      //Dictionary<string, object> _response = new Dictionary<string, object>();

                      _response["draw"] = Convert.ToInt16(sEcho);

                      _response["recordsTotal"] = totalData;
                      _response["recordsFiltered"] = totalFiltered;

                      // datatable to list <dictionary> to Json
                      // datatables use columns[0], columns[1] instead of columns[name].... must add index start from 0

                      List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                      Dictionary<string, object> row;
                      foreach (DataRow dr in dt_body.Rows)
                      {
                          int k = 0;
                          row = new Dictionary<string, object>();
                          foreach (DataColumn col in dt_body.Columns)
                          {

                              row.Add(Convert.ToString(k), dr[col]);
                              row.Add(col.ColumnName, dr[col]);
                              k = k + 1;
                          }
                          rows.Add(row);
                      }

                      _response["data"] = rows;

                      result = serializer.Serialize(_response);

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result, "text/plain");

            return response;
        }
コード例 #48
0
ファイル: Device.cs プロジェクト: moscrif/ide
        public string GenerateJson()
        {
            string json ="";

            try{

                System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
                     new System.Web.Script.Serialization.JavaScriptSerializer();

                oSerializer.RegisterConverters
                    (new System.Web.Script.Serialization.JavaScriptConverter[]
                     {
                        new DeviceJavaScriptConverter(),
                     	new PublishPropertyJavaScriptConverter(),
                        new IncludesJavaScriptConverter(),
                        new SkinJavaScriptConverter(),
                        new ConditionJavaScriptConverter()
                     });
                string sJSON = oSerializer.Serialize(this);
                json =  sJSON;

            }catch(Exception ex){
                Logger.Error(ex.Message);
                return "";
            }

            DeviceJSonFormatter djf= new DeviceJSonFormatter();
            json = djf.Format(json);

            return json;
        }
コード例 #49
0
ファイル: ShopForm.cs プロジェクト: oleh111/Registration
        private void ShopForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            string path = "..\\..\\IndieBase.json";
            File.WriteAllText(path, "");
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            for (int i = 0; i < indies.Count; i++)
            {
                string sJSON = oSerializer.Serialize(indies[i]);
                sJSON += "\n";
                File.AppendAllText(path, sJSON);
            }

            path = "..\\..\\DataBase.json";
            File.WriteAllText(path, "");
            for (int j = 0; j < libr.size(); j++)
            {
                string sJSON = oSerializer.Serialize(libr.getByIndex(j));
                sJSON += "\n";
                File.AppendAllText(path, sJSON);

            }
        }
コード例 #50
0
        private void save(Info n)
        {

            XmlSerializer sl = new XmlSerializer(typeof(Info));

            FileStream cd;
            sl.Serialize(cd = File.OpenWrite(@"B:\code\oursonic\" + scriptName + ".xml"), n);
            cd.Close();


            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            oSerializer.MaxJsonLength *= 10;
            string sJSON = oSerializer.Serialize(n);
            File.WriteAllText(@"B:\code\oursonic\" + scriptName + ".js", sJSON);

            cd.Close();


            gmc = sJSON;








        }
コード例 #51
0
ファイル: Program.cs プロジェクト: cubean/CG
        static void DumpInst()
        {
            var server = new Sig200ServerClass();
            Sig200SignatureList insList = null;
            server.CreateInstructionSignatures(null);
            server.SetMnemonic(eSIG200_MNEMONICS.eSIG200_MNEMONIC_SIMATIC);
            server.GetInstructionSignatureList(ref insList);
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            var sigs = new List<InsStruct>();
            for (int i = 1; i < insList.GetSize(); ++i)
            {
                InsStruct sig = new InsStruct();
                Sig200Signature ins = null;
                insList.GetAt(i, ref ins);
                var isig = (CoMsSig200Lib.ISig200SignatureServerOnlyAccess)ins;
                sig.OpCode = isig.GetOpCode();
                string name;
                isig.GetName(out name);
                sig.Editors = ins.GetEditors();
                sig.ExecutionStatusScheme = ins.GetExecutionStatusScheme();
                sig.FBDVersion = ins.GetFBDVersion();
                sig.IECFBDVersion = ins.GetIECFBDVersion();
                sig.IECInstructionCategory = ins.GetIECInstructionCategory();
                sig.IECLADVersion = ins.GetIECLADVersion();
                sig.IECSTLVersion = ins.GetIECSTLVersion();
                sig.InstId = ins.GetInstId();
                sig.InstructionCategory = ins.GetInstructionCategory();
                sig.InstructionSets = ins.GetInstructionSets();
                sig.InstructionType = ins.GetInstructionType();
                ins.GetInternationalMnemonic(out sig.InternationalMnemonic);
                sig.IsOverloaded = ins.GetIsOverloaded();
                sig.LADVersion = ins.GetLADVersion();
                sig.MacroExpansionFormat = ins.GetMacroExpansionFormat();
                sig.MacroRecognitionFormat = ins.GetMacroRecognitionFormat();
                sig.ReturnsStackInfo = ins.GetReturnsStackInfo();
                sig.RMEInstructionType = ins.GetRMEInstructionType();
                sig.RunModeEdgeBit = ins.GetRunModeEdgeBit();
                sig.SetsENO = ins.GetSetsENO();
                ins.GetSimaticMnemonic(out sig.SimaticMnemonic);
                sig.StackUsage = ins.GetStackUsage();
                sig.STLANDVersion = ins.GetSTLANDVersion();
                sig.STLORVersion = ins.GetSTLORVersion();
                sig.STLVersion = ins.GetSTLVersion();
                sig.HasPowerFlowIn = ins.HasPowerFlowIn() > 0;
                sig.HasPowerFlowOut = ins.HasPowerFlowOut() > 0;
                sig.HasRangeCheckField = ins.HasRangeCheckField() > 0;
                sig.OpCode = server.GetOpCode(sig.InstId, 0, sig.ParameterCount);
                sig.ParameterCount = ins.GetParameterCount();
                sig.Parameters = new List<InsParam>();

                for (int j=0; j<sig.ParameterCount; ++j)
                {
                    InsParam p = new InsParam();
                    Sig200Parameter param = null;
                    ins.GetParameter(j, ref param);
                    p.AddrRangeQual = param.GetAddrRangeQual();
                    p.DataFormats = param.GetDataFormats();
                    p.DataTypes = param.GetDataTypes();
                    p.DefStatusFormat = param.GetDefStatusFormat();
                    p.DisplaysWithRisingEdge = param.GetDisplaysWithRisingEdge();
                    p.MemoryAreas = param.GetMemoryAreas();
                    param.GetName(out p.Name);
                    p.Size = param.GetSize();
                    p.VarType = param.GetVarType();
                    p.IsOverloaded = param.IsOverloaded() > 0;
                    sig.Parameters.Add(p);
                }
                sigs.Add(sig);
            }

            //oSerializer.RegisterConverters(new JavaScriptConverter[] { new IntConverter() });
            string sJSON = oSerializer.Serialize(sigs);
            Console.WriteLine(sJSON);
        }
コード例 #52
0
ファイル: Widget.cs プロジェクト: Techtwebty/Brew
        private List<KeyValuePair<String, object>> ParseEvents()
        {
            var result = new List<KeyValuePair<String, object>>();
            var type = this.GetType();
            var auto = typeof(IAutoPostBack).IsAssignableFrom(type);
            var events = GetEvents();
            var postbacks = new Dictionary<String, String>();

            foreach (var e in events) {
                var @event = type.GetEvents().Where(ev => ev.Name.ToLower() == e.Name || ev.Name == e.EventName).FirstOrDefault();

                if (@event == null || !auto) {
                    continue;
                    //throw new ArgumentException("Brew Error: Widget has event defined with no matching EventHandler.");
                }

                if (auto) {
                    var iauto = this as IAutoPostBack;
                    if (!iauto.AutoPostBack) {
                        continue;
                    }
                }

                var field = type.GetField(@event.Name, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
                var del = (Delegate)field.GetValue(this);

                if (del != null) {
                    var list = del.GetInvocationList();

                    // add only those for which event handlers are assigned
                    if (list != null && list.Length > 0 && e.CausesPostBack) {
                        postbacks.Add(e.Name, e.DataChangedEvent ? @event.Name : null);
                    }
                }
            }

            var js = new System.Web.Script.Serialization.JavaScriptSerializer();
            var json = js.Serialize(postbacks);
            var pair = new KeyValuePair<string, object>("postbacks", json);

            result.Add(pair);

            return result;
        }
コード例 #53
0
        private void Buy(int i)
        {
            GameFormController gfcntrl = new GameFormController(glibr.Get(i), user, t1[i], t2[i], t3[i]);
            DialogResult dlgResult = gfcntrl.Run(this);
            if (dlgResult == DialogResult.OK)
            {
                user.Glib.Add(glibr.Get(i));
                libr.Set(user);
                System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                File.WriteAllText(@"E:\Registration\Registration\Registration\DataBase.json", "");
                for (int j = 0; j < libr.size(); j++)
                {
                    string sJSON = oSerializer.Serialize(libr.getByIndex(j));
                    sJSON += "\n";
                    File.AppendAllText(@"E:\Registration\Registration\Registration\DataBase.json", sJSON);

                }
                initializeTabPage2();
            }
        }
コード例 #54
0
ファイル: BudgetController-Back.cs プロジェクト: khwwas/SCMS
        //public String GetLastRecordByBudgetTypeId(string LocationId, string BudgetTypeId)
        //{
        //    var Budget = new DALBudgetEntry().GetLastRecordByVchrType(LocationId, BudgetTypeId);
        //    String LastBudget = "";
        //    if (Budget != null && Budget.Count > 0)
        //    {
        //        LastBudget += "<div class='CustomCell' style='width: 800px; height: 30px; font-family: Tahoma;'>";
        //        LastBudget += "<b>Budget # : </b>";
        //        LastBudget += Budget.Last().BgdtMas_Code;
        //        LastBudget += "<b>, Date : </b>";
        //        LastBudget += Budget.Last().BgdtMas_Date != null ? Convert.ToDateTime(Budget.Last().BgdtMas_Date).ToShortDateString() : "";
        //        LastBudget += "<b>, Status : </b>";
        //        LastBudget += Budget.Last().BgdtMas_Status;
        //        LastBudget += "</div>";
        //        LastBudget += "<div class='Clear' style='border-bottom: 1px solid #ccc; margin-bottom: 5px;'>";
        //        LastBudget += "</div>";
        //    }
        //    return LastBudget;
        //}
        //public ActionResult SaveBudget(String BudgetMasterCode, DateTime BudgetDate, string Status, String BudgetType, String LocationId, String Remarks, String[] BudgetDetailRows)
        //[HttpPost]
        //[AcceptVerbs(HttpVerbs.Post)]
        public string SaveBudget(IEnumerable<string> BudgetRow)
        {
            //Session["BudgetTypeForBudgetEntry"] = BudgetType;
            //Session["LocationIdForBudgetEntry"] = LocationId;
            DALBudgetEntry objDalBudgetEntry = new DALBudgetEntry();
            DALCalendar objDalCalendar = new DALCalendar();
            GL_BgdtMaster GLBgdtMaster = new GL_BgdtMaster();
            //int flag = 0;

            //String ls_Action = "Edit", IsAuditTrail = "", ls_UserId = "";
            //String[] ls_Lable = new String[7], ls_Data = new String[7];
            Int32 li_ReturnValue = 0;

            try
            {

                //    GL_VchrDetail GL_Detail = new GL_VchrDetail();
                //    String Prefix = new DALBudgetType().GetAllData().Where(c => c.BgdtType_Id.Equals(BudgetType)).SingleOrDefault().VchrType_Prefix;
                //    ls_VchrTypId = Convert.ToString(Convert.ToInt32(BudgetType));

                String[] MasterRow = BudgetRow.Last().Split('║');
                String BudgetMasterId = MasterRow[0];
                String BudgetMasterCode = MasterRow[1].Replace("[Auto]", null);
                DateTime BudgetDate = MasterRow[2] != null ? Convert.ToDateTime(MasterRow[2]) : DateTime.Now;
                String Status = MasterRow[3];
                String BudgetType = MasterRow[4];
                String Year = MasterRow[5];
                String LocationId = MasterRow[6];
                String Remarks = MasterRow[7];
                string ls_YearPrefix = "";

                //if (String.IsNullOrEmpty(BudgetMasterId))
                if (String.IsNullOrEmpty(BudgetMasterCode))
                {
                    if (DALCommon.AutoCodeGeneration("GL_BgdtMaster") == 1)
                    {
                        ls_YearPrefix = objDalCalendar.GetCalendarPrefix_ByCurrentDate(BudgetDate);
                        if (ls_YearPrefix == null && ls_YearPrefix == "")
                        {
                            return "";
                        }
                        BudgetMasterId = DALCommon.GetMaxBudgetMasId(ls_YearPrefix);
                        BudgetMasterCode = BudgetMasterId;
                        //BudgetMasterCode = DALCommon.GetMaxBudgetCode("GL_VchrMaster", BudgetType, Prefix, LocationId, ls_YearPrefix);
                        //ls_Action = "Add";
                    }
                }

                //    List<GL_VchrDetail> BudgetDetailList = new List<GL_VchrDetail>();

                if (!String.IsNullOrEmpty(BudgetMasterCode))
                {
                    //ViewData["BudgetId"] = BudgetMasterId;
                    //ViewData["BudgetCode"] = BudgetMasterCode;

                    GLBgdtMaster.BgdtMas_Id = BudgetMasterId;
                    GLBgdtMaster.BgdtMas_Code = BudgetMasterCode;
                    GLBgdtMaster.BgdtMas_Date = BudgetDate;
                    GLBgdtMaster.BgdtMas_Status = Status;
                    GLBgdtMaster.BgdtType_Id = BudgetType;
                    GLBgdtMaster.Cldr_Id = Year;
                    GLBgdtMaster.Loc_Id = LocationId;
                    GLBgdtMaster.BgdtMas_Remarks = Remarks;
                    GLBgdtMaster.BgdtMas_EnteredDate = DateTime.Now;
                    GLBgdtMaster.BgdtMas_EnteredBy = ((SECURITY_User)Session["user"]).User_Title;
                    li_ReturnValue = objDalBudgetEntry.SaveBudgetMaster(GLBgdtMaster);
                    //        if (li_ReturnValue > 0)
                    //        {
                    //            if (flag == 1)
                    //            {
                    //                objDalBudgetEntry.DeleteDetailRecordByMasterId(BudgetMasterId);
                    //            }
                    //            for (int index = 0; index < BudgetDetailRows.ToList().Count - 1; index++)
                    //            {
                    //                string Row = BudgetDetailRows.ToList()[index];
                    //                String[] Columns = Row.Split('║');
                    //                String BudgetDetailCode = "";

                    //                if (String.IsNullOrEmpty(BudgetDetailCode))
                    //                {
                    //                    if (DALCommon.AutoCodeGeneration("GL_VchrDetail") == 1)
                    //                    {
                    //                        BudgetDetailCode = DALCommon.GetMaximumCode("GL_VchrDetail");
                    //                        //BudgetDetailCode = BudgetMasterCode;
                    //                    }
                    //                }

                    //                if (!String.IsNullOrEmpty(BudgetDetailCode) && Columns[0] != null && Columns[0] != "" && Columns[0] != "0" && ((Columns[1] != null && Columns[1] != "") || (Columns[2] != null && Columns[2] != "")))
                    //                {
                    //                    GL_Detail = new GL_VchrDetail();
                    //                    GL_Detail.VchDet_Id = BudgetDetailCode;
                    //                    GL_Detail.BgdtMas_Id = BudgetMasterId;
                    //                    GL_Detail.ChrtAcc_Id = Columns[0].ToString(); //Columns[0] has AccountId from Account Title drop down;
                    //                    GL_Detail.VchMas_DrAmount = (Columns[1] != null && Columns[1] != "") ? Convert.ToDecimal(Columns[1].Replace(",", "")) : 0; // Columns[1] has Debit Amount
                    //                    GL_Detail.VchMas_CrAmount = (Columns[2] != null && Columns[2] != "") ? Convert.ToDecimal(Columns[2].Replace(",", "")) : 0; // Columns[2] has Debit Amount
                    //                    GL_Detail.VchDet_Remarks = (Columns[3] != null && Columns[3] != "") ? Columns[3].ToString() : ""; // Columns[3] has Remarks
                    //                    objDalBudgetEntry.SaveBudgetDetail(GL_Detail);
                    //                    BudgetDetailList.Add(GL_Detail);
                    //                }
                    //            }
                    //        }
                }
                //ViewData["SaveResult"] = li_ReturnValue;

                //    IsAuditTrail = System.Configuration.ConfigurationManager.AppSettings.GetValues("IsAuditTrail")[0];

                //    // Save Audit Log
                //    if (li_ReturnValue > 0 && IsAuditTrail == "1")
                //    {
                //        DALAuditLog objAuditLog = new DALAuditLog();

                //        ls_UserId = ((SECURITY_User)Session["user"]).User_Id;
                //        ls_Lable[0] = "Code";
                //        ls_Lable[1] = "Date";
                //        ls_Lable[2] = "Location";
                //        ls_Lable[3] = "Budget Type";
                //        ls_Lable[4] = "Remarks";
                //        ls_Lable[5] = "Status";

                //        ls_Data[0] = BudgetMasterCode;
                //        ls_Data[1] = BudgetDate.ToString("dd/MM/yyyy");
                //        ls_Data[2] = LocationId;
                //        ls_Data[3] = BudgetType;
                //        ls_Data[4] = Remarks;
                //        ls_Data[5] = Status;

                //        foreach (GL_VchrDetail BudgetDetail in BudgetDetailList)
                //        {
                //            Increment++;
                //            ls_Lable[Increment] = "Account Code";
                //            ls_Data[Increment] = BudgetDetail.ChrtAcc_Id;

                //            Increment++;
                //            ls_Lable[Increment] = "Debit";
                //            ls_Data[Increment] = Convert.ToString(BudgetDetail.VchMas_DrAmount);

                //            Increment++;
                //            ls_Lable[Increment] = "Credit";
                //            ls_Data[Increment] = Convert.ToString(BudgetDetail.VchMas_CrAmount);

                //            Increment++;
                //            ls_Lable[Increment] = "Narration";
                //            ls_Data[Increment] = BudgetDetail.VchDet_Remarks;
                //        }

                //        objAuditLog.SaveRecord(7, ls_UserId, ls_Action, ls_Lable, ls_Data);
                //    }
                //    //// Audit Trail Entry Section
                //    //if (li_ReturnValue > 0)
                //    //{
                //    //    string IsAuditTrail = System.Configuration.ConfigurationManager.AppSettings.GetValues(3)[0];
                //    //    if (IsAuditTrail == "1")
                //    //    {
                //    //        SYSTEM_AuditTrail systemAuditTrail = new SYSTEM_AuditTrail();
                //    //        DALAuditLog objAuditTrail = new DALAuditLog();
                //    //        systemAuditTrail.Scr_Id = flag == 0 ? 17 : 16;
                //    //        systemAuditTrail.User_Id = ((SECURITY_User)Session["user"]).User_Id;
                //    //        systemAuditTrail.Loc_Id = GL_Master.Loc_Id;
                //    //        systemAuditTrail.BgdtType_Id = GL_Master.BgdtType_Id;
                //    //        systemAuditTrail.AdtTrl_Action = flag == 0 ? "Add" : "Edit";
                //    //        systemAuditTrail.AdtTrl_EntryId = BudgetMasterId;
                //    //        systemAuditTrail.AdtTrl_DataDump = "BgdtMas_Id = " + GL_Master.BgdtMas_Id + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "BgdtMas_Code = " + GL_Master.BgdtMas_Code + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "BgdtMas_Date = " + GL_Master.BgdtMas_Date + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "Cmp_Id = " + GL_Master.Cmp_Id + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "Loc_Id = " + GL_Master.Loc_Id + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "BgdtType_Id = " + GL_Master.BgdtType_Id + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "BgdtMas_Remarks = " + GL_Master.BgdtMas_Remarks + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "BgdtMas_Status = " + GL_Master.BgdtMas_Status + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "VchMas_EnteredBy = " + GL_Master.VchMas_EnteredBy + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "VchMas_EnteredDate = " + GL_Master.VchMas_EnteredDate + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "VchMas_ApprovedBy = " + GL_Master.VchMas_ApprovedBy + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "VchMas_ApprovedDate = " + GL_Master.VchMas_ApprovedDate + ";";
                //    //        systemAuditTrail.AdtTrl_DataDump += "SyncStatus = " + GL_Master.SyncStatus + ";";

                //    //        foreach (GL_VchrDetail BudgetDetail in BudgetDetailList)
                //    //        {
                //    //            systemAuditTrail.AdtTrl_DataDump += "║ VchDet_Id = " + BudgetDetail.VchDet_Id + ";";
                //    //            systemAuditTrail.AdtTrl_DataDump += "BgdtMas_Id = " + BudgetDetail.BgdtMas_Id + ";";
                //    //            systemAuditTrail.AdtTrl_DataDump += "ChrtAcc_Id = " + BudgetDetail.ChrtAcc_Id + ";";
                //    //            systemAuditTrail.AdtTrl_DataDump += "VchMas_DrAmount = " + BudgetDetail.VchMas_DrAmount + ";";
                //    //            systemAuditTrail.AdtTrl_DataDump += "VchMas_CrAmount = " + BudgetDetail.VchMas_CrAmount + ";";
                //    //            systemAuditTrail.AdtTrl_DataDump += "VchDet_Remarks = " + BudgetDetail.VchDet_Remarks + ";";
                //    //        }

                //    //        systemAuditTrail.AdtTrl_Date = DateTime.Now;
                //    //        objAuditTrail.SaveRecord(systemAuditTrail);
                //    //    }
                //    //}
                //    //// Audit Trail Section End

                //    //return PartialView("GridData");
                //    //string result = ViewData["BudgetId"].ToString(); //+ "|" + ViewData["BudgetCode"].ToString() + "|" + ViewData["SaveResult"].ToString();
                string[] rList = new string[3];
                rList[0] = BudgetMasterId;// ViewData["BudgetId"].ToString();
                rList[1] = BudgetMasterCode;// ViewData["BudgetCode"].ToString();
                rList[2] = li_ReturnValue.ToString();// ViewData["SaveResult"].ToString();
                System.Web.Script.Serialization.JavaScriptSerializer se = new System.Web.Script.Serialization.JavaScriptSerializer();
                string result = se.Serialize(rList);
                return result;
            }
            catch
            {
                ViewData["SaveResult"] = 0;
                //return PartialView("GridData");
                return "0";
            }

            //return li_ReturnValue.ToString();
        }
コード例 #55
0
        public static void sendTodayReport()
        {
            // TODO: call LocalDBInterface.getProductSoldToday()
            // parse Product id + number of stock sold today
            // convert to JSON string
            // make a post request, data: "content=" + jsonstring
            List<Product> todayReport = LocalDBInterface.getProductSoldToday();
            List<productDataToSend> finalReport = new List<productDataToSend>();
            for (int i = 0; i < todayReport.Count; i++)
            {
                finalReport.Add(new productDataToSend{itemId=todayReport.ElementAt(i).getBarcode(),num=todayReport.ElementAt(i).getNumberSoldToday()});
            }
            if (todayReport.Count == 0) return;
            dataSender dataSend = new dataSender();
            dataSend.storeId = "46912";
            dataSend.data = finalReport;
            dataSend.time = DateTime.Now.ToString();
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            //string sJSON = oSerializer.Serialize(finalReport);
            string sJSON = oSerializer.Serialize(dataSend);

            PostSubmitter postReq = new PostSubmitter();
            postReq.Url = HQ_updateURL;
            postReq.PostItems.Add("", sJSON);
            try
            {
                string result = postReq.Post();
            }
            catch { };
            // update again

            //HTTPGet req = new HTTPGet();
            //string reqString = HQ_updateURL + "?id=11001&from=0&to=100";
            //req.Request(reqString);
            //Console.WriteLine(req.StatusLine);
            //Console.WriteLine(req.ResponseTime);

            //LocalDBInterface.reset();
            HTTPGet req = new HTTPGet();
            List<Product> listP = new List<Product>();
            string syncURL = "http://cegmarket.appspot.com/store/update?id=46912&";
            int start = 0, end = 10000;

            while (true)
            {
                string fromString = "from=";
                string toString = "to=";
                fromString = fromString + start.ToString() + "&";
                toString = toString + end.ToString();
                req.Request(syncURL+fromString+toString);
                if (req.StatusCode == 204) break;
                start = end;
                end = end + 10000;
                Console.WriteLine(req.StatusLine);
                Console.WriteLine(req.ResponseTime);
                //Json.JsonArray data = JsonParser.Deserialize(req.ResponseBody);
                //System.Collections.IEnumerator ite = data.GetEnumerator();
                string jsonString = req.ResponseBody;
                jsonString = jsonString.Replace("id", "barcode");
                jsonString = jsonString.Replace("brand", "manufacturer");
                jsonString = jsonString.Replace("transistNum", "number_in_stock");
                jsonString = jsonString.Replace("transistPrice", "price");

                dynamic deserializedProduct = (List<Product>)JsonConvert.DeserializeObject<List<Product>>(jsonString);
                listP.AddRange(deserializedProduct);
            }
            LocalDBInterface.addListProduct(listP);

            /* HTTPPost example
            PostSubmitter post = new PostSubmitter();
            //post.Url = "http://ec2-50-17-68-237.compute-1.amazonaws.com/2102/post/14";
            post.Url = "http://3B.cegmarket.appspot.com/store/update?id=11001&from=&to";
            post.PostItems.Add("content", sJSON);
            //post.PostItems.Add("rel_code", "1102");
            //post.PostItems.Add("FREE_TEXT", "c# jobs");
            //post.PostItems.Add("SEARCH", "");
            post.Type = PostSubmitter.PostTypeEnum.Post;

            string result = post.Post();
            */

            // TODO:
        }
コード例 #56
0
ファイル: Ajax.aspx.cs プロジェクト: Jristy1989/Husbandry
 /// <summary>
 /// 内部方法:将对象序列化为JSON格式
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 private static string JsonSerializer(object obj)
 {
     var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
     return jss.Serialize(obj);
 }
コード例 #57
0
    /// <summary>
    /// This method creates a Session for an outgoing call or message.
    /// </summary>
    private void CreateSession()
    {
        try
        {
            CreateSessionClass createSessionData = new CreateSessionClass();
            createSessionData.numberToDial = txtNumberToDial.Text.ToString();
            if (lstTemplate.SelectedValue != "")
                createSessionData.feature = lstTemplate.SelectedValue.ToString();
            else
                createSessionData.feature = string.Empty;
            createSessionData.messageToPlay = txtMessageToPlay.Text.ToString();
            createSessionData.featurenumber = txtNumberForFeature.Text.ToString();
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
                        new System.Web.Script.Serialization.JavaScriptSerializer();

            string requestParams = oSerializer.Serialize(createSessionData);
            string createSessionResponse;
            HttpWebRequest createSessionRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + "/rest/1/Sessions");
            createSessionRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);

            createSessionRequestObject.Method = "POST";
            createSessionRequestObject.ContentType = "application/json";
            createSessionRequestObject.Accept = "application/json";

            UTF8Encoding encoding = new UTF8Encoding();
            byte[] postBytes = encoding.GetBytes(requestParams);
            createSessionRequestObject.ContentLength = postBytes.Length;

            Stream postStream = createSessionRequestObject.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            HttpWebResponse createSessionResponseObject = (HttpWebResponse)createSessionRequestObject.GetResponse();
            using (StreamReader createSessionResponseStream = new StreamReader(createSessionResponseObject.GetResponseStream()))
            {
                createSessionResponse = createSessionResponseStream.ReadToEnd();
                if (!string.IsNullOrEmpty(createSessionResponse))
                {
                    JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                    CreateSessionResponse deserializedJsonObj = (CreateSessionResponse)deserializeJsonObject.Deserialize(createSessionResponse, typeof(CreateSessionResponse));
                    if (null != deserializedJsonObj)
                    {
                        lblSessionId.Text = deserializedJsonObj.id.ToString();
                        NameValueCollection displayParam = new NameValueCollection();
                        displayParam.Add("id", deserializedJsonObj.id);
                        displayParam.Add("success", deserializedJsonObj.success.ToString());
                        this.DrawPanelForSuccess(pnlCreateSession, displayParam, string.Empty);
                    }
                    else
                    {
                        this.DrawPanelForFailure(pnlCreateSession, "Got response but not able to deserialize json" + createSessionResponse);
                    }
                }
                else
                {
                    this.DrawPanelForFailure(pnlCreateSession, "Success response but with empty ad");
                }

                createSessionResponseStream.Close();
            }
        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }

            this.DrawPanelForFailure(pnlCreateSession, errorResponse + Environment.NewLine + we.ToString());
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(pnlCreateSession, ex.ToString());
        }
    }
コード例 #58
0
 public static string ToJSON(this object o)
 {
     var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     return oSerializer.Serialize(o);
 }
コード例 #59
0
        public static string FillGrid(int PageNumber, int PageSize, string filter)
        {
            if (HttpContext.Current.Session["UserName"] == null)
            {
                return "Error: You are not logged-in.";
            }

            DBClass db = new DBClass("SCM");
            db.Con.Open();
            if (String.IsNullOrEmpty(filter))
                db.Com.CommandText = "SELECT [id] ,[description] FROM [costsetupItemMainhead] ORDER BY [id]";
            else
                db.Com.CommandText = "SELECT [id] ,[description] FROM [costsetupItemMainhead] WHERE [id] LIKE '%" + filter + "%' OR [description] LIKE '%" + filter + "%' ORDER BY [id] ";
            SqlDataAdapter da = new SqlDataAdapter(db.Com);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataTable paggedtable = new DataTable();
            paggedtable = dt.Clone();
            int initial = (PageNumber - 1) * PageSize + 1;
            int last = initial + PageSize;

            for (int i = initial - 1; i < last - 1; i++)
            {
                if (i >= dt.Rows.Count)
                {
                    break;
                }
                paggedtable.ImportRow(dt.Rows[i]);
            }

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in paggedtable.Rows)
            {
                row = new Dictionary<String, Object>();

                foreach (DataColumn col in paggedtable.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);

                }

                rows.Add(row);
            }

            db.Con.Close();
            db = null;
            return String.Format("{{\"total\":{0},\"rows\":{1}}}", dt.Rows.Count, serializer.Serialize(rows));
        }
コード例 #60
0
ファイル: VoucherController.cs プロジェクト: khwwas/SCMS
        public ActionResult VoucherEntry(String VoucherId)
        {
            DALVoucherEntry objDalVoucherEntry = new DALVoucherEntry();

            var VoucherTypes = new DALVoucherType().GetAllData();
            var Locations = new DALLocation().PopulateData();
            var Voucher = new DALVoucherEntry().GetAllMasterRecords();

            ViewData["ddl_VoucherType"] = new SelectList(VoucherTypes, "VchrType_Id", "VchrType_Title", Session["VoucherTypeForVoucherEntry"]);
            var ChartOfAccounts = new DALChartOfAccount().GetChartOfAccountForDropDown(1, "''");
            string ChartOfAccountCodes = "";
            foreach (SETUP_ChartOfAccount COA in ChartOfAccounts)
            {
                if (ChartOfAccountCodes.Length > 0)
                {
                    ChartOfAccountCodes += "|" + COA.ChrtAcc_Id + ":" + COA.ChrtAcc_Title;
                }
                else
                {
                    ChartOfAccountCodes += COA.ChrtAcc_Id + ":" + COA.ChrtAcc_Title;
                }
            }
            ViewData["ChartOfAccountCodesWithTitles"] = ChartOfAccountCodes;
            SETUP_ChartOfAccount SelectChartOfAccount = new SETUP_ChartOfAccount();
            SelectChartOfAccount.ChrtAcc_Id = "0";
            SelectChartOfAccount.ChrtAcc_Code = "";
            ChartOfAccounts.Insert(0, SelectChartOfAccount);
            ViewData["ChartOfAccounts"] = ChartOfAccounts;
            ViewData["ddl_Account"] = new SelectList(ChartOfAccounts, "ChrtAcc_Id", "ChrtAcc_Title", "");
            var NarrationList = new DALVoucherTypeNarration().GetAllData().ToList();
            string[] nList = new string[NarrationList.Count];
            if (NarrationList != null && NarrationList.Count > 0)
            {
                for (int index = 0; index < NarrationList.Count; index++)
                {
                    nList[index] = NarrationList[index].VchrTypeNarr_Title;
                }
                System.Web.Script.Serialization.JavaScriptSerializer se = new System.Web.Script.Serialization.JavaScriptSerializer();
                ViewData["Narrations"] = se.Serialize(nList);
            }
            ViewData["ddl_Location"] = new SelectList(Locations, "Loc_Id", "Loc_Title", Session["LocationIdForVoucherEntry"]);
            if (!String.IsNullOrEmpty(VoucherId))
            {
                SetVoucherEntryToEdit(VoucherId);
            }
            else
            {
                ViewData["VoucherCode"] = "[Auto]";
                ViewData["CurrentDate"] = DateTime.Now.ToString("MM/dd/yyyy");
            }
            Session.Remove("VoucherTypeForVoucherEntry");
            Session.Remove("LocationIdForVoucherEntry");
            return View();
        }