Esempio n. 1
0
        public void ThenISeeTheActiveDistricts(int expectedDistrict)
        {
            var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<ArrayList>(_theResponse);
            int count = json.Count;

            Assert.That(count, Is.AtLeast(expectedDistrict));
        }
Esempio n. 2
0
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(_webAPIUrl);

                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Sale jsonObj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Sale>(txtSalesJSONInput.Text);
                var response = client.PostAsJsonAsync("api/sales", jsonObj).Result;

                if (response.IsSuccessStatusCode)
                {
                    lblMessage.Content = "Sale Added Successfully.";
                    BindSalesList();
                }
                else
                {
                    lblMessage.Content = "Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase;
                }
            }
            catch (ArgumentException ex)
            {
                lblMessage.Content = ex.Message;
            }
            catch (Exception ex)
            {
                lblMessage.Content = ex.Message;
            }
        }
        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));
        }
        public void ThenISeePrimaryapplication_Metainfo_NameContains(string expectedname)
        {
            var dict =
                new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, dynamic>>(
                    _theResponse);
            int count = dict["recordCount"];
            if (count == 1)
            {
                _name = dict["records"][0]["primaryApplication"]["metaInfo"]["name"];
            }
            else
            {
                int i = 0;
                for (i = 0; i <= count - 1; i++)
                {
                    if (dict["records"][i]["primaryApplication"]["metaInfo"]["name"] == expectedname)
                    {
                        _name = dict["records"][i]["primaryApplication"]["metaInfo"]["name"];
                        break;
                    }

                }
            }
            Assert.AreEqual(expectedname, _name);
        }
Esempio n. 5
0
        //public List<DataRow> databasecall(string username)
        //public object databasecall(string username)
        public string databasecall(string username)
        {
            var con = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            SqlConnection mycon = new SqlConnection(con);

            try
            {

                DataTable dt = new DataTable();
                SqlCommand cmd = new SqlCommand("Select * from Demo where NAME=@NAME", mycon);
                cmd.Parameters.AddWithValue("@NAME", "hunny");
                mycon.Open();
                SqlDataReader DR1 = cmd.ExecuteReader();
                {
                    if (DR1.HasRows)
                        dt.Load(DR1);
                }
                //return "success";
               // string result = DataTableToJSON(dt);
               // return DatatableToDictionary(dt, "hunny");
               // return DataTableToJSON(dt).ToString();

                //calling datatable to json method

                return DataTableToJsonObj(dt);

                //converting it to  list
                List<DataRow> list = new List<DataRow>();
                foreach (DataRow dr in dt.Rows)
                {
                    list.Add(dr);
                }
                //converting it to  list

                //return list;

                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);
                ////return dt.ToString();

            }
            catch (Exception e)
            {
                // cmd.ExecuteScalar();
                mycon.Close();
                //return null;
                return "unsuccessful";
            }
        }
Esempio n. 6
0
        public static Quova GetLocationResult(string fullURL)
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

              // Create the web request
              HttpWebRequest request = WebRequest.Create(fullURL) as HttpWebRequest;

              // Get response
              string json;
              using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
              {
            json = DeserializeResponse(response.GetResponseStream());
              }

              Quova quovaResult = null;
              try
              {
            quovaResult = serializer.Deserialize<Quova>(json);
              }
              catch
              {
            //do nothing
              }

              return quovaResult;
        }
Esempio n. 7
0
        public void GetAccessToken()
        {
            var token = GetToken();

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

            this.Context.Response.ContentType = "application/json; charset=utf-8";
            this.Context.Response.Write(serializer.Serialize(new { tokens = token.Result }));
        }
Esempio n. 8
0
        /// <summary>
        /// Queue up a TFS build for a specific build id.
        /// </summary>
        /// <param name="buildId">The TFS build id of that target build to invoke.</param>
        /// <returns></returns>
        public async Task <Response> QueueBuild(string buildId)
        {
            dynamic obj = new
            {
                definition = new
                {
                    id   = buildId,
                    type = "build"
                }
            };


            if (!string.IsNullOrEmpty(sourceBranch))
            {
                obj = new
                {
                    obj,
                    sourceBranch = sourceBranch
                                   //"sourceBranch": "refs/heads/master"
                };
            }

            // Covert the object over to JSON
            System.Web.Script.Serialization.JavaScriptSerializer js =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            var httpArgsContent = new StringContent(js.Serialize(obj), Encoding.UTF8, "application/json");

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                // If we need Authentication
                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passWord))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                        "Basic",
                        Convert.ToBase64String(Encoding.ASCII.GetBytes($"{this.userName}:{this.passWord}")));
                }

                using (HttpResponseMessage response = client.PostAsync(GetQueueBuildRequestUri(), httpArgsContent).Result)
                {
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(responseBody))
                    {
                        // Convert the object over to a friendly C# object
                        Response buildResponseObject = js.Deserialize <Response>(responseBody);
                        Console.WriteLine(responseBody);

                        return(buildResponseObject);
                    }
                }
            }
            return(null);
        }
Esempio n. 9
0
        public static IEnumerable <backend.Class.IBooksWithInterface> decodejason(string json)// for testing async not working in nunit
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();

            backend.Class.Books books = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <backend.Class.Books>(json);

            return(books.books);
            // note a list is a enumrable just run command books.books.AsEnumerable();
        }
Esempio n. 10
0
        public string getPlanAccountItem(string itemid)
        {
            log.Info("get plan account item by id=" + itemid);
            System.Web.Script.Serialization.JavaScriptSerializer objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string itemJson = objSerializer.Serialize(service.getPlanAccountItem(itemid));

            log.Info("plan account item  info=" + itemJson);
            return(itemJson);
        }
        public static string PaisesDataBind()
        {
            List <Entities.Pais> list = new List <Pais>();

            Business.Paises bo = new Business.Paises();
            list = bo.Combo();
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            return(js.Serialize(list));
        }
Esempio n. 12
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");
            }
        }
Esempio n. 13
0
        protected dynamic RestHandler(string methord, string urlSuffix, object param, bool isJsonResponse)              //,bool validResponseCode){
        {
            string url = string.Format(BaseURL, _orgId);

            url = url + urlSuffix;
            bool isQuerry = false;

            if (methord == "GET" && param  is string)
            {
                url     += param;
                isQuerry = true;
            }
            System.Net.WebRequest request = WebRequest.Create(url);
            request.Method = methord;
            byte[] credentialBuffer = new UTF8Encoding().GetBytes(_apiKey + ":" + _authToken);
            request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
            request.PreAuthenticate          = true;
            request.Timeout = Timeout;
            log.Info("Request " + methord + "  " + url);

            if (param != null & !isQuerry)
            {
                request.ContentType = "application/json";

                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(param);
                    log.Info("Request Json " + json);

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            // Get the response.
            HttpWebResponse response     = (HttpWebResponse)request.GetResponse();
            int             responseCode = (int)response.StatusCode;

            log.Info("response " + response.ResponseUri + "  " + responseCode);

            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        var JsonResponse = reader.ReadToEnd();
                        if (isJsonResponse)
                        {
                            return(new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <dynamic>(JsonResponse));
                        }
                    }
                }
            }

            return(new {});
        }
        public static string EstadosDataBind(string claPais)
        {
            List <Entities.Estado> list = new List <Estado>();

            Business.Estados bo = new Business.Estados();
            list = bo.Combo(0);
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            return(js.Serialize(list));
        }
Esempio n. 15
0
        /// <summary>
        /// 生成JSON字符串
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public string ToJson(Dictionary <string, string> dic)
        {
            System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
            arrayList.Add(dic); //ArrayList集合中添加键值

            return(javaScriptSerializer.Serialize(arrayList));
        }
Esempio n. 16
0
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <returns></returns>

        private void Down(HttpContext context)
        {
            ZipHelper            zip       = new ZipHelper();
            JsonModel            jsonModel = null;
            JavaScriptSerializer jss       = new System.Web.Script.Serialization.JavaScriptSerializer();

            string ids     = context.Request.Form["DownID"].SafeToString();
            string ZipUrl  = context.Server.MapPath(ConfigHelper.GetConfigString("ZipUrl")) + "/" + DateTime.Now.Ticks;
            string DownUrl = ConfigHelper.GetConfigString("DownUrl");
            string result  = "0";

            try
            {
                string[] idarry = ids.TrimEnd(',').Split(',');
                FileHelper.CreateDirectory(ZipUrl);
                for (int i = 0; i < idarry.Length; i++)
                {
                    #region 文件移动
                    JsonModel  model    = Bll.GetEntityById(int.Parse(idarry[i]));
                    MyResource resource = (MyResource)(model.retData);
                    string     FileUrl  = resource.FileUrl;
                    if (resource.postfix == "")
                    {
                        FileHelper.CopyFolder(context.Server.MapPath(FileUrl), ZipUrl);
                    }
                    else
                    {
                        FileHelper.CopyTo(context.Server.MapPath(FileUrl), ZipUrl + FileUrl.Substring(FileUrl.LastIndexOf("/")));
                    }
                    #endregion
                }
                string ZipName = "/下载文件" + DateTime.Now.Ticks + ".rar";
                //文件打包
                SharpZip.PackFiles(context.Server.MapPath(ConfigHelper.GetConfigString("ZipUrl")) + ZipName, ZipUrl);

                jsonModel = new JsonModel()
                {
                    errNum  = 0,
                    errMsg  = "",
                    retData = DownUrl + "\\" + ZipName //+ ".rar"
                };
            }
            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();
        }
Esempio n. 17
0
        public string GetFormContent()
        {
            Layout layout = LayoutCollection.GetLayOut("4").SingleOrDefault();

            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            string s = js.Serialize(layout.NavigationUrl);

            return(s);
        }
Esempio n. 18
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);
                }
            }
        }
Esempio n. 19
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)));
        }
Esempio n. 20
0
        //FacilityMap
        //public ActionResult FacilityMap()
        //{
        //    ViewData["datasource"] = Syncfusion_LocationData.GetSyncfusionLocationData();
        //    return View();
        //}
        public ActionResult ConvertDataTabletoString()
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            mascisEntities   context = new mascisEntities();
            var              x       = context.A_Facilities.AsNoTracking().ToList();
            List <MapMarker> syncfusionLocationData = new List <MapMarker>();

            foreach (var n in x)
            {
                var district = context.A_District.FirstOrDefault(e => e.District_Code == n.DistrrictCode);
                var DZ       = context.A_DeliveryZone.FirstOrDefault(e => e.ZoneCode == n.DeliveryZoneCode);
                var CP       = context.A_ImplimentingPartners.FirstOrDefault(e => e.ImplimentingPartnerCode == n.ComprehensiveImplimentingPartnerCode);
                var CDC      = context.A_CDCRegion.FirstOrDefault(e => e.CDCRegionId == n.CDCRegionId);
                var CT       = context.A_ClientType.FirstOrDefault(e => e.client_type_code == n.client_type_code);
                var LOC      = context.A_Facility_Level_Of_Care.FirstOrDefault(e => e.level_of_care_code == n.level_of_care);

                LocationData msyncfusionLocationData = new LocationData()
                {
                    Name      = n.Facility,
                    Latitude  = Convert.ToDouble(n.Latititude),
                    Longitude = Convert.ToDouble(n.Longtitude),
                };
                if (district != null)
                {
                    msyncfusionLocationData.District = district.District_Name;
                }
                if (LOC != null)
                {
                    msyncfusionLocationData.LevelOfCare = LOC.level_of_care;
                }
                if (CT != null)
                {
                    msyncfusionLocationData.CleintType = CT.client_type_desc;
                }
                if (CDC != null)
                {
                    msyncfusionLocationData.CDCRegion = CDC.CDCRegion;
                }
                if (CP != null)
                {
                    msyncfusionLocationData.IP = CP.ImplementingPartnerDescription;
                }
                if (DZ != null)
                {
                    msyncfusionLocationData.Sector = DZ.ZoneDescription;
                }
                syncfusionLocationData.Add(msyncfusionLocationData);
            }
            //List<MapMarker> syncfusionLocationData = new List<MapMarker>
            //{
            //    new LocationData {Name = "Chennai", Country = "India", Latitude =13.0839 , Longitude = 80.27 , Description = "Syncfusion's branch office is located in AnnaNagar, Chennai", Address ="EYMARD Complex AJ 217 4th Avenue Shanthi Colony Anna Nagar Chennai-40 India" },
            //    new LocationData {Name = "North Carolina", Country = "United States", Latitude =35.5 , Longitude = -80 , Description = "Syncfusion's corporate office is located in Research Triangle Park North Carolina", Address ="Company Headquarters 2501 Aerial Center Parkway Suite 200 Morrisville NC 27560 USA" },
            //};
            // return serializer.Serialize(syncfusionLocationData);
            return(Json(syncfusionLocationData, JsonRequestBehavior.AllowGet));//syncfusionLocationData;
        }
Esempio n. 21
0
        // POST: api/UploadFile
        public async Task <bool> Post(int id = 0)
        {
            bool vResult = false;

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            Dictionary <string, string> vDic = new Dictionary <string, string>();
            //string root = HttpContext.Current.Server.MapPath("~/App_Data");//指定要将文件存入的服务器物理位置
            var vProvider = new MultipartFormDataMemoryStreamProvider();

            try
            {
                // 从流中读取数据
                await Request.Content.ReadAsMultipartAsync(vProvider);

                foreach (var key in vProvider.FormData.AllKeys)
                {//接收FormData
                    vDic.Add(key, vProvider.FormData[key]);
                }
                string vJsonStr = vDic["Json"];
                if (vJsonStr != null && vJsonStr != "" && vProvider.FileContents.Count > 0)
                {
                    JavaScriptSerializer vJSC  = new System.Web.Script.Serialization.JavaScriptSerializer();
                    UploadFileStruct     value = vJSC.Deserialize <UploadFileStruct>(vJsonStr);
                    // 获取流中所有的文件
                    for (int i = 0; i < vProvider.FileContents.Count; i++)
                    {
                        var vFileContent = vProvider.FileContents[i];
                        var vFileInfo    = value.Files[i];
                        var vStream      = await vFileContent.ReadAsStreamAsync();

                        byte[] vBody = new byte[vStream.Length];
                        vStream.Read(vBody, 0, vBody.Length);
                        FilesManage vFilesManage = new FilesManage();
                        vResult = vFilesManage.AddFile(value.UsersAuthor.UserID, vFileInfo.AreaCode, vFileInfo.UnitName,
                                                       vFileInfo.FileName, vFileInfo.Author, vBody);
                        if (!vResult)
                        {
                            break;
                        }
                        else
                        {
                            UserOperateLog vUserOperateLog = new UserOperateLog();
                            vUserOperateLog.WriteLog(value.UsersAuthor.UserID, value.UsersAuthor.UserName, string.Format("上传文件,文件名[{0}]", vFileInfo.FileName));
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            return(vResult);
        }
Esempio n. 22
0
        /// <summary>
        /// 保存客户端状态
        /// </summary>
        /// <param name="clientState"></param>
        ///<remarks></remarks>
        protected override string SaveClientState()
        {
            BulidArray(this.items);

            System.Web.Script.Serialization.JavaScriptSerializer js = JSONSerializerFactory.GetJavaScriptSerializer();

            string fsSerialize = js.Serialize(nodeSelectedArray);

            return(fsSerialize);
        }
Esempio n. 23
0
        public string GetListAllMusic(int startIndex, int pageSize, string sortExpression)
        {
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            Dictionary <string, object> result    = new Dictionary <string, object>();
            MusicCollection             MusicList = MusicCollection.GetMusicClipCollection();

            result["data"]  = MusicList.GetSegment(startIndex * pageSize, pageSize, sortExpression);
            result["total"] = MusicList.Count;
            return(js.Serialize(result));
        }
Esempio n. 24
0
 public static string GetEntityForEdition(string id)
 {
     System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
     Business.Campus bo     = new Business.Campus();
     Entities.Campus entity = new Entities.Campus();
     entity.ID = Utils.IsNull(id, 0);
     entity.SetFromDataSource(true);
     bo.PrepareEntityForEdition(entity);
     return(js.Serialize(entity));
 }
Esempio n. 25
0
        protected string JsonString <T>(T returnObj) where T : class
        {
            System.Web.Script.Serialization.JavaScriptSerializer objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            StringBuilder sb = new StringBuilder();

            //將回傳的資料寫入Reponse中
            string _resultStr = objSerializer.Serialize(returnObj);

            return(_resultStr);
        }
Esempio n. 26
0
 /// <summary>
 /// Json转换为List
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static IList <T> ToListModel <T>(string obj)
 {
     try
     {
         System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
         IList <T> p1 = jss.Deserialize <IList <T> >(obj);
         return(p1);
     }
     catch { return(null); }
 }
Esempio n. 27
0
        /// <summary>
        /// 把对象转成json字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string SerializeToJson(object o)
        {
            StringBuilder sb = new StringBuilder();

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

            json.Serialize(o, sb);

            return(sb.ToString());
        }
Esempio n. 28
0
 /// <summary>
 /// Json转换为Model
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static T ToModel <T>(string obj)
 {
     try
     {
         System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
         T p1 = jss.Deserialize <T>(obj);
         return(p1);
     }
     catch { return(default(T)); }
 }
Esempio n. 29
0
    public static string restfulJSON(string relues, string errValue, string inputId)
    {
        System.Web.Script.Serialization.JavaScriptSerializer   jss  = new System.Web.Script.Serialization.JavaScriptSerializer();
        System.Collections.Generic.Dictionary <string, string> drow = new System.Collections.Generic.Dictionary <string, string>();

        drow.Add("status", relues);
        drow.Add("msg", errValue);
        drow.Add("relues", inputId);
        return(jss.Serialize(drow));
    }
Esempio n. 30
0
        public UserInfo Login(string UserName, string Password)
        {
            string vUrl                    = string.Format("{0}/Api/Login", m_RemotingServerAddress);
            string vPostData               = string.Format("UserName={0}&Password={1}", UserName, Password);
            string vResult                 = HttpGet(vUrl, vPostData);
            JavaScriptSerializer vJSC      = new System.Web.Script.Serialization.JavaScriptSerializer();
            UserInfo             vUserInfo = vJSC.Deserialize <UserInfo>(vResult);

            return(vUserInfo);
        }
Esempio n. 31
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();
        }
Esempio n. 32
0
        /// <summary>
        /// Output the replay as json with minimal post processing.
        /// No removal of duplicate data, no joining of new and updated data.
        /// </summary>
        /// <param name="replay"></param>
        /// <returns></returns>
        public string SerializeRaw(Replay replay)
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            serializer.RegisterConverters(new List <JavaScriptConverter>()
            {
            });

            //Dictionary<int, ActorStateJson> actorStates = new Dictionary<int, ActorStateJson>();
            var frameJson = new List <string>();

            foreach (var f in replay.Frames.Where(x => x.ActorStates.Count > 0))
            {
                List <UInt32>         deletedActorStateIds = new List <UInt32>();
                List <ActorStateJson> newActorStates       = new List <ActorStateJson>();
                List <ActorStateJson> updatedActorStates   = new List <ActorStateJson>();

                Dictionary <int, ActorStateJson> actor = new Dictionary <int, ActorStateJson>();

                foreach (var a in f.ActorStates.Where(x => x.State == ActorStateState.Deleted))
                {
                    deletedActorStateIds.Add(a.Id);
                }

                foreach (var a in f.ActorStates.Where(x => x.State == ActorStateState.New))
                {
                    var actorState = new ActorStateJson();
                    actorState.Id              = a.Id;
                    actorState.UnknownBit      = a.Unknown1;
                    actorState.TypeName        = a.TypeName;
                    actorState.ClassName       = a.ClassName;
                    actorState.InitialPosition = a.Position;
                    actorState.Properties      = new List <ActorStateProperty>();
                    newActorStates.Add(actorState);
                }

                foreach (var a in f.ActorStates.Where(x => x.State == ActorStateState.Existing))
                {
                    var actorState = new ActorStateJson();
                    actorState.Id         = a.Id;
                    actorState.Properties = new List <ActorStateProperty>();

                    actorState.Properties = a.Properties.Select(p => new ActorStateProperty {
                        Name = p.PropertyName, Data = p.Data
                    }).ToList();

                    updatedActorStates.Add(actorState);
                }

                // Serializing at each frame to make sure we capture the state at each step.
                // Otherwise, since we're not cloning objects at each step, we'd serialize only the most recent set of data
                frameJson.Add(serializer.Serialize(new { Time = f.Time, DeletedActorIds = deletedActorStateIds, NewActors = newActorStates, UpdatedActors = updatedActorStates }));
            }
            return("[" + string.Join(",", frameJson) + "]");
        }
        public bool Post_To_HubSpot_FormsAPI(int intPortalID, string strFormGUID, Dictionary <string, string> dictFormValues, string strHubSpotUTK, string strIpAddress, string strPageTitle, string strPageURL, ref string strMessage)
        {
            // Build Endpoint URL
            string strEndpointURL = string.Format("https://forms.hubspot.com/uploads/form/v2/{0}/{1}", intPortalID, strFormGUID);

            // Setup HS Context Object
            Dictionary <string, string> hsContext = new Dictionary <string, string>();

            hsContext.Add("hutk", strHubSpotUTK);
            hsContext.Add("ipAddress", strIpAddress);
            hsContext.Add("pageUrl", strPageURL);
            hsContext.Add("pageName", strPageTitle);

            // Serialize HS Context to JSON (string)
            System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
            string strHubSpotContextJSON = json.Serialize(hsContext);

            // Create string with post data
            string strPostData = "";

            // Add dictionary values
            foreach (var d in dictFormValues)
            {
                strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&";
            }

            // Append HS Context JSON
            strPostData += "hs_context=" + Server.UrlEncode(strHubSpotContextJSON);

            // Create web request object
            System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strEndpointURL);

            // Set headers for POST
            r.Method        = "POST";
            r.ContentType   = "application/x-www-form-urlencoded";
            r.ContentLength = strPostData.Length;
            r.KeepAlive     = false;

            // POST data to endpoint
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(r.GetRequestStream()))
            {
                try
                {
                    sw.Write(strPostData);
                }
                catch (Exception ex)
                {
                    // POST Request Failed
                    strMessage = ex.Message;
                    return(false);
                }
            }

            return(true); //POST Succeeded
        }
Esempio n. 34
0
        public void PassRatesBroadband()
        {
            using (NetaServiceClient proxy = new NetaServiceClient())
            {
                allBBandPRItems = proxy.MyView();
                var serilizer = new System.Web.Script.Serialization.JavaScriptSerializer();
            }

            DataTable dt = new DataTable();

            dt = ConvertToDatatable(allBBandPRItems);


            StringBuilder str = new StringBuilder();

            str.Append(@"<script type = 'text/javascript'>
                      google.load('visualization', '1', { packages: ['corechart']});
            
                      function drawVisualization() {
                      var data = google.visualization.arrayToDataTable([
                       ['SchoolName','PercentPassed','AverageSpeed'],");

            int count = dt.Rows.Count - 1;

            for (int i = 0; i <= count; i++)
            {
                if (count == i)
                {
                    str.Append("['"
                               + dt.Rows[i]["SchoolName"].ToString()
                               + "',"
                               + dt.Rows[i]["PercentPassed"].ToString()
                               + ","
                               + dt.Rows[i]["AverageSpeed"].ToString()
                               + "]]);");
                }
                else
                {
                    str.Append("['"
                               + dt.Rows[i]["SchoolName"].ToString()
                               + "',"
                               + dt.Rows[i]["PercentPassed"].ToString()
                               + ","
                               + dt.Rows[i]["AverageSpeed"].ToString()
                               + "],");
                }
            }


            str.Append("var options = {vAxes: {0: { title: 'Percent', format: ''},1: { title: 'Average Speed (mbps)', format: '##'}},hAxis: { title: 'School Name', format: ''},seriesType: 'bars',series:{ 0:{ type: 'bars', targetAxisIndex: 0}, 1: { type: 'line', targetAxisIndex: 1}}, };");

            str.Append(" var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));  chart.draw(data, options); } google.setOnLoadCallback(drawVisualization);");

            bbprScripts.Text = str.ToString() + "</script>";
        }//PassRatesBroadband
Esempio n. 35
0
    //request获取所有参数
    public MyTable set <MyTable>(MyTable itable, string pre1)
        where MyTable : ITableImplement, new()
    {
        int count = 0;
        List <AttributeItem> list1 = itable.af_GetAttributes();

        if (list1.Count == 0)
        {
            MyTable itable2 = new MyTable(); itable2.LoadAllAttributes(true);
            list1 = itable2.af_GetAttributes();
        }
        foreach (AttributeItem attr1 in list1)
        {
            if (noAttrs.Contains(attr1))
            {
                continue;
            }
            string f1 = Request.QueryString[pre1 + attr1.FieldName];
            if (!string.IsNullOrEmpty(f1) && (isNotContainsZero && f1 != "0"))
            {
                count++;
                itable.SetValue(attr1, f1);
            }
            else
            {
                itable.SetInitialized(attr1, false);
            }
        }
        if (count == 0)//可能是post对象进来,是否需要处理
        {
            string js1 = null;
            try
            {
                js1 = getString();
                if (js1.StartsWith("{"))
                {
                    JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    //PostData = javaScriptSerializer.Deserialize<PostData>(js1);//字符串反序列化
                    //string email = Convert.ToString(Request.Form["email"]);
                    Response.Write("{\"code\":444, \"message\":\"老师提示请修改前端,因前端postAjax传参方式为json字符串模式\r\n\"");
                    Response.Write(js1);
                    Response.End();
                }
                else
                {
                    //string email = Convert.ToString(Request.Form["email"]);
                    //Response.Write("前端传参方式为非json字符串模式\r\n");
                    //Response.Write(js1);
                    //Response.End();
                }
            }
            catch (Exception ex1) { Response.Write("{\"code\":444, \"message\":\"" + js1 + "==异常==" + ex1.Message + "\""); Response.End(); }
        }
        return(itable);
    }
        public string TranslateGoogle(string text, string fromCulture, string toCulture)
        {
            fromCulture = fromCulture.ToLower();
            toCulture = toCulture.ToLower();

            // normalize the culture in case something like en-us was passed
            // retrieve only en since Google doesn't support sub-locales
            string[] tokens = fromCulture.Split('-');
            if (tokens.Length > 1)
                fromCulture = tokens[0];

            // normalize ToCulture
            tokens = toCulture.Split('-');
            if (tokens.Length > 1)
                toCulture = tokens[0];

            string url = string.Format(@"http://translate.google.com/translate_a/t?client=j&text={0}&hl=en&sl={1}&tl={2}",
                                       HttpUtility.UrlEncode(text), fromCulture, toCulture);

            // Retrieve Translation with HTTP GET call
            string html = null;
            try
            {
                WebClient web = new WebClient();

                // MUST add a known browser user agent or else response encoding doen't return UTF-8 (WTF Google?)
                web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0");
                web.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");

                // Make sure we have response encoding to UTF-8
                web.Encoding = Encoding.UTF8;
                html = web.DownloadString(url);
            }
            catch (Exception ex)
            {
                //this.ErrorMessage = Westwind.Globalization.Resources.Resources.ConnectionFailed + ": " +
                //                    ex.GetBaseException().Message;
                //return null;
            }

            // Extract out trans":"...[Extracted]...","from the JSON string
            string result = Regex.Match(html, "trans\":(\".*?\"),\"", RegexOptions.IgnoreCase).Groups[1].Value;

            if (string.IsNullOrEmpty(result))
            {
                //this.ErrorMessage = Westwind.Globalization.Resources.Resources.InvalidSearchResult;
                //return null;
            }

            //return WebUtils.DecodeJsString(result);

            // Result is a JavaScript string so we need to deserialize it properly
            JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            return ser.Deserialize(result, typeof(string)) as string;
        }
    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));
    }
Esempio n. 38
0
        private List <GetOverdueApplicationsByInmate> GetOverDueApplicationsByInmates(string HouseName)
        {
            string json = string.Empty;

            DashboardServices.MySQLConnection.MySQLConnection con = new DashboardServices.MySQLConnection.MySQLConnection();
            json = con.GetTableOverDueData(ProcedureConstants.SP_INMATES_OVERDUEAPPLICATIONS, HouseName);
            System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List <GetOverdueApplicationsByInmate> objOverdueInmate            = jsSerializer.Deserialize <List <GetOverdueApplicationsByInmate> >(json);

            return(objOverdueInmate);
        }
Esempio n. 39
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();
    }
        public static string FillExpGrid(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 [AGglCode], [FOglCode], [SDglCode], [COGSglCode] FROM [costsetupOverheadMainheadGLCode] ORDER BY [id]";
            else
                db.Com.CommandText = "SELECT [AGglCode], [FOglCode], [SDglCode], [COGSglCode] FROM [costsetupOverheadMainheadGLCode] where Branchid = '"+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));
        }
 private static Dictionary<string, object> getPushResult(String url, String appKey, String masterSecret, String taskId)
 {
     Dictionary<string, object> param = new Dictionary<string, object>();
     param.Add("action", "getPushMsgResult");
     param.Add("appkey", appKey);
     param.Add("taskId", taskId);
     string sign = createSign(param, masterSecret);
     param.Add("sign", sign);
     string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(param);
     System.Console.WriteLine(json);
     string resp = httpPost(url, json);
     System.Console.WriteLine(resp);
     Dictionary<string, object> result = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, object>>(resp);
     return result;
 }
        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());
            }
        }
 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);
 }
 public MainControl()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     libr = new Library();
     string sJSON;
     System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     System.IO.StreamReader file = new System.IO.StreamReader(@"E:\Registration\Registration\Registration\DataBase.json");
     while ((sJSON = file.ReadLine()) != null)
     {
         Person nana;
         nana = JsonConvert.DeserializeObject<Person>(sJSON);
         libr.Add(nana);
     }
     file.Close();
 }
Esempio n. 45
0
        public List<Models.Contact> GetAll()
        {
            using (var reader = new StreamReader(File.Open(path, FileMode.OpenOrCreate)))
            {
                var data = reader.ReadToEnd();

                if (!String.IsNullOrEmpty(data))
                {
                    System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                    var result = jss.Deserialize<List<Contact>>(data);
                    return result;
                }
            }

            return new List<Contact>();
        }
Esempio n. 46
0
 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);
 }
        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();
            db.Com.CommandText = "SELECT [id] , [Description], MarketingOverhead, VariableExpense FROM [CostsetupItem] " + 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));
        }
 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;
     }
 }
        public static object jsonDeserialize(string json)
        {
            var d = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(json);
            return d;
            /*
                        var settings = new DataContractJsonSerializerSettings
                        {
                            UseSimpleDictionaryFormat = true
                        };
                        var serializer = new DataContractJsonSerializer(typeof(ExpandoObject), settings);
                        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                        {
                            IDictionary<string, object> d = (ExpandoObject)serializer.ReadObject(stream);

                            var e = Expando(d);
                            return e;
                        } */
        }
Esempio n. 50
0
 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);
         }
     }
 }
Esempio n. 51
0
        //Use this one when get the data from database
        public void CheckProductOutStock_API(List<Product> products_OutOfStock)
        {
            if (products_OutOfStock.Count() > 0)
            {

                int j = products_OutOfStock.Count();

                foreach (var product in products_OutOfStock)
                {

                    Console.WriteLine("Total number of products to be marked as hidden :" + j);
                    Console.WriteLine("****************************************************");

                    var shopifyProducts = Shopify_Get("/admin/products.json?handle=" + product.Handle);

                    if (shopifyProducts != "{\"products\":[]}")
                    {

                        Shopify_Product_Loader_ShopifyClass.RootObject jsonObject = null;

                        try
                        {
                            System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();

                            jsonObject = json.Deserialize<Shopify_Product_Loader_ShopifyClass.RootObject>((string)shopifyProducts);

                            foreach (var item in jsonObject.products)
                            {
                                UpdateOutStockProduct(item.id.ToString(), item.variants[0].id.Value.ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            int f = 2;

                        }

                        Thread.Sleep(new TimeSpan(0, 0, 1));
                        j--;
                    }
                }
            }
        }
    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);
    }
Esempio n. 53
0
        /// <summary> Get Klout Score Using Klout WCF Service
        /// </summary>
        private void GetKloutScore()
        {
            string kloutUserId = txtUserId.Text;
              string kloutKey    = txtApplicationId.Text;
              string kloutURL    = Properties.Settings.Default.KloutURL;

              // Construct Klout URL For Request
              kloutURL = kloutURL.Replace("kloutuserid", kloutUserId) + "?key=" + kloutKey;

              //  Construct Klout WCF Web Service Client And Get User's Klout Score
              Service1Client svcClient = new Service1Client();
              string score = svcClient.GetKloutScore(kloutURL);

              // Decode JSON Response
              System.Web.Script.Serialization.JavaScriptSerializer jsSer = new System.Web.Script.Serialization.JavaScriptSerializer();

              // Deserialize Response To A Klout Class
              Klout klScore = jsSer.Deserialize<Klout>(score);

              // Display Klout Score
              lblScore.Text = "Score : " + klScore.Score;
        }
        public ActionResult Create(string jsonContrato, string jsonLaboratorios, string jsonIngenieros)
        {
            if (ModelState.IsValid)
            {
                List<int> listLaboratios = new List<int>();
                List<int> listIngenieros = new List<int>();
                Contrato contrato = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Contrato>(jsonContrato);

                //Obtener los laboratios
                dynamic jObj = JsonConvert.DeserializeObject(jsonLaboratorios);
                foreach (var child in jObj.Laboratorios.Children())
                {
                    //listLaboratios.Add((int)child);
                    contrato.laboratorioCalidad.Add(db.laboratorioCalidad.Find((int)child));
                }

                //inserción del contrato a la DB
                db.Contrato.Add(contrato);
                db.SaveChanges();
                //obtención del id del contrato
                var idContrato = contrato.id;

                //Obtener ingenieros.
                jObj = JsonConvert.DeserializeObject(jsonIngenieros);
                foreach (var child in jObj.Ingenieros.Children())
                {
                    //Creación del ingeniero-contrato.
                    ingenieroContrato ing_contrato = new ingenieroContrato();
                    ing_contrato.idContrato = idContrato;
                    ing_contrato.idIngeniero = (int)child;
                    db.ingenieroContrato.Add(ing_contrato);
                    db.SaveChanges();
                }

            }
            //RedirectToAction("Index", "Contrato");
            return View("Index");
        }
        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);
        }
        public void GetPostsLoggedIn()
        {
            const uint EXPECTED_NUM_POSTS = 3;
            WebSecurity.Setup(w => w.CurrentUserId()).Returns(0);

            var result = Controller.GetPosts("49.246458", "-123.09391") as JsonResult;
            Assert.IsNotNull(result);

            //Convert the result to objects.
            string json = (new JavaScriptSerializer().Serialize(result.Data));
            List<ResultContainerObject> rh = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<ResultContainerObject>>(json);

            uint expectedpostscount = 0;
            foreach (var item in rh)
            {
                Assert.IsFalse(item.Title.Equals("NotSee"));
                if (item.Title.Equals("See"))
                {
                    expectedpostscount++;
                }

            }
            Assert.IsTrue(expectedpostscount == EXPECTED_NUM_POSTS);
        }
Esempio n. 57
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:
        }
    public string GetSearchByKeyword(string keyword, int pageSize, string TokenJSON, string filters, int? userCode)
    {
        int UserCode = userCode == null ? new Base().UserKey : (int)userCode;
        User user = new DataModelEntities().Users.FirstOrDefault(f => f.User_Code == userCode);
        dynamic filterObject = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<dynamic>(filters);

        EbayServiceBL serviceBL = new EbayServiceBL(UserCode);

        FindItemsByKeywordsResponse response = serviceBL.SearchItems(keyword, pageSize, 1, filterObject);
        SearchResult result = response.searchResult;

        if (result == null)
            return null;

        // get all Items Details
        SimpleItemType[] simpleItems = serviceBL.GetMultipleItemsDetails(result);
        List<EbaySearchItem> searchItems = new List<EbaySearchItem>();

        Dictionary<string, int> tokens = (Dictionary<string, int>)Common.Deserialize(TokenJSON, typeof(Dictionary<string, int>));

        string[] mySellerIDs = tokens.Select(t => t.Key).ToArray();

        // Looping through response object for result
        foreach (SearchItem item in result.item)
        {
            SimpleItemType simpleItem = simpleItems.FirstOrDefault(i => i.ItemID == item.itemId);
            if (simpleItem.ReserveMetSpecified == false || simpleItem.ReserveMet == true)
            {
                EbaySearchItem searchItem = new EbaySearchItem();
                string timeLeft = item.sellingStatus.timeLeft, days = string.Empty, temp = string.Empty;

                if (timeLeft.IndexOf('D') != -1)
                    days = timeLeft.Substring(timeLeft.IndexOf('P') + 1, timeLeft.IndexOf('D') - 1) + "d ";
                if (days == "0d ")
                    days = "";

                temp = days + timeLeft.Substring(timeLeft.IndexOf('T') + 1, timeLeft.IndexOf('H') - timeLeft.IndexOf('T') - 1) + "h ";

                if (days == "")
                    timeLeft = temp + timeLeft.Substring(timeLeft.IndexOf('H') + 1, timeLeft.IndexOf('M') - timeLeft.IndexOf('H') - 1) + "m";
                else
                    timeLeft = temp;

                searchItem.ItemID = item.itemId;
                searchItem.Title = item.title;
                searchItem.Price = item.sellingStatus.currentPrice.Value;
                searchItem.TimeRemaining = timeLeft;
                searchItem.ViewURL = item.viewItemURL;
                searchItem.ImageURL = item.galleryURL;
                searchItem.SellerID = simpleItem.Seller.UserID;
                searchItem.TopRatedSeller = simpleItem.Seller.TopRatedSeller;
                searchItem.SellerScore = simpleItem.Seller.PositiveFeedbackPercent;
                searchItem.ConvertedPrice = item.sellingStatus.convertedCurrentPrice.Value;
                searchItem.TotalCost = searchItem.ConvertedPrice;//will be shown on search result

                //We are ignoring Shipping cost for the time being because we dont have solution to get converted shipping cost
                if (item.shippingInfo.shippingServiceCost != null)
                    searchItem.ShippingCost = item.shippingInfo.shippingServiceCost.Value;
                else
                    searchItem.ShippingCost = 0;

                /*If user have selected include shipping in settings shippingcost + price*/
                if (user.Automation_Include_Shipping != null && user.Automation_Include_Shipping == true)
                    searchItem.TotalCostIncludingShipping = searchItem.ShippingCost + searchItem.ConvertedPrice;
                else
                    searchItem.TotalCostIncludingShipping = searchItem.ConvertedPrice;

                if (mySellerIDs.Contains(searchItem.SellerID))
                    searchItem.IsMyProduct = true;
                else
                    searchItem.IsMyProduct = false;

                searchItems.Add(searchItem);
            }
        }

        var data = searchItems.OrderBy(o => o.TotalCostIncludingShipping).ToList();
        return Common.Serialize(data);
    }
        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);
        }
Esempio n. 60
0
 /// <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);
 }