Example #1
0
        public string Codecompletion(string code, int position, int language, int line, int ch)
        {
            Compression.SetCompression();
            JavaScriptSerializer json = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(code))
                return json.Serialize(new List<string>());

            if (language == (int)LanguagesEnum.CSharp)
            {
                return CsharpComplete.Complete(code, position, line, ch);
            }
            else if (language == (int)LanguagesEnum.Java)
            {
                return JavaComplete.Complete(code, position, line, ch);
            }
            else if (language == (int)LanguagesEnum.CPP || language == (int)LanguagesEnum.CPPClang || language == (int)LanguagesEnum.VCPP)
            {
                return VcppComplete.Complete(code, position, line, ch);
            }
            else if (language == (int)LanguagesEnum.Python)
            {
                return PythonComplete.Complete(code, position, line, ch);
            }
            else
            {
                return json.Serialize(new List<string>());
            }
        }
        /// <summary>
        /// Process Request that updates user info given the HttpContext, and returns confirmation message upon successful completion
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            String jsonString;
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            try
            {
                User user = new User
                {
                    FirstName = request.Form["firstName"],
                    LastName = request.Form["lastName"],
                    Gender = request.Form["gender"],
                    PhoneNumber = request.Form["phoneNumber"],
                    Address = request.Form["address"],
                    ZipCode = request.Form["zipCode"],
                    UserName = request.Form["userName"]
                };
                user.UpdateProfile();

                jsonString = serializer.Serialize(new { result = "success" });
            }
            catch (Exception ex)
            {
                jsonString = serializer.Serialize(new { result = ex.Message });
            }
           
            response.Write(jsonString);
            response.ContentType = "application/json";
        }
Example #3
0
        public void AcceptGift(string userId, int sessionId, int playerLevel, string itemId, string senderId, ulong delayInSeconds)
        {
            var serializer = new JavaScriptSerializer();
            var data = new Dictionary<string, object>();
            data.Add("playerLevel", playerLevel);
            data.Add("itemId", itemId);
            data.Add("sender", senderId);
            data.Add("delay", delayInSeconds);

            var rows = new List<Dictionary<string, object>>();

            var item = new Dictionary<string, object>();
            item.Add("data", serializer.Serialize(data));
            item.Add("timeInMillis", this.UnixTime());
            item.Add("playerId", userId);
            item.Add("actionType", 3);
            item.Add("sessionId", sessionId);

            rows.Add(item);

            var fs = new Dictionary<string, object>();
            fs.Add("rows", rows);
            fs.Add("authCode", this.ApiKey);

            this.CurlPostData(serializer.Serialize(fs));
        }
Example #4
0
        // get : api/Movies?type={current/all order by name etc}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            try
            {
                SetConnectionString();

                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);
                if (string.IsNullOrEmpty(qpParams["type"]))
                {
                    throw new ArgumentException("type is not present");
                }

                string type = qpParams["type"].ToString();

                var tableMgr = new TableManager();
                var movies = new List<MovieEntity>();

                if (type.ToLower() == "orderby")
                {
                    movies = tableMgr.GetSortedMoviesByName();
                }
                else if (type.ToLower() == "current")
                {
                    movies = tableMgr.GetCurrentMovies();
                }

                return json.Serialize(movies);
            }
            catch (Exception ex)
            {
               return  json.Serialize(new { Status = "Error", Message = ex.Message });
            }
        }
Example #5
0
        // get : api/Actor?n={actor/actress/producer...etc name}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParam = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParam["n"]))
                {
                    throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                }

                string actorName = qpParam["n"].ToString();

                // get movies by actor(roles like actor, actress, producer, director... etc)
                var movies = tableMgr.SearchMoviesByActor(actorName);

                // serialize movie list and return
                return json.Serialize(movies);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_MOVIES, ActualError = ex.Message });
            }
        }
        public override void OnMessage(string message)
        {
            var ser = new JavaScriptSerializer();
            var msg = ser.Deserialize<Message>(message);

            switch (msg.Type)
            {
                case MessageType.Join:
                    name = msg.Value.ToString();
                    clientIds.Add(name);
                    var response = ser.Serialize(new
                    {
                        type = MessageType.UpdateClients,
                        value = clientIds.ToArray()
                    });

                    clients.Broadcast(response);
                    break;

                case MessageType.Draw:
                    var responsedata = ser.Serialize(new
                    {
                        type = MessageType.Draw,
                        username = name,
                        value = msg.Value
                    });

                    clients.Broadcast(responsedata);
                    break;

                default:
                    return;
            }
        }
Example #7
0
        //returns a json string for multiple models
        public string ToJsonModels(IEnumerable<object> models)
        {
            int x = 0;
            int z = models.Count();
            string result = "";
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            foreach (Contact model in models)
            {

                if (x == 0) { result = "["; }

                if (x == z - 1)
                {
                    result += serializer.Serialize(this.ToDictModel(model)).ToString() + "]";
                }
                else
                {
                    result += serializer.Serialize(this.ToDictModel(model)).ToString() + ",";
                }

                x++;

            }

            return result;
        }
Example #8
0
        public String ajax_SQLExecute(String SQL)
        {
            ReturnAjaxData rAjaxResult = new ReturnAjaxData();
            JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 65536 }; //64K
            String r = String.Empty;

            try
            {
                DataTable dt = getSQLConnection().ExecuteData(SQL);
                List<String> ColumnName = new List<String>();
                foreach (DataColumn dc in dt.Columns)
                {
                    ColumnName.Add(dc.ColumnName);
                }

                List<String[]> Rows = new List<String[]>();
                foreach (DataRow dr in dt.Rows)
                {
                    List<String> Cells = new List<String>();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        Cells.Add(dr[i].ToString());
                    }
                    Rows.Add(Cells.ToArray());
                }

                r = js.Serialize(new { Columns = ColumnName.ToArray(), DataItems = Rows.ToArray(), result = true, message = "" });
            }
            catch (Exception ex)
            {
                r = js.Serialize(new { result = false, message = ex.Message });
            }
            return r;
        }
Example #9
0
 /// <summary>
 /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
 /// </summary>
 /// <param name="context">The context within which the result is executed.</param>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="context"/> parameter is null.</exception>
 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
           String.Equals(context.HttpContext.Request.HttpMethod, "GET"))
     {
         throw new InvalidOperationException();
     }
     var response = context.HttpContext.Response;
     if (!String.IsNullOrEmpty(ContentType))
         response.ContentType = ContentType;
     else
         response.ContentType = CallbackApplicationType;
     if (ContentEncoding != null)
         response.ContentEncoding = this.ContentEncoding;
     if (Data != null)
     {
         String buffer;
         var request = context.HttpContext.Request;
         var serializer = new JavaScriptSerializer();
         if (request[JsonpCallbackName] != null)
             buffer = String.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data));
         else
             buffer = serializer.Serialize(Data);
         response.Write(buffer);
     }
 }
        /// <summary>
        /// Process request on deletion of user based on HTTP context, returns message upon success
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            String jsonString = String.Empty;
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            Models.Login.Login login = new Models.Login.Login(new User
            {
                UserName = request.Form["userName"]
            });

            try
            {
                login.DeleteUser();
                jsonString = serializer.Serialize(new { result = "success" });
            }
            catch (Exception ex)
            {
                jsonString = serializer.Serialize(new { result = ex.Message });
            }
            finally
            {
                response.Write(jsonString);
                response.ContentType = "application/json";
            }
        }
        public string GetCoverage()
        {
            var baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            var path = baseDirectory + "CSVFiles\\CountyFullImmunizationCoverageRate.csv";

            var iop = System.IO.File.ReadAllLines(path).Skip(1).Select(line => new { line, columns = line.Split(','), rows = line.Split(';') }).Select(@t => new
            {
                year1 = @t.columns[1],
                year2 = @t.columns[2],
                year3 = @t.columns[3]
            }).ToList();

            var coverage = new List<List<float>>();

            var coverageYr1 = iop.Select(v => float.Parse(v.year1)).ToList();
            coverage.Add(coverageYr1);
            var coverageYr2 = iop.Select(v => float.Parse(v.year2)).ToList();
            coverage.Add(coverageYr2);
            var coverageYr3 = iop.Select(v => float.Parse(v.year3)).ToList();
            coverage.Add(coverageYr3);
            var jsonSerialiser = new JavaScriptSerializer();
            foreach (var c in coverage)
            {
                var json = jsonSerialiser.Serialize(c);
            }

            var json1 = jsonSerialiser.Serialize(coverage);
            return json1;
        }
Example #12
0
        public string Diff(string left, string right)
        {
            int maxLength = 200000;
            Compression.SetCompression();
            JavaScriptSerializer json = new JavaScriptSerializer();

            if (!string.IsNullOrEmpty(left) && left.Length > maxLength)
            {
                return json.Serialize(new JsonData() { IsError = true, Errors = string.Format("Left input is too long (max is {0} characters).\n", maxLength) });
            }

            if (!string.IsNullOrEmpty(right) && right.Length > maxLength)
            {
                return json.Serialize(new JsonData() { IsError = true, Errors = string.Format("Right input is too long (max is {0} characters).\n", maxLength) });
            }

            Service.LinuxService ser = new Service.LinuxService();
            var res = ser.GetDiff(left, right);
            if (res.IsError)
                return json.Serialize(new JsonData() { IsError = true });
            else
            {
                if (!string.IsNullOrEmpty(res.Result))
                {
                    int startIndex = res.Result.IndexOf("<table");
                    if (startIndex != -1)
                        res.Result = res.Result.Substring(startIndex);
                    int endIndex = res.Result.LastIndexOf("</body");
                    if (endIndex != -1)
                        res.Result = res.Result.Substring(0, endIndex);
                }
                return json.Serialize(new JsonData() { Result = res.Result });
            }
        }
        public void GetFacilityAddress_When_CurrentSubscriber_SessionInstance_is_Null()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                var expectedFacilityAddress = new FacilityAddress();
                // Fake the session state for HttpContext
                // http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/
                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState();
                session.ItemGetString = (key) => { if (key == "Subscriber") return null; return null; };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // GetInstance will return the Faked instance
                var myCurrentSubscriber = CurrentSubscriber.GetInstance();

                // Act
                // While we are using a fake, we haven't faked the SessionInstance which
                // means this will be null and this in turn means that
                //GetFacilityAddress should return a new FacilityAddress
                var actualFacilityAddress = myCurrentSubscriber.GetFacilityAddress();

                // Assert
                Assert.IsNotNull(actualFacilityAddress, "CurrentSubscriber.GetInstance().GetFacilityAddress() is null");
                var jss = new JavaScriptSerializer();
                Assert.AreEqual(jss.Serialize(expectedFacilityAddress),jss.Serialize(actualFacilityAddress), "There is a difference between the expected and actual address");
            }
        }
Example #14
0
        public string AddComment(string userData)
        {
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            CommentOrder comment = jsonSerializer.Deserialize<CommentOrder>(userData);

            OrdersBusiness orderbusiness = new OrdersBusiness();

            WebService ws = new WebService();
            string result;
            int state;
            if (myHeader != null && ws.VerifyUser(myHeader.UserName, myHeader.Password))
            {
                state = orderbusiness.InsertComment(comment);
                if (state != -1)
                {
                    result = "0"; //增加评论
                }
                else
                {
                    result = "1";
                }
            }
            else
            {
                return jsonSerializer.Serialize("loginfalse");
            }
            return jsonSerializer.Serialize(result);
        }
Example #15
0
        public static void Main()
        {
            var digits = new Dictionary<string, int>
            {
                { "one", 1 },
                { "two", 2 },
                { "three", 3 },
                { "four", 4 },
                { "five", 5 },
                { "six", 6 },
                { "seven", 7 },
                { "eight", 8 },
                { "nine", 9 },
            };

            var serializer = new JavaScriptSerializer();
            var digitsInJson = serializer.Serialize(digits);
            Console.WriteLine(digitsInJson);

            var digitsDeserialized = serializer.Deserialize<Dictionary<string, int>>(digitsInJson);
            digitsDeserialized.Print();

            var dict = new Dictionary<int, string>
            {
                { 0, "zero" },
                { 1, "one" },
                { 2, "two" }
            };

            // Exception: On serialization/deserialization of a dictionary, keys must be strings or objects.
            var dictSerialized = serializer.Serialize(dict);
        }
Example #16
0
        // get : api/Search?q={searchText}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParams["q"]))
                {
                    throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                }

                string searchText = qpParams["q"];

                searchText = string.IsNullOrEmpty(searchText) ? string.Empty : searchText.Replace(".", "");

                // get movies by search keyword
                var movie = tableMgr.SearchMovies(searchText);

                // serialize movie list and return
                return json.Serialize(movie);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with sys  tem error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_MOVIES, ActualError = ex.Message });
            }
        }
Example #17
0
        public void MyCouponJsonSerializeAndDeserialize_Test()
        {
            IRepository repo = new Repository();

            var coupons = repo.Query<CouponView>(x => x.UserID == 443);

            if (coupons != null && coupons.Count > 0)
            {
                var couponDtos = coupons.MapToList<CouponView, CouponDto>().ToList();

                var jsonSerializer = new JavaScriptSerializer();

                var json = jsonSerializer.Serialize(couponDtos);

                if (!string.IsNullOrEmpty(json))
                {
                    couponDtos = jsonSerializer.Deserialize<List<CouponDto>>(json);

                    Assert.IsInstanceOfType(couponDtos[0], typeof(CouponDto));
                }

                var myCouponDto = new MyCouponDto
                {
                    Coupons = couponDtos
                };

                json = jsonSerializer.Serialize(myCouponDto);

                Assert.IsTrue(!string.IsNullOrEmpty(json));
            }
        }
        private ActionResult All()
        {
            var userNameInfo = UserName;
            var settings = UserSettings;

            var changelists = (from item in db.ChangeLists.AsNoTracking()
                                where (item.UserName == userNameInfo.fullUserName ||
                                        item.UserName == userNameInfo.userName ||
                                        item.ReviewerAlias == userNameInfo.reviewerAlias) &&
                                        item.Stage != (int)ChangeListStatus.Deleted
                                select item).OrderByDescending(x => x.TimeStamp);

            var model = new List<ChangeListDisplayItem>();
            foreach (var item in changelists)
            {
                model.Add(new ChangeListDisplayItem(item));
            }

            if (model.Count == 0)
            {
                return RedirectToAction("Index", "SubmitReview");
            }

            var js = new JavaScriptSerializer();
            var data = model.ToList();

            ViewBag.ChangeListDisplayItems = js.Serialize(data);
            ViewBag.Message = "Code Reviewer";
            ViewBag.UserSettings = js.Serialize(ReviewUtil.GenerateUserContext(0, userNameInfo.userName, "settings", settings));

            return View(data);
        }
Example #19
0
 public string DeleteExistingChain(String firstBlockGUID)
 {
     var jss = new JavaScriptSerializer();
     List<ServiceFlow> sfs;
     String errorMessage;
     if (GetServiceFlows(out sfs, out errorMessage))
     {
         foreach (ServiceFlow serviceFlow in sfs)
         {
             if (serviceFlow.FirstBlockGUID == firstBlockGUID)
             {
                 try
                 {
                     UserProfile profile = UserProfile.GetUserProfile(User.Identity.Name);
                     List<ServiceFlow> newServiceFlows = new List<ServiceFlow>(sfs);
                     newServiceFlows.Remove(serviceFlow);
                     profile.ServiceFlows = newServiceFlows.SerializeAndZip();
                     profile.Save();
                     return jss.Serialize("Chain Deleted Successfully");
                 }
                 catch (Exception exception)
                 {
                     return jss.Serialize("Problem deleting chain - " + exception.Message);
                 }
             }
         }
         return jss.Serialize("Error - Chain not found");
     }
     return jss.Serialize(errorMessage);
 }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
                response.ContentType = ContentType;
            else
                response.ContentType = "application/json";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {
                HttpRequestBase request = context.HttpContext.Request;

                var serializer = new JavaScriptSerializer();
                if (!string.IsNullOrEmpty(request.Params["callback"]))
                    response.Write(SanitizeCallback(request.Params["callback"]) + "(" + serializer.Serialize(Data) +
                                   ");");
                else
                    response.Write(serializer.Serialize(Data));
            }
        }
        public void LoadEditPPV_VODContent_NullModel_ValidateUserAbleToLoadDefaultPpvVodContentForEdit()
        {
            using (ShimsContext.Create())
            {
                // Given a user

                // And a default ppv and vod content for a subscriber
                var ppvVodModel = new PPV_VOD_SettingsModel
                {
                    PIN = null,
                    PINRequired = false,
                    PPVCap = null,
                    PPVPrivilege = DAL.Enums.SubscriberEnums.PPVPrivilegeEnum.None,
                    PPVResetDay = 0
                };

                // When loading the ppv and vod content for edit by passing null model
                var ppvVodController = DependencyResolver.Current.GetService<PPV_VODController>();
                var actionResponse = ppvVodController.LoadEditPPV_VODContent(null) as PartialViewResult;

                // Then the user receives a response
                Assert.IsNotNull(actionResponse, "LoadEditPPV_VODContent returned null");

                // And the response is successful
                Assert.AreEqual("EditPPV_VOD_Partial", actionResponse.ViewName, "ViewName does not match");

                // And the ppv vod settings matches with the default ppv vod settings model
                var jss = new JavaScriptSerializer();
                Assert.AreEqual(jss.Serialize(ppvVodModel), jss.Serialize(actionResponse.Model));
            }
        }
Example #22
0
        public string GetDiffHtml(string CodeGuid, string LeftGuid, string RightGuid)
        {
            Compression.SetCompression();
            JavaScriptSerializer json = new JavaScriptSerializer();

            var left = Model.GetCode(LeftGuid, false);
            var right = Model.GetCode(RightGuid, false);

            if (left == null || right == null)
            {
                throw new HttpException(404, "not found");
            }
            Service.LinuxService ser = new Service.LinuxService();
            var res = ser.GetDiff(left.Program, right.Program);
            if (res.IsError)
                return json.Serialize(new JsonData() { Errors = true });
            else
            {
                if (!string.IsNullOrEmpty(res.Result))
                {
                    int startIndex = res.Result.IndexOf("<table");
                    if (startIndex != -1)
                        res.Result = res.Result.Substring(startIndex);
                    int endIndex = res.Result.LastIndexOf("</body");
                    if (endIndex != -1)
                        res.Result = res.Result.Substring(0, endIndex);
                }
                return json.Serialize(new JsonData() { Result = res.Result });
            }
        }
Example #23
0
 public string Subscribe(int? wall_id)
 {
     Compression.SetCompression();
     JavaScriptSerializer json = new JavaScriptSerializer();
     if (!SessionManager.IsUserInSession())
         return json.Serialize(new SubscriptionData() { Errors = false, NotLoggedIn = true, Subscribed = false });
     bool? s = Model.Subscribe(wall_id);
     return json.Serialize(new SubscriptionData() { Errors = s == null, NotLoggedIn = false, Subscribed = s});
 }
        static void Main()
        {
            var context = new MoviesContext();
            var jsSerializer = new JavaScriptSerializer();

            // Adult Movies
            var adultMovies = context.Movies
                .Where(m => m.AgeRestriction == AgeRestriction.Adult)
                .Select(m => new
                {
                    title = m.Title,
                    ratingsGiven = m.Ratings.Count()
                })
                .ToList();

            var adultMoviesJson = jsSerializer.Serialize(adultMovies);
            File.WriteAllText("adult-movies.json", adultMoviesJson);
            Console.WriteLine("Adult Movies exported to adult-movies.json.");

            // Rated Movies by User jmeyery
            var ratedMoviesByUser = context.Users
                .Where(u => u.UserName == "jmeyery")
                .Select(u => new
                {
                    username = u.UserName,
                    ratedMovies = u.Ratings
                        .Select(r => new
                        {
                            title = r.Movie.Title,
                            userRaiting = r.Stars,
                            averageRating = r.Movie.Ratings.Average(m => m.Stars)
                        })
                });

            var jsonMovies = jsSerializer.Serialize(ratedMoviesByUser);
            File.WriteAllText("rated-movies-by-jmeyery.json", jsonMovies);
            Console.WriteLine("Rated Movies by User jmeyery exported to rated-movies-by-jmeyery.json.");

            // Top 10 Favourite Movies
            var topFavMovies = context.Movies
                .Where(m => m.AgeRestriction == AgeRestriction.Teen)
                .OrderByDescending(m => m.Users.Count())
                .ThenBy(m => m.Title)
                .Select(m => new
                {
                    isbn = m.Isbn,
                    title = m.Title,
                    favouritedBy = m.Users.Select(u => u.UserName)
                })
                .Take(10)
                .ToList();

            var jsonTopFavMovies = jsSerializer.Serialize(topFavMovies);
            File.WriteAllText("top-10-favourite-movies.json", jsonTopFavMovies);
            Console.WriteLine("Top 10 Favourite Movies exported to top-10-favourite-movies.json.");
        }
Example #25
0
 protected void Page_Load(object sender, EventArgs e)
 {
     UserData ud = Session["UserData"] as UserData;
     if (!UserData.ChkObjNull(UserData.ObjType.购物车))
     {
         ud = Session["UserData"] as UserData;
         ud.ShoppingCart = new DS_Cart();
     }
     var js = new System.Web.Script.Serialization.JavaScriptSerializer();
     string act=Request["action"];
     switch(act){
         case "chg_num":
             var odinfo=ud.ShoppingCart.Add(int.Parse(Request.Form["id"]),int.Parse(Request.Form["num"]));
             Response.Write(js.Serialize(odinfo));
             break;
         case "del":
             odinfo=ud.ShoppingCart.Del(int.Parse(Request.Form["id"]));
             Response.Write(js.Serialize(odinfo));
             break;
         case "dels":
             odinfo = ud.ShoppingCart.Del(Request.Form["ids"].TrimEnd(','));
             Response.Write(js.Serialize(odinfo));
             break;
         case "chgarea":
             var bl = new DS_Area_Br();
             Response.Write(js.Serialize(bl.Query("parentid=@0","px",int.Parse(Request["id"]))));
             break;
         case "sub_order":
             var am = new ActMsg {succe=false,msg="" };
             //try
             //{
                 var oddtbl = new DS_Orders_Br();
                 var od=ud.ShoppingCart.Orders.Single(a=>a.ID.Equals(int.Parse(Request.QueryString["oid"])));
                 od.ClientArea = Request["province"].Split(',')[0] + " " + Request["city"].Split(',')[0] + " " + Request["town"].Split(',')[0];
                 od.ClientZipCode=Request["zipcode"];
                 od.ClientStreet = Request["street"];
                 od.ClientName = Request["username"];
                 od.ClientPhone = Request["phone"].Replace("区号-电话号码-分机","");
                 od.ClientMobile=Request["mobile"];
                 od.ClientRemark = Request["remark"].Replace("请输入您对该笔交易或货品的特殊要求以提醒供应商,字数不超过500字", "").Trim();
                 var list=ud.ShoppingCart.OrderDetail.Where(a=>a.OrderID.Equals(od.ID)).ToList();
                 oddtbl.Add(od,list);
                 ud.ShoppingCart.OrderDetail.RemoveAll(a=>a.OrderID.Equals(od.ID));
                 ud.ShoppingCart.Orders.Remove(od);
                 am.succe = true;
                 am.msg = "提交订单成功。";
             //}
             //catch (Exception ex) {
             //    am.msg = "抱歉,提交出错。";
             //}
             Response.Write(js.Serialize(am));
             break;
     }
 }
		protected void Page_Load(object sender, EventArgs e)
		{
			_Perm_Resource_Link_Ok = UserHasPermission(Permission.Hyperlink_Resource_Name);

			if (!IsPostBack)
			{
				ImageWebFolder = (Request.ApplicationPath.Equals("/") ? string.Empty : Request.ApplicationPath) + "/Images/";

				var serializer = new JavaScriptSerializer();
				/* convert resource category, type, subtype into an array, and then a string to use as a JSON data source */
				var resourceTypes = Thinkgate.Base.Classes.Resource.GetResourceCategoriesDataTable();
				var resourceTypeArry = new ArrayList();
				foreach (DataRow row in ((DataTable)resourceTypes).Rows)
				{
					resourceTypeArry.Add(new string[] { row["Category"].ToString(), row["TYPE"].ToString(), row["SubType"].ToString() });
				}
				var resourceTypeStr = serializer.Serialize(resourceTypeArry);

				ctrlCategory.JsonDataSource = resourceTypeStr;
				ctrlDocuments.JsonDataSource = resourceTypeStr;
				ctrlStandards.JsonDataSource = serializer.Serialize(CourseMasterList.StandCourseList.BuildJsonArray());
				ctrlCurriculum.JsonDataSource = serializer.Serialize(CourseMasterList.CurrCourseList.BuildJsonArray());
				ctrlClasses.JsonDataSource = serializer.Serialize(CourseMasterList.ClassCourseList.BuildJsonArray());
				txtSearch.DataSource = TextSearchDropdownValues();

				ctrlSchools.JsonDataSource = serializer.Serialize(SchoolMasterList.BuildJsonArrayForTypeAndSchool());
				ctrlStudents.DataSource = Grade.GetGradeListForDistrict(); //TODO: Not a fan of using this to load the grades. Should be in a global static list, but time is short

				ctrlTeachers.DataTextField = "RoleName";
				ctrlTeachers.DataSource = ThinkgateRole.GetRolesCollectionForApplication();
			}
			if (radGridResults.DataSource == null)
			{
				radGridResults.Visible = false;
			}

			if (IsPostBack)
			{
				radGridResults.Visible = true;

				//Populate NodeAliasPaths
				string userName = ((UserInfo)Session["KenticoUserInfo"]).UserName;
				string clientID = DistrictParms.LoadDistrictParms().ClientID;
				string envState = KenticoHelper.getState(clientID);

				//Our search should include all resource documents belonging to the 
				// - User
				// - District
				// - State
				NodeAliasPaths = new [] {"/" + envState + "/Users/" + userName + "/%", "/" + envState + "/Districts/" + clientID + "/%", "/" + envState + "/Documents/%"};

			}

		}
        public string AddToFavorites(string jsonData)
        {
            Dictionary<string, string> json = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonData);
            Dictionary<string, string> result = new Dictionary<string, string>();
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            using (MySqlConnection conn = new MySqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["BooksConn"].ConnectionString;
                try
                {
                    conn.Open();

                    string sql = "SELECT * FROM UserBooks WHERE IDUser=?IDUser AND IDBook=?IDBook";
                    MySqlCommand command = new MySqlCommand(sql, conn);
                    command.Parameters.AddWithValue("?IDUser", json["userId"]);
                    command.Parameters.AddWithValue("?IDBook", json["bookId"]);

                    MySqlDataReader reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        reader.Close();
                        result["status"] = "error";
                        result["message"] = "You already have this book in your favorites.";

                        return serializer.Serialize((object)result);
                    }
                    else
                    {
                        reader.Close();

                        command.CommandText = "INSERT INTO UserBooks (IDUser, IDBook) VALUES (?IDUser, ?IDBook)";
                        command.ExecuteNonQuery();

                        result["status"] = "success";
                        result["message"] = "The book has been added to your favorites.";

                        return serializer.Serialize((object)result);
                    }
                }
                catch (Exception ex)
                {
                    result["status"] = "error";
                    result["message"] = ex.Message;

                    return serializer.Serialize((object)result);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
		public object AJAXSendComplextTypeArray(int[] items, Address[] addresses)
		{
			string json = string.Empty;

			var jsonSer = new JavaScriptSerializer();
			string jsonItems = jsonSer.Serialize(items);
			string jsonAddresses = jsonSer.Serialize(addresses);

			json = jsonItems + "\n" + jsonAddresses;
			return json;
		}
Example #29
0
 public ActionResult Index()
 {
     using (var db = new GraphContext())
     {
         var jss = new JavaScriptSerializer();
         ViewBag.Json1 = jss.Serialize(db.Nodes.Select(p => new { p.Id, N = p.Name, p.X, p.Y }));
         ViewBag.Json2 = jss.Serialize(db.Edges.Where(p=>p.Dir == "A").Select(p => new { NF = new { p.FromNode.Id, p.FromNode.X, p.FromNode.Y }, 
                                                                  NT = new { p.ToNode.Id, p.ToNode.X, p.ToNode.Y } 
                                                                 }));
     }
     return View();
 }
Example #30
0
 public static HttpResponseMessage HttpRMtoJson(string jsonpCallback, object obj, HttpStatusCode statusCode, customStatus customStatus)
 {
     string str;
     ResponseJsonMessage rjm = new ResponseJsonMessage(customStatus.ToString(), obj);
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     if(string.IsNullOrEmpty(jsonpCallback))
         str = serializer.Serialize(rjm);
     else
         str = jsonpCallback + "(" + serializer.Serialize(rjm) + ");";
     HttpResponseMessage result = new HttpResponseMessage() { StatusCode = statusCode, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
     return result;
 }