Пример #1
0
        static void btn_Click(object sender, Game.GUI.Controls.EventArgs e)
        {
            all_items.RemoveAll(el => !el.Item1.IsAlive);
            var seri =  new System.Web.Script.Serialization.JavaScriptSerializer();
            var query = all_items.Select(el => el.Item2).GroupBy(el => el).Select(el => new { stack = el.Key, count = el.Count() }).OrderByDescending(el => el.count);

            var txt = seri.Serialize(query);
            System.IO.File.WriteAllText("D:\\Temp\\Stacks.txt", txt);

            var query2 = all_items.GroupBy(el => el.Item1.Target.ItemID).OrderByDescending(group=>group.Count()).Select(group =>
                {
                    var dict = new Dictionary<string, int>();

                    var regrouped = group.GroupBy(el2 => el2.Item1.Target.MaterialID);
                    if (regrouped.Count() > 1)
                    {
                        dict.Add("total", group.Count());
                    }
                    foreach (var el in regrouped)
                    {
                        dict.Add(((Material)el.Key).ToString(), el.Count());
                    }
                    return Tuple.Create(group.Key.ToString(), new SerializableDataBag<int>(dict));
                }).ToBag();
            using (var file = System.IO.File.OpenWrite("D:\\Temp\\Types.txt"))
            {
                JSON.ToJSON(query2, file, typeof(SerializableDataBag<int>));
            }
            //var txt2 = seri.Serialize(query2);
            //System.IO.File.WriteAllText("D:\\Temp\\Types.txt", txt2);
        }
Пример #2
0
        public void DeleteFiles(string jlist)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<string> list = serializer.Deserialize<List<string>>(jlist);
            List<string> archives = new List<string>();
            foreach (string path in list)
            {

                FileAttributes attr = System.IO.File.GetAttributes(path);
                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true); //delete folder and all subdirectories
                        // return RedirectToAction("Repository", "Repository");
                    }
                }
                else
                {
                    if (System.IO.File.Exists(path))
                    {
                        string previousVirtualPath = UtilityOperations.GetVirtualPath(path);//.Replace("~/", "~//");
                        DocumentsOperations documentsOperations = new DocumentsOperations();
                        documentsOperations.DeleteFile(previousVirtualPath);
                        System.IO.File.Delete(path);
                        // return RedirectToAction("Repository", "Repository");
                    }
                }
            }

            //return View();
        }
        internal SubscriberInformation GetMemberInformation(string memberId)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(apiUri + "/MemberInformation/GetMemberInformation?memberId=" + memberId);
            req.ContentType = "application/json";
            req.Method = "Get";
            req.AllowAutoRedirect = false;
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            String output = RespsoneToString(resp);
            try
            {
                if (output == "null" || string.IsNullOrEmpty(output))
                {
                    return null;
                }
                else
                {
                    System.Web.Script.Serialization.JavaScriptSerializer jser = new System.Web.Script.Serialization.JavaScriptSerializer();
                    object obj = jser.Deserialize(output, typeof(SubscriberInformation));
                    SubscriberInformation result = (SubscriberInformation)obj;
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #4
0
        public void UploadFileAjax()
        {
            HttpRequest request = this.Context.Request;

            HttpPostedFile file = request.Files["file"];
            //Save the file appropriately.
            //file.SaveAs(...);

            string msg = "File Name: " + file.FileName;
            msg += "<br />First Name: " + request["first-name"];
            msg += "<br />Country: " + request["country_Value"];

            var o = new { success = true, msg = msg };
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            HttpContext context = this.Context;
            HttpResponse response = context.Response;

            context.Response.ContentType = "text/html";

            string s = serializer.Serialize(o);
            byte[] b = response.ContentEncoding.GetBytes(s);
            response.AddHeader("Content-Length", b.Length.ToString());
            response.BinaryWrite(b);

            try
            {
                this.Context.Response.Flush();
                this.Context.Response.Close();
            }
            catch (Exception) { }
        }
        public async override Task<ActionResult> IndexAsync(AuthorizationCodeResponseUrl authorizationCode,
            CancellationToken taskCancellationToken)
        {
            if (string.IsNullOrEmpty(authorizationCode.Code))
            {
                var errorResponse = new TokenErrorResponse(authorizationCode);
                Logger.Info("Received an error. The response is: {0}", errorResponse);

                return OnTokenError(errorResponse);
            }

            Logger.Debug("Received \"{0}\" code", authorizationCode.Code);

            var returnUrl = Request.Url.ToString();
            returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?"));

            var token = await Flow.ExchangeCodeForTokenAsync(UserId, authorizationCode.Code, returnUrl,
                taskCancellationToken).ConfigureAwait(false);

            // Extract the right state.
            var oauthState = await AuthWebUtility.ExtracRedirectFromState(Flow.DataStore, UserId, authorizationCode.State).ConfigureAwait(false);

            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(token);
            System.IO.File.WriteAllText("D://json.txt", json);

            return RedirectToAction("Index", "Home");
            //TODO: Move to Home/Connect
            //ToDO: move to Home/Upload
            //TODO: Load from Disk
        }
        public string Query(string ip)
        {
            string value;
            if (Cache.TryGetValue(ip, out value))
                return value;

            var client = new WebClient();
            var json = client.DownloadString("http://172.30.0.164:8081/MobiWebService.svc/json/GetCountryISOCode?ip=" + ip + "&key=RIG8UhzkrSKmy7G1P55QdivGTvrbgJ+13thnE8mjzbo=");
            try {
                dynamic res = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<dynamic>(json);
                var country = res["GetCountryISOCodeResult"] as string;
                if (!string.IsNullOrEmpty(country))
                {
                    if (1 == country.Length)
                        country += "-";
                    value = country.ToLower();
                    Cache[ip] = value;
                    return value;
                }
                return null;

            } catch(Exception ex)
            {
                // eat it!
                return null;
            }
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            string _isMobileCheckParams = filterContext.HttpContext.Request.Params["isMobile"];
            string _userAgent = filterContext.HttpContext.Request.UserAgent;

            if (string.IsNullOrWhiteSpace(_isMobileCheckParams) || !_isMobileCheckParams.ToUpper().Equals("Y"))
            {
                if (!(IsAppleDevice(_userAgent) || IsAndroidDevice(_userAgent)))
                {
                    if (string.IsNullOrEmpty(RedirectUrl))
                    {
                        //throw new Exception("Mobile only!!");
                        var _errorMessage = new string[]
                    {
                        "mobile only",
                        filterContext.HttpContext.Request.Url.AbsoluteUri
                    };

                        string _model = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(_errorMessage);
                        filterContext.Result = new RedirectToRouteResult(
                            new System.Web.Routing.RouteValueDictionary { { "controller", "Error" }, { "model", _model } }
                        );
                    }
                    else
                    {
                        filterContext.HttpContext.Response.Redirect(RedirectUrl);
                    }

                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {

            context.Response.ContentType = "text/plain";
            //就是将所有的User中的信息添加到主表中 Id, LoginName, Password, Phone, Email, UserState

            List<shaoqi.Model.Comment> list = comBll.GetModelList(" ");
            List<shaoqi.Model.CommentTwo> listTwo = new List<shaoqi.Model.CommentTwo>();
            for (int i = 0; i < list.Count; i++)
            {
                shaoqi.Model.CommentTwo model = new shaoqi.Model.CommentTwo();
                model.Id = list[i].Id;
                model.CommentContext = list[i].ComContent;
                model.UserName = list[i].UserId.LoginName;
                model.CartoonName = list[i].CartoonId.CartoonName;
                model.AddTime = list[i].AddTime;
                listTwo.Add(model);
            }
            System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();

            //还要查出有多少条记录
            string sqlc = "select count(*) from Comment";
            int count = comBll.GetinfoCount(sqlc);

            var info = new { total = count, rows = listTwo };

            string allinfo = json.Serialize(info);

            context.Response.Write(allinfo);
        }
Пример #9
0
        public async Task<HttpResponseMessage> Upload()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = "C:\\Users\\Hà\\Desktop\\upload";// HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new CustomMultipartFormDataStreamProvider(root);
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.Size.ToString());
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine("Server file path: " + file.LocalFileName);
                    //var result = new { name = file.LocalFileName };
                    //HttpContext.Current.Response.Write(serializer.Serialize(result));

                }
                return Request.CreateResponse(HttpStatusCode.OK);

            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
Пример #10
0
 /// <summary>
 /// Constructor: set members
 /// </summary>
 public DragDropPayload(Constants.operations operation, string name, string guid)
 {
     _operation = operation;
     RpcName = name;
     RpcGuid = guid;
     _jss = new System.Web.Script.Serialization.JavaScriptSerializer();
 }
Пример #11
0
 public object Deconstruct(string jsonObject)
 {
     System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
     DragDropPayload ret = new DragDropPayload();
     ret = jss.Deserialize<DragDropPayload>(jsonObject);
     return ret;
 }
Пример #12
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.ResultModel result = new NFMT.Common.ResultModel();

            try
            {
                NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;
                context.Response.ContentType = "text/plain";

                string empStr = context.Request.Form["Employee"];
                if (string.IsNullOrEmpty(empStr))
                {
                    context.Response.Write("员工信息不能为空");
                    context.Response.End();
                }

                string accountStr = context.Request.Form["account"];
                if (string.IsNullOrEmpty(empStr))
                {
                    context.Response.Write("员工账号密码信息不能为空");
                    context.Response.End();
                }

                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                NFMT.User.Model.Employee emp = serializer.Deserialize<NFMT.User.Model.Employee>(empStr);
                NFMT.User.Model.Account account = serializer.Deserialize<NFMT.User.Model.Account>(accountStr);

                if (emp.DeptId <= 0)
                {
                    context.Response.Write("未选择部门");
                    context.Response.End();
                }

                if (string.IsNullOrEmpty(emp.EmpCode))
                {
                    context.Response.Write("未填写员工编号");
                    context.Response.End();
                }

                if (string.IsNullOrEmpty(emp.Name))
                {
                    context.Response.Write("员工名称不能为空");
                    context.Response.End();
                }

                NFMT.User.BLL.EmployeeBLL empBLL = new NFMT.User.BLL.EmployeeBLL();
                result = empBLL.CreateHandler(user, emp, account);

                if (result.ResultStatus == 0)
                    result.Message = "员工新增成功";

            }
            catch (Exception e)
            {
                result.Message = e.Message;
                result.ResultStatus = -1;
            }

            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
        }
Пример #13
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.ResultModel result = new NFMT.Common.ResultModel();
            context.Response.ContentType = "text/plain";
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            string orderStr = context.Request.Form["order"];
            string orderStockInvoiceStr = context.Request.Form["orderStockInvoice"];
            string orderDetailStr = context.Request.Form["orderDetail"];

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

            NFMT.Document.Model.DocumentOrder order = serializer.Deserialize<NFMT.Document.Model.DocumentOrder>(orderStr);
            List<NFMT.Document.Model.OrderReplaceStock> stockInvoices = serializer.Deserialize<List<NFMT.Document.Model.OrderReplaceStock>>(orderStockInvoiceStr);
            NFMT.Document.Model.DocumentOrderDetail detail = serializer.Deserialize<NFMT.Document.Model.DocumentOrderDetail>(orderDetailStr);

            NFMT.Document.BLL.DocumentOrderBLL bll = new NFMT.Document.BLL.DocumentOrderBLL();
            result = bll.UpdateReplaceOrder(user, order, stockInvoices, detail);

            if (result.ResultStatus == 0)
                result.Message = "制单指令修改成功";

            string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(result);
            context.Response.Write(jsonStr);
        }
        public static string getSLDuAn_DaDauTu( List<EntityDuAn> duan)
        {
            string[] mang = new string[] { "#FF99CC", "#CC99CC", "#9999CC", "#6699CC", "#0099CC", "#FF66CC", "#CC99CC", "#6699CC", "#0099CC", "#3366CC", "#00EE00", "#008800", "#002200", "#000044", "#DDC488", "#ECAB53", "#008080", "#FFCC99", "#FFD700", "#9932CC", "#8A2BE2", "#C71585", "#800080", "#FFBF00", "#9966CC", "#7FFFD4", "#007FFF", "#3D2B1F", "	#0000FF", "#DE3163", "#7FFF00", "#50C878", "#DF73FF", "#4B0082", "#FFFF00", "#008080", "#660099", "#FFE5B4" };
            dbFirstStepDataContext db = new dbFirstStepDataContext();
            List<BanDoModel> list = new List<BanDoModel>  ();
            var danhmuc  =  db.EntityDanhMucs.Where(g => g.IdRoot ==1).ToList();
            Random rd = new Random();
            int vt = rd.Next(mang.Count()-danhmuc.Count());
            int i = -1;
            foreach(var item in danhmuc)
            {
                i++;
                BanDoModel bando = new BanDoModel ();
                int sl = duan == null ? 0 : duan.Where(g => g.IdDanhMuc == item.Id).ToList().Count();
                bando.value = 1;
                if (sl > 0)
                {
                    bando.color = mang[vt+i];

                }
                else bando.color = "#f5f5f5";

             //   bando.color = sl > 0 ? "#14c3be" : "#f5f5f5";
                bando.highlight = "#FF5A5E";
                bando.label = item.TenDM.ToString()+"("+sl+")";
                list.Add(bando);
            }

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string sJSON = oSerializer.Serialize(list);
            return sJSON;
        }
Пример #15
0
        public void Delete(string uri, string endpoint)
        {
            JObject responseObject = null;
            IdentityManager identityManager = new IdentityManager(this._identity);
            var authData = identityManager.GetAuthData(endpoint);

            string requestUrl = authData.Endpoint + uri;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
            request.Method = "DELETE";
            request.Headers.Add("X-Auth-Token", authData.AuthToken);
            request.ContentType = "application/json";
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            HttpStatusCode statusCode;
            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
            statusCode = response.StatusCode;
            if (statusCode.Equals(HttpStatusCode.OK))
            {
            }
        }
        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string JSON = serializer.Serialize(new ReplayJSON(fileDlg.FileName));

            txtBoxJSON.Text = JSON;
        }
Пример #17
0
        /// <summary>
        /// Assign RFQ VVI to Supplier
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult AssignSupplier()
        {
            SystemMessages sysMsg = new SystemMessages();
            int id = 0;
            string postData = Request["postData"];
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            Dictionary<string, object> jsonData = jss.Deserialize<Dictionary<string, object>>(postData) as Dictionary<string, object>;
            Dictionary<string, object> data = jsonData["data"] as Dictionary<string, object>;
            string dataId = Convert.ToString(jsonData["dataId"]);
            string operation = Convert.ToString(jsonData["operation"]);
            string suppliercode = Convert.ToString(jsonData["SupplierCode"]);
            List<FieldCategory> lfc = FieldCategory.GetCategorys(FieldCategory.Category_TYPE_VVI);
            Int32.TryParse(dataId, out id);

            using (TScope ts = new TScope())
            {
                try
                {

                    VVIQuotationDetail dm = new VVIQuotationDetail(lfc, data);

                    if (id > 0)
                    {

                        dm.AssignVVIData(id, suppliercode, sysMsg);
                    }
                    else
                    {
                        sysMsg.isPass = false;
                        sysMsg.Messages.Add("Error", "Please select a RFQ ");
                    }

                }
                catch (Exception ex)
                {
                    ts.Rollback();
                    sysMsg.isPass = false;
                    sysMsg.Messages.Add("Error", ex.Message);
                }
            }
            string html = "";
            string wfStatus = "";

            VVIQuotationDetail b2Detail = new VVIQuotationDetail();
            // List<FieldCategory> lfc = FieldCategory.GetMasterCategorys(FieldCategory.Category_TYPE_VVI);
            b2Detail.FillCategoryData(lfc, id);
            WFTemplate wfTemplate = new WFTemplate("VVIWF", id);
            html = DetailUIHelper.GenrateCategories(lfc, wfTemplate);
            wfStatus = wfTemplate.Status == WorkflowStatus.Finished ? "Finished" : "";

            var returnData = new
            {
                DataId = id,
                SysMsg = sysMsg,
                Html = html,
                wfStatus = wfStatus
            };

            return Json(returnData, JsonRequestBehavior.AllowGet);
        }
Пример #18
0
        private string GetArtist()
        {
            var response = new JsonResponseMessage();
            var jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            try
            {
                List<Artist> results;
                using (var ormContext = new ChinookContext())
                {
                    results = ormContext.Artists.ToList();
                }
                // var results = this.contexts1.Artists.ToList();
                response.IsSucess = true;
                response.Message = string.Empty;
                response.CallBack = this.callBackMethodName;
                response.ResponseData = results;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.IsSucess = false;
            }
            return jSearializer.Serialize(response);
        }
Пример #19
0
 public string getAllUsersJson()
 {
     System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     jsSerializer.MaxJsonLength = 5000000;
     String json = jsSerializer.Serialize(listUsuario());
     return json;
 }
        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);
        }
Пример #21
0
        public IEnumerable<IMessage> GetMessages()
        {
            var xml = "<Messages>" + MessagesScriptAsXml + "</Messages>";

            var xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(xml);

            var messages = new List<IMessage>();

            foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
            {
                var type = node.Attributes["type"].Value;
                var messageType = node.Attributes["messageType"].Value;
                var serializedMessage = node.InnerXml;

                var actualType = Type.GetType(type);

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

                var message = serializer.Deserialize(serializedMessage, actualType) as IMessage;

                messages.Add(message);
            }

            return messages;
        }
        public async Task attemptLogIn()
        {
            if (username == "Username" || password == "1234567")
            {
                return;
            }
            Dictionary<String, String> attrs = new Dictionary<string, string>();
            attrs["password"] = password;
            attrs["username"] = username;
            string api_sig = signMethod("auth.getMobileSession", attrs);
            string requestURL = "https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession&username="******"&password="******"&api_key=" + API_KEY + "&api_sig=" + api_sig +
                "&format=json";

            string auth_response = await fetchURL(requestURL);
            
            if (auth_response == "")
            {
                user_key = null;
                return;
            }

            AuthenticationResponse auth = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<AuthenticationResponse>(auth_response);
            user_key = auth.session.key;
            return;
        }
        public void ProcessRequest(HttpContext context)
        {

            context.Response.ContentType = "text/plain";
            //就是将所有的User中的信息添加到主表中 Id, LoginName, Password, Phone, Email, UserState

            List<shaoqi.Model.Announce> list = annBll.GetModelList(" ");
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].AnnContent.Length > 200)
                {
                    list[i].AnnContent = list[i].AnnContent.Substring(0, 200);
                }

                list[i].adminName = adminBll.GetModel(Convert.ToInt32(list[i].AdminId)).LoginName;
            }
            System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();

            //还要查出有多少条记录
            string sqlc = "select count(*) from Announce";
            int count = annBll.GetinfoCount(sqlc);

            var info = new { total = count, rows = list };

            string allinfo = json.Serialize(info);

            context.Response.Write(allinfo);
        }
Пример #24
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.ResultModel result = new NFMT.Common.ResultModel();
            context.Response.ContentType = "text/plain";
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            string documentStr = context.Request.Form["document"];
            string docStocksStr = context.Request.Form["docStocks"];
            string isSubmitAuditStr = context.Request.Form["IsSubmitAudit"];

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

            NFMT.Document.Model.Document document = serializer.Deserialize<NFMT.Document.Model.Document>(documentStr);
            List<NFMT.Document.Model.DocumentStock> docStocks = serializer.Deserialize<List<NFMT.Document.Model.DocumentStock>>(docStocksStr);

            bool isSubmitAudit = false;
            if (string.IsNullOrEmpty(isSubmitAuditStr) || !bool.TryParse(isSubmitAuditStr, out isSubmitAudit))
                isSubmitAudit = false;

            NFMT.Document.BLL.DocumentBLL bll = new NFMT.Document.BLL.DocumentBLL();
            result = bll.Create(user, document, docStocks, isSubmitAudit);

            if (result.ResultStatus == 0)
                result.Message = "制单新增成功";

            string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(result);
            context.Response.Write(jsonStr);
        }
        private static Dictionary<string, List<Dictionary<string, object>>> Parse(string jsonString)
        {
            if (jsonString == null || jsonString == String.Empty)
                throw new ArgumentNullException("jsonString");

            Dictionary<string, ArrayList> jsonContent = null;
            try
            {
                jsonContent = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, ArrayList>>(jsonString);
            }
            catch
            {
                throw new InvalidCastException("jsonString");
            }

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

            foreach (KeyValuePair<string, ArrayList> arrayElement in jsonContent)
            {
                List<Dictionary<string, object>> temp = new List<Dictionary<string, object>>();
                foreach (object obj in arrayElement.Value)
                {
                    temp.Add((Dictionary<string, object>)(obj));
                }

                result.Add(arrayElement.Key, temp);
            }

            return result;
        }         
Пример #26
0
 public string ConvertDataTabletoString(string bib)
 {
     DataTable dt = new DataTable();
     using (SqlConnection con = new SqlConnection("Data Source=184.168.194.70;Initial Catalog=ittitudeworks;User ID=rakesh123; Password=Rakesh@123; Trusted_Connection=False"))
     {
         using (SqlCommand cmd = new SqlCommand("select * from all_triathlon_timing where BIBNumber='" + bib.ToString() + "'", con))
         {
             con.Open();
             SqlDataAdapter da = new SqlDataAdapter(cmd);
             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);
             }
             return serializer.Serialize(rows);
         }
     }
 }
Пример #27
0
        public ActionResult Payment(int id)
        {
            var model = new Models.Peyment();
            using (var db = new DataAccess.PeymentContext())
            {
                var entity = db.Orders.Find(id);
                if (entity == null)
                {
                    return RedirectToAction("Index", "Home", null);
                }

                model.Total = entity.Total;
                model.OrderId = entity.Id;

                callback_url = string.Format(callback_url, model.OrderId, entity.Secret);
                callback_url = Uri.EscapeDataString(callback_url);
                BaseUrl = string.Format(BaseUrl, xpub, callback_url, key);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                var value = new StreamReader(resStream).ReadToEnd();

                Models.Response res = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Models.Response>(value);

                model.Adderess = res.address;

            }
            return View(model);
        }
Пример #28
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.ResultModel result = new NFMT.Common.ResultModel();
            context.Response.ContentType = "text/plain";
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            string orderStr = context.Request.Form["order"];
            string orderStockInvoiceStr = context.Request.Form["orderStockInvoice"];
            string orderDetailStr = context.Request.Form["orderDetail"];
            string isSubmitAuditStr = context.Request.Form["IsSubmitAudit"];

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

            NFMT.Document.Model.DocumentOrder order = serializer.Deserialize<NFMT.Document.Model.DocumentOrder>(orderStr);
            List<NFMT.Document.Model.OrderStockInvoice> stockInvoices = serializer.Deserialize<List<NFMT.Document.Model.OrderStockInvoice>>(orderStockInvoiceStr);
            NFMT.Document.Model.DocumentOrderDetail detail = serializer.Deserialize<NFMT.Document.Model.DocumentOrderDetail>(orderDetailStr);

            bool isSubmitAudit = false;
            if (string.IsNullOrEmpty(isSubmitAuditStr) || !bool.TryParse(isSubmitAuditStr, out isSubmitAudit))
                isSubmitAudit = false;

            NFMT.Document.BLL.DocumentOrderBLL bll = new NFMT.Document.BLL.DocumentOrderBLL();
            result = bll.Create(user, order, stockInvoices, detail, isSubmitAudit);

            if (result.ResultStatus == 0)
                result.Message = "制单指令新增成功";

            string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(result);
            context.Response.Write(jsonStr);
        }
Пример #29
0
        //public HttpResponseMessage<JsonPReturn> Get(int id, string callback)
        // Changed for Web Api RC
        // GET /api/values/5
        public string Get()
        {
            var _response = new JsonResponseMessage();
            var jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            _response.IsSucess = true;
            _response.Message = string.Empty;
            _response.CallBack = string.Empty;
            _response.ResponseData = "This is a test";

            //context.Response.Write(jSearializer.Serialize(_response));
            // return Request.CreateResponse(HttpStatusCode.Created, "{'id':'" + id.ToString(CultureInfo.InvariantCulture) + "','data':'Hello JSONP'}");

            //var ret =
            //    new HttpResponseMessage<JsonPReturn>(
            //        new JsonPReturn
            //            {
            //                CallbackName = callback,
            //                Json = "{'id':'" + id.ToString(CultureInfo.InvariantCulture) + "','data':'Hello JSONP'}"
            //            });

            //ret.Content.Headers.ContentType = new MediaTypeHeaderValue("application/javascript");
            //return ret;
            return jSearializer.Serialize(_response);
        }
        static To2LetterCountryCodeConverter()
        {
            var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            allCountries = jsSerializer.Deserialize <Dictionary <string, string> >("{'BGD': 'BD', 'BEL': 'BE', 'BFA': 'BF', 'BGR': 'BG', 'BIH': 'BA', 'BRB': 'BB', 'WLF': 'WF', 'BLM': 'BL', 'BMU': 'BM', 'BRN': 'BN', 'BOL': 'BO', 'BHR': 'BH', 'BDI': 'BI', 'BEN': 'BJ', 'BTN': 'BT', 'JAM': 'JM', 'BVT': 'BV', 'BWA': 'BW', 'WSM': 'WS', 'BES': 'BQ', 'BRA': 'BR', 'BHS': 'BS', 'JEY': 'JE', 'BLR': 'BY', 'BLZ': 'BZ', 'RUS': 'RU', 'RWA': 'RW', 'SRB': 'RS', 'TLS': 'TL', 'REU': 'RE', 'TKM': 'TM', 'TJK': 'TJ', 'ROU': 'RO', 'TKL': 'TK', 'GNB': 'GW', 'GUM': 'GU', 'GTM': 'GT', 'SGS': 'GS', 'GRC': 'GR', 'GNQ': 'GQ', 'GLP': 'GP', 'JPN': 'JP', 'GUY': 'GY', 'GGY': 'GG', 'GUF': 'GF', 'GEO': 'GE', 'GRD': 'GD', 'GBR': 'GB', 'GAB': 'GA', 'SLV': 'SV', 'GIN': 'GN', 'GMB': 'GM', 'GRL': 'GL', 'GIB': 'GI', 'GHA': 'GH', 'OMN': 'OM', 'TUN': 'TN', 'JOR': 'JO', 'HRV': 'HR', 'HTI': 'HT', 'HUN': 'HU', 'HKG': 'HK', 'HND': 'HN', 'HMD': 'HM', 'VEN': 'VE', 'PRI': 'PR', 'PSE': 'PS', 'PLW': 'PW', 'PRT': 'PT', 'SJM': 'SJ', 'PRY': 'PY', 'IRQ': 'IQ', 'PAN': 'PA', 'PYF': 'PF', 'PNG': 'PG', 'PER': 'PE', 'PAK': 'PK', 'PHL': 'PH', 'PCN': 'PN', 'POL': 'PL', 'SPM': 'PM', 'ZMB': 'ZM', 'ESH': 'EH', 'EST': 'EE', 'EGY': 'EG', 'ZAF': 'ZA', 'ECU': 'EC', 'ITA': 'IT', 'VNM': 'VN', 'SLB': 'SB', 'ETH': 'ET', 'SOM': 'SO', 'ZWE': 'ZW', 'SAU': 'SA', 'ESP': 'ES', 'ERI': 'ER', 'MNE': 'ME', 'MDA': 'MD', 'MDG': 'MG', 'MAF': 'MF', 'MAR': 'MA', 'MCO': 'MC', 'UZB': 'UZ', 'MMR': 'MM', 'MLI': 'ML', 'MAC': 'MO', 'MNG': 'MN', 'MHL': 'MH', 'MKD': 'MK', 'MUS': 'MU', 'MLT': 'MT', 'MWI': 'MW', 'MDV': 'MV', 'MTQ': 'MQ', 'MNP': 'MP', 'MSR': 'MS', 'SEÑMRT': 'OR', 'IMN': 'IM', 'UGA': 'UG', 'TZA': 'TZ', 'MYS': 'MIS', 'MEX': 'MX', 'ISR': 'IL', 'FRA': 'FR', 'IOT': 'IO', 'SHN': 'SH', 'FIN': 'FI', 'FJI': 'FJ', 'FLK': 'FK', 'FSM': 'FM', 'FRO': 'FO', 'NIC': 'NI', 'NLD': 'NL', 'NOR': 'NO', 'NAM': 'NA', 'VUT': 'VU', 'NCL': 'NC', 'NER': 'NE', 'NFK': 'NF', 'NGA': 'NG', 'NZL': 'NZ', 'NPL': 'NP', 'NRU': 'NR', 'NIU': 'NU', 'C*K': 'CK', 'XKX': 'XK', 'CIV': 'CI', 'CHE': 'CH', 'COL': 'CO', 'CHN': 'CN', 'CMR': 'CM', 'CHL': 'CL', 'CCK': 'CC', 'CAN': 'CA', 'COG': 'CG', 'CAF': 'CF', 'COD': 'CD', 'CZE': 'CZ', 'CYP': 'CY', 'CXR': 'CX', 'CRI': 'CR', 'CUW': 'CW', 'CPV': 'CV', 'CUB': 'CU', 'SWZ': 'SZ', 'SYR': 'SY', 'SXM': 'SX', 'KGZ': 'KG', 'KEN': 'KE', 'SSD': 'SS', 'SUR': 'SR', 'KIR': 'KI', 'KHM': 'KH', 'KNA': 'KN', 'COM': 'KM', 'STP': 'ST', 'SVK': 'SK', 'KOR': 'KR', 'SVN': 'SI', 'PRK': 'KP', 'KWT': 'KW', 'SEN': 'SN', 'SMR': 'SM', 'SLE': 'SL', 'SYC': 'SC', 'KAZ': 'KZ', 'CYM': 'KY', 'SGP': 'SG', 'SWE': 'SE', 'SDN': 'SD', 'DOM': 'DO', 'DMA': 'DM', 'DJI': 'DJ', 'DNK': 'DK', 'VGB': 'VG', 'DEU': 'DE', 'YEM': 'YE', 'DZA': 'DZ', 'USA': 'US', 'URY': 'UY', 'MYT': 'YT', 'UMI': 'UM', 'LBN': 'LB', 'LCA': 'LC', 'LAO': 'LA', 'TUV': 'TV', 'TWN': 'TW', 'TTO': 'TT', 'TUR': 'TR', 'LKA': 'LK', 'LIE': 'LI', 'LVA': 'LV', 'TON': 'TO', 'LTU': 'LT', 'LUX': 'LU', 'LBR': 'LR', 'LSO': 'LS', 'THA': 'TH', 'ATF': 'TF', 'TGO': 'TG', 'TCD': 'TD', 'TCA': 'TC', 'LBY': 'LY', 'VAT': 'VA', 'VCT': 'VC', 'ARE': 'AE', 'AND': 'AD', 'ATG': 'AG', 'AFG': 'AF', 'AIA': 'AI', 'VIR': 'VI', 'ISL': 'IS', 'IRN': 'IR', 'ARM': 'AM', 'ALB': 'AL', 'AGO': 'AO', 'ATA': 'AQ', 'ASM': 'AS', 'ARG': 'AR', 'AUS': 'AU', 'AUT': 'AT', 'ABW': 'AW', 'IND': 'IN', 'ALA': 'AX', 'AZE': 'AZ', 'IRL': 'IE', 'IDN': 'ID', 'UKR': 'UA', 'QAT': 'QA', 'MOZ': 'MZ'}");
        }
Пример #31
0
        protected override void SolveInstance(IGH_DataAccess da)
        {
            var jserializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            var point_evaluator = new Section.PointEvaluator();

            var resulting_points = new List <Point3d>();
            var resulting_curves = new List <Curve>();

            // read variables
            foreach (var json in da.GetDataList <string>(0))
            {
                var v = jserializer.Deserialize <Section.Variable>(json);
                if (v != null)
                {
                    point_evaluator.AddVariable(v.Name, v.Value);
                }
            }

            // read sectional points
            var qpoints = new List <Section.Point>();

            foreach (var json in da.GetDataList <string>(1))
            {
                var p = jserializer.Deserialize <Section.Point>(json);
                if (p != null)
                {
                    qpoints.Add(p);
                }
            }

            // evaluate sectional points
            var gpoints = point_evaluator.EvaluatePoints(qpoints);

            if (gpoints.Count > 0)
            {
                resulting_points.AddRange(gpoints);
            }


            // read polygons and evaluate points
            foreach (var json in da.GetDataList <string>(2))
            {
                var poly = jserializer.Deserialize <Section.Polygon>(json);
                if (poly != null)
                {
                    gpoints = point_evaluator.EvaluatePoints(poly.Points);
                    if (gpoints.Count > 1)
                    {
                        if (gpoints.First().DistanceTo(gpoints.Last()) > 1.0E-4) // close polygon
                        {
                            gpoints.Add(gpoints.First());
                        }

                        resulting_curves.Add(new PolylineCurve(gpoints));
                    }
                }
            }
            da.SetDataList(0, resulting_points);
            da.SetDataList(1, resulting_curves);
        }
Пример #32
0
        public ActionResult Detail()
        {
            string shebei_code = Request["code"] ?? "";

            ViewData["shebei_code"] = shebei_code;

            var zqyl_day_list  = new List <object>();
            var zqwd_day_list  = new List <object>();
            var zqgd_day_list  = new List <object>();
            var yqhy_day_list  = new List <object>();
            var zqyl_week_list = new List <object>();
            var zqwd_week_list = new List <object>();
            var zqgd_week_list = new List <object>();
            var yqhy_week_list = new List <object>();

            //获取该锅炉的24小时数据
            using (var context = new gatewayEntities())
            {
                var tempDate = DateTime.Now.AddHours(-24);
                var day_list = context.Data1.Where(i => i.ShiJian > tempDate && i.SheBei == shebei_code).OrderBy(i => i.ShiJian).ToList();
                foreach (var guolu in day_list)
                {
                    string temp_str = ((DateTime)guolu.ShiJian).Day.ToString() + "日" + ((DateTime)guolu.ShiJian).Hour + "时";
                    zqyl_day_list.Add(new { x = temp_str, y = guolu.ZQYL02 });
                    zqwd_day_list.Add(new { x = temp_str, y = guolu.ZQWD01 });
                    zqgd_day_list.Add(new { x = temp_str, y = guolu.ZQGD17 });
                    yqhy_day_list.Add(new { x = temp_str, y = guolu.YQHY20 });
                }
            }
            //获取该锅炉的一周数据
            using (var context = new gatewayEntities())
            {
                var tempDate  = DateTime.Now.AddDays(-7);
                var week_list = context.Data1.Where(i => i.ShiJian > tempDate && i.SheBei == shebei_code).OrderBy(i => i.ShiJian).ToList();
                foreach (var guolu in week_list)
                {
                    string temp_str = ((DateTime)guolu.ShiJian).Month.ToString() + "月" + ((DateTime)guolu.ShiJian).Day + "日";
                    zqyl_week_list.Add(new { x = temp_str, y = guolu.ZQYL02 });
                    zqwd_week_list.Add(new { x = temp_str, y = guolu.ZQWD01 });
                    zqgd_week_list.Add(new { x = temp_str, y = guolu.ZQGD17 });
                    yqhy_week_list.Add(new { x = temp_str, y = guolu.YQHY20 });
                }
            }
            var seri = new System.Web.Script.Serialization.JavaScriptSerializer();

            var day_arr = new
            {
                xScale = "ordinal",
                type   = "line-dotted",
                yScale = "linear",
                main   = new List <object>()
                {
                    new { data = zqyl_day_list },
                    new { data = zqwd_day_list },
                    new { data = zqgd_day_list },
                    new { data = yqhy_day_list }
                }
            };
            var week_arr = new
            {
                xScale = "ordinal",
                type   = "line-dotted",
                yScale = "linear",
                main   = new List <object>()
                {
                    new { data = zqyl_week_list },
                    new { data = zqwd_week_list },
                    new { data = zqgd_week_list },
                    new { data = yqhy_week_list }
                }
            };

            ViewData["day_data"]  = seri.Serialize(day_arr);
            ViewData["week_data"] = seri.Serialize(week_arr);
            ViewData["action"]    = "detail_data";
            return(View());
        }
Пример #33
0
        public ActionResult History()
        {
            string shebei_code = Request["code"] ?? "";

            ViewData["shebei_code"] = shebei_code;
            string start_time = Request["start_time"] ?? DateTime.Now.ToShortDateString();
            string end_time   = Request["end_time"] ?? DateTime.Now.AddDays(1).ToShortDateString();
            string Chang      = (Request["Chang"] ?? "").Trim();
            string Zhan       = (Request["Zhan"] ?? "").Trim();
            string GuoLu      = (Request["GuoLu"] ?? "").Trim();
            string ShuXing    = (Request["ShuXing"] ?? "").Trim();

            var           sx_list    = new List <object>();
            List <string> Chang_list = null;
            List <string> Zhan_list  = null;
            List <string> GuoLu_list = null;
            Dictionary <string, string> ShuXing_list = null;

            //获取该锅炉的24小时数据
            using (var context = new gatewayEntities())
            {
                System.Data.Objects.ObjectResult <ShuXingData> time_list = null;
                if (!string.IsNullOrEmpty(ShuXing))
                {
                    time_list = context.ExecuteStoreQuery <ShuXingData>("select " + ShuXing + " as ShuXing, ShiJian from Data1 where Chang={0} and Zhan={1} and GuoLu={2} and ShiJian>={3} and ShiJian<{4}", Chang, Zhan, GuoLu, start_time + " 00:00:00", end_time + " 00:00:00");
                }
                if (time_list != null)
                {
                    var tempList = time_list.ToList();
                    foreach (var item in tempList)
                    {
                        string temp_str = ((DateTime)item.ShiJian).Day.ToString() + "日" + ((DateTime)item.ShiJian).Hour + "时";
                        sx_list.Add(new { x = temp_str, y = item.ShuXing });
                    }
                }
                GuoLu_list = context.Data1.Select(i => i.GuoLu.Trim()).Distinct().ToList();

                Chang_list   = context.Data1.Select(i => i.Chang.Trim()).Distinct().ToList();
                Zhan_list    = context.Data1.Select(i => i.Zhan.Trim()).Distinct().ToList();
                GuoLu_list   = context.Data1.Select(i => i.GuoLu.Trim()).Distinct().ToList();
                ShuXing_list = new Dictionary <string, string>();
                #region 属性配置
                ShuXing_list.Add("ZQWD01", "蒸汽温度℃");
                ShuXing_list.Add("YQHY20", "烟气含氧量%");
                ShuXing_list.Add("ZQGD17", "蒸汽干度%");
                ShuXing_list.Add("ZQYL02", "蒸汽压力Mpa");
                ShuXing_list.Add("GSLL10", "给水流量t/h");
                ShuXing_list.Add("FSWD09", "辐入温度℃");
                ShuXing_list.Add("DRWD08", "对流入口温度℃");
                ShuXing_list.Add("DCWD07", "对流出口温度℃");
                ShuXing_list.Add("RYYL", "燃油压力Mpa");
                ShuXing_list.Add("GBWD05", "管壁温度℃");
                ShuXing_list.Add("WKWD04", "瓦口温度℃");
                ShuXing_list.Add("PYWD03", "排烟温度℃");
                ShuXing_list.Add("RQLJ", "燃气累计m3");
                ShuXing_list.Add("RYLJ", "燃油累计t");
                ShuXing_list.Add("SLLJQ", "水量累计t(燃气时)");
                ShuXing_list.Add("SLLJY", "水量累计t(燃油时)");
                ShuXing_list.Add("RQDH", "燃气单耗m3/t");
                ShuXing_list.Add("RYDH", "燃油单耗m3/t");
                ShuXing_list.Add("YDDH", "用电单耗 kw.h/t");
                ShuXing_list.Add("YDLJ", "用电累计kw.h");
                ShuXing_list.Add("GFPL14", "鼓风频率");
                //ShuXing_list.Add("RYLJ", "燃油流量t/h");??????????????????????????????????
                ShuXing_list.Add("RYLL16", "燃气流量m3/h");
                #endregion
            }
            var seri = new System.Web.Script.Serialization.JavaScriptSerializer();

            var day_arr = new
            {
                xScale = "ordinal",
                type   = "line-dotted",
                yScale = "linear",
                main   = new List <object>()
                {
                    new { data = sx_list }
                }
            };

            ViewData["Chang"]        = Chang;
            ViewData["Zhan"]         = Zhan;
            ViewData["GuoLu"]        = GuoLu;
            ViewData["ShuXing"]      = ShuXing;
            ViewData["time_data"]    = seri.Serialize(day_arr);
            ViewData["action"]       = "history_data";
            ViewData["Chang_list"]   = Chang_list;
            ViewData["Zhan_list"]    = Zhan_list;
            ViewData["GuoLu_list"]   = GuoLu_list;
            ViewData["ShuXing_list"] = ShuXing_list;
            ViewData["GuoLu"]        = GuoLu;
            ViewData["start_time"]   = start_time;
            ViewData["end_time"]     = end_time;
            return(View());
        }
Пример #34
0
    public static IList <GoodsOrderInfo> GetGoodsOrderInfoList(string nick, DateTime start, DateTime end, string session, string orderState)
    {
        bool notlast = true;
        int  page_no = 0;

        List <GoodsOrderInfo> list = new List <GoodsOrderInfo>();

        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
        while (notlast)
        {
            page_no++;
            Dictionary <string, string> dic = new Dictionary <string, string>();
            dic.Add("start_created", start.ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("end_created", end.ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("use_has_next", "true");
            dic.Add("page_size", "100");
            dic.Add("page_no", page_no.ToString());
            dic.Add("status", orderState);//"TRADE_FINISHED");
            dic.Add("fields", "total_fee,receiver_state,receiver_city,commission_fee,payment,cod_fee,end_time,pay_time,created,post_fee,tid,commission_fee,seller_nick,buyer_nick,orders.num_iid,orders.num,orders.status");
            string text = Post(nick, "taobao.trades.sold.get", session, dic, DataFormatType.json);
            if (!string.IsNullOrEmpty(text))
            {
                if (text.Contains("error_response"))
                {
                    LogInfo.WriteLog("获取订单参数错误" + session, text);
                    return(null);
                }
                string index = "{\"trades_sold_get_response\":{\"has_next\":true,\"trades\":{\"trade\":[";
                if (!text.Contains(index))
                {
                    index   = "{\"trades_sold_get_response\":{\"has_next\":false,\"trades\":{\"trade\":[";
                    notlast = false;
                }

                Regex regex = new Regex(",\"total_results\":\\d+}}", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                if (new Regex("\"total_results\":\\d+}}", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(text).Value == "\"total_results\":0}}")
                {
                    return(list);
                }

                text = regex.Replace(text, "");

                text = text.Replace("{\"order\":", "");
                text = text.Replace("},\"pay_time", ",\"pay_time");
                //货到付情况下
                text = text.Replace("},\"payment\"", ",\"payment\"");

                text = text.Replace(index, "");
                text = "[" + text.Substring(0, text.Length - 1);
                try
                {
                    list.AddRange(js.Deserialize <List <GoodsOrderInfo> >(text));
                    //for (int i = 0; i < list.Count; i++)
                    //{
                    //    if (list[i].orders.Count > 1)
                    //    {
                    //        string s = list[i].tid;
                    //    }
                    //}
                }
                catch (Exception ex)
                {
                    LogInfo.WriteLog("获取订单转换出错", text + ex.Message);
                }
            }
        }
        return(list);
    }
Пример #35
0
        /// <summary>
        /// Default json deserializer. Requires a reference to System.Web.Extensions.
        /// </summary>
        public static Dictionary <string, dynamic> FromString(string json)
        {
            var deserializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            return(deserializer.Deserialize <Dictionary <string, dynamic> >(json));
        }
        private void checkForUpdates()
        {
            try
            {
                WebClient fetcher = (new WebClient());
                fetcher.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)");
                var           content         = fetcher.DownloadString("https://api.github.com/repos/MarshallOfSound/Google-Play-Music-Desktop-Player-UNOFFICIAL-/releases/latest");
                GithubRelease g               = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <GithubRelease>(content);
                string        version         = g.tag_name;
                string        changeLog       = g.body;
                string        download_URL_32 = "";
                string        download_URL_64 = "";
                foreach (Asset a in g.assets)
                {
                    Regex test  = new Regex(@"x64");
                    Match match = test.Match(a.browser_download_url);
                    if (match.Success)
                    {
                        download_URL_64 = a.browser_download_url;
                    }
                    else
                    {
                        download_URL_32 = a.browser_download_url;
                    }
                }
                string downloadURL = (is64BitProcess ? download_URL_64 : download_URL_32);
                if (downloadURL == "")
                {
                    return;
                }

                // If the newest version is not the current version there must be an update available
                if (version != CURRENT_VERSION)
                {
                    UpdateDialog dialog = new UpdateDialog(changeLog, CURRENT_VERSION, version);
                    var          result = dialog.ShowDialog(this);
                    dialog.Dispose();
                    if (result == DialogResult.Yes)
                    {
                        // Download the Resource URL from the GitHub API
                        Process.Start(downloadURL);
                        // Let the form finish initialising before closing it through an asyncronous method invoker
                        // Prevents strange garbage collection
                        new Thread(() =>
                        {
                            Load += (send, ev) =>
                            {
                                GPMBrowser.IsBrowserInitializedChanged += (res, se) =>
                                {
                                    if (GPMBrowser.IsBrowserInitialized)
                                    {
                                        Close();
                                    }
                                };
                            };
                        }).Start();
                        return;
                    }
                }
            }
            catch (Exception)
            {
                // Something went wrong while fetching from the GitHub API
            }
        }
Пример #37
0
    public static object Get_Resumen(Int32 codC)
    {
        String fl_seguir   = "0";
        String msg_retorno = String.Empty;
        object strRetorno;
        object oDatosCita = null;

        try
        {
            Int32 nid_cita = codC;

            fl_seguir = "1";
            CitasBL     oCitasBL     = new CitasBL();
            CitasBE     oCitasBE     = new CitasBE();
            CitasBEList oCitasBEList = new CitasBEList();
            oCitasBE.nid_cita = nid_cita;
            oCitasBEList      = oCitasBL.Listar_Datos_Cita(oCitasBE);
            oCitasBE          = new CitasBE();
            oCitasBE          = oCitasBEList[0];

            CorreoElectronico oEmail = new CorreoElectronico(HttpContext.Current.Server.MapPath("~/"));
            //>> Llenado para la Impresion
            string  strImpresion = oEmail.CargarPlantilla_Imprimir(oCitasBE, Parametros.EstadoCita.REGISTRADA).ToString();
            Boolean fl_confirmar = !(oCitasBL.BuscarCitaPorCodigo(oCitasBE)[0].nu_estado.Equals(4));

            if (ConfigurationManager.AppSettings["MostrarMensajeRegistro"].Equals("1"))
            {
                msg_retorno = (ConfigurationManager.AppSettings["msgCitaRegistrada"].ToString());
            }

            //Set Datos Cita
            oDatosCita = new
            {
                template_impresion = strImpresion,
                fl_confirmar       = fl_confirmar,
                //-------------------------
                nid_cita           = oCitasBE.nid_cita,
                nu_estado          = oCitasBE.nu_estado,
                co_reserva         = " " + oCitasBE.cod_reserva_cita,
                no_taller          = Parametros.N_Taller + ": " + oCitasBE.no_taller,
                no_asesor          = Parametros.N_Asesor + ": " + oCitasBE.no_asesor,
                fe_programada      = "Fecha: " + oCitasBE.fecha_prog,
                ho_programada      = "Hora: " + FormatoHora(oCitasBE.ho_inicio_c),
                nu_telf_taller     = Parametros.N_TelefonoTaller + ": " + oCitasBE.nu_telefono_t,
                nu_cel_asesor      = Parametros.N_CellAsesor + ": " + oCitasBE.nu_telefono_a,
                nu_telf_callcenter = Parametros.N_TelefonoCall + ": "
                                     + (oCitasBE.nid_taller_empresa.Equals(0) ? Parametros.N_TelefonoCallCenter : (string.IsNullOrEmpty(oCitasBE.nu_callcenter) ? Parametros.N_TelefonoCallCenter : oCitasBE.nu_callcenter))
            };

            strRetorno = new
            {
                fl_seguir   = fl_seguir,
                msg_retorno = msg_retorno,
                oDatosCita  = oDatosCita
            };
        }
        catch (Exception ex)
        {
            strRetorno = new
            {
                fl_seguir   = "-1",
                msg_retorno = "Error: " + ex.Message,
                oDatosCita  = oDatosCita
            };
        }

        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return(serializer.Serialize(strRetorno));
    }
Пример #38
0
        public ActionResult SaveMusic(string editedMusic, HttpPostedFileBase WAVFile, HttpPostedFileBase MP3File, string tagIdsStr)
        {
            ResponseBase     res       = new ResponseBase();
            var              serl      = new System.Web.Script.Serialization.JavaScriptSerializer();
            MusicSearchModel music     = serl.Deserialize <MusicSearchModel>(editedMusic);
            var              dbResTags = new List <Tag>();

            if (tagIdsStr != null && tagIdsStr.Length > 0)
            {
                IEnumerable <Guid> tagIds = tagIdsStr.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                                            .Select(t => Guid.Parse(t));
                if (tagIds.Any())
                {
                    dbResTags = _tgService.GetTagList(tagIds)
                                .Entities
                                .Where(t => t.IsPublicTag)
                                .ToList();
                }
            }

            var         user = User.GetUser();
            MusicHelper mh   = new MusicHelper();

            if (music.ID == null)
            {
                Music msc = new Music();
                msc.CreateDate = DateTime.Now;
                msc.ArtistID   = user.Id;
                msc.Artist     = user.Artist;
                msc.Status     = MusicActiveStatus.New;
                msc.Tags       = dbResTags;
                var newInSystemTagRes = _tgService.GetNewInSystemTag();
                if (newInSystemTagRes.Success)
                {
                    msc.Tags.Add(newInSystemTagRes.Entity);
                }
                var files = mh.SetMusicBeforeUpDateForArtist(msc, music, WAVFile, MP3File);
                res = _mscService.Add(msc, files.wavFile, files.mp3File);
                if (res.Success)
                {
                    var confirm = new Confirmation();
                    confirm.ConfirmType = ConfirmType.NewMusic;
                    confirm.DateUpdate  = DateTime.Now;
                    confirm.Name        = msc.HebrewName;
                    confirm.EntityId    = msc.ID.ToString();
                    res = _cnfrmService.Add(confirm);
                }
            }
            else
            {
                var getMusicRes = _mscService.GetByID(music.ID.Value);
                if (getMusicRes.Success && getMusicRes.Entity.ArtistID == user.Id)
                {
                    var msc = new Music(getMusicRes.Entity);
                    msc.Tags = msc.Tags
                               .Where(t => !t.IsPublicTag)
                               .Union(dbResTags)
                               .ToList();
                    var files = mh.SetMusicBeforeUpDateForArtist(msc, music, WAVFile, MP3File);

                    if (msc.Status == MusicActiveStatus.Public)
                    {
                        msc.Status        = MusicActiveStatus.WaitingForConfirm;
                        msc.SourceMusicId = getMusicRes.Entity.ID;
                        msc.ID            = 0;
                        res = _mscService.Add(msc, files.wavFile, files.mp3File);
                        if (res.Success)
                        {
                            getMusicRes.Entity.Status = MusicActiveStatus.Edited;
                            var confirm = new Confirmation();
                            confirm.ConfirmType = ConfirmType.UpdateMusic;
                            confirm.DateUpdate  = DateTime.Now;
                            confirm.Name        = msc.HebrewName;
                            confirm.EntityId    = msc.ID.ToString();
                            res = _cnfrmService.Add(confirm);
                        }
                    }
                    else if (msc.Status == MusicActiveStatus.New || msc.Status == MusicActiveStatus.WaitingForConfirm)
                    {
                        var confirmRes = _cnfrmService.GetByEntityId(msc.ID.ToString());
                        if (confirmRes.Success && confirmRes.Entity == null)
                        {
                            var confirm = new Confirmation();
                            confirm.ConfirmType =
                                msc.Status == MusicActiveStatus.New
                                    ? ConfirmType.NewMusic
                                    : ConfirmType.UpdateMusic;
                            confirm.DateUpdate = DateTime.Now;
                            confirm.Name       = msc.HebrewName;
                            confirm.EntityId   = msc.ID.ToString();
                            res = _cnfrmService.Add(confirm);
                        }
                        res = _mscService.Update(msc, msc.ID, files.wavFile, files.mp3File);
                    }
                }
                else
                {
                    res.Success = false;
                }
            }

            return(Json(res));
        }
        /// <summary>
        /// Writes the value of the current instance of the class to the output stream.
        /// </summary>
        /// <param name="output">The output stream.</param>
        /// <param name="bufferSize">Buffer size.</param>
        /// <param name="outputStatus">To parameter is passed information about the state of the writes to stream.</param>
        /// <param name="contentType">The type of content.</param>
        /// <param name="codePage">The character encoding.</param>
        public void WriteToStream(Stream output, int bufferSize, StreamWriteEventArgs outputStatus, string contentType, Encoding codePage)
        {
            if (this.Value == null)
            {
                return;
            }

            if (output == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException("The value of the bufferSize must be greater than zero.");
            }

            if (outputStatus == null)
            {
                outputStatus = new StreamWriteEventArgs();
            }

            if (this.Value.GetType() == typeof(byte[]))
            {
                output.Write((byte[])this.Value, 0, ((byte[])this.Value).Length);
                outputStatus.BytesWritten = ((byte[])this.Value).Length;
            }
            else if (this.Value.GetType() == typeof(Stream) || this.Value.GetType().IsSubclassOf(typeof(Stream)))
            {
                if (((Stream)this.Value).CanSeek)
                {
                    ((Stream)this.Value).Position = 0;
                }

                using (BinaryReader br = new BinaryReader((Stream)this.Value))
                {
                    int    bytesRead = 0;
                    byte[] buffer    = new byte[bufferSize];

                    while ((bytesRead = br.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        output.Write(buffer, 0, bytesRead);
                        outputStatus.BytesWritten = bytesRead;
                    }
                }
            }

            /*else if (this.Value.GetType() == typeof(string) || this.Value.GetType() == typeof(char) || this.Value.GetType() == typeof(StringBuilder))
             * {
             * var buffer = codePage.GetBytes(this.Value.ToString());
             * output.Write(buffer, 0, buffer.Length);
             * outputStatus.BytesWritten = buffer.Length;
             * }*/
            else
            {
                string dataToWrite = "";

                if (contentType == null)
                {
                    contentType = "";
                }

                contentType = contentType.ToLower();

                if (contentType.Contains("json"))
                {
                    dataToWrite = new System.Web.Script.Serialization.JavaScriptSerializer()
                    {
                        MaxJsonLength  = int.MaxValue,
                        RecursionLimit = int.MaxValue
                    }.Serialize(this.Value);
                }
                else if (contentType.Contains("xml"))
                {
                    using (var m = new MemoryStream())
                    {
                        new System.Xml.Serialization.XmlSerializer(this.Value.GetType()).Serialize(m, this.Value);
                        dataToWrite = codePage.GetString(m.ToArray());
                    }
                }
                else
                {
                    dataToWrite = this.Value.ToString();
                }

                var buffer = codePage.GetBytes(dataToWrite);
                output.Write(buffer, 0, buffer.Length);
                outputStatus.BytesWritten = buffer.Length;
            }
        }
Пример #40
0
 public static string GetArticleList(int startIndex, int maximumRows, string sortExpressions)
 {
     FeedBackList = PSCPortal.CMS.ArticleCommentCollection.GetArticleCommentCollection(artId);
     System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
     return(js.Serialize(FeedBackList.GetSegment(startIndex, maximumRows, sortExpressions)));
 }
        public static void Run(TimerInfo getRewardsTrxReadyForFulfillmentTimer, ICollector <string> errormessage, TraceWriter log)
        {
            try
            {
                if (getRewardsTrxReadyForFulfillmentTimer.IsPastDue)
                {
                    log.Verbose("Timer is running late!", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment");
                }

                //Get RewardsTrx Ready for fulfillment
                List <SqlParameter> objprm = new List <SqlParameter>();
                objprm.Add(new SqlParameter("@RewardTrxStatus", "Ready for fulfillment"));
                List <Common.Model.GetRewardsRequest> lstRewardsTrx = MSSQLConnection.ExecuteStoredProcedure <Common.Model.GetRewardsRequest>(Common.Constants.USPContstants.GetRewardsTrx, objprm).ToList();
                log.Verbose($"Get RewardsTrx Ready for fulfillment:={lstRewardsTrx.Count}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment");

                //Service bus queue names and connection strings
                var connectionString = ConfigurationManager.AppSettings["MyServiceBusReader"].ToString();
                var FulfillmentRequestTopicClient = TopicClient.CreateFromConnectionString(connectionString, "fulfillmentrequest");
                var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

                #region Create Subscrptions for the first time
                //// Create a "EnergyEarthSubscription" filtered subscription.
                if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "EnergyEarthSubscription"))
                {
                    SqlFilter energyEarthFilter = new SqlFilter("channelType = 'EnergyEarth'");
                    namespaceManager.CreateSubscription("fulfillmentrequest", "EnergyEarthSubscription", energyEarthFilter);
                }

                //// Create a "GBASSSubscription" filtered subscription.
                if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "GBASSCTLAdjSubscription"))
                {
                    SqlFilter GBASSFilter = new SqlFilter("channelType = 'GBASSCTLAdj'");
                    namespaceManager.CreateSubscription("fulfillmentrequest", "GBASSCTLAdjSubscription", GBASSFilter);
                }

                if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "GBASSTariffSubscription"))
                {
                    SqlFilter GBASSFilter = new SqlFilter("channelType = 'GBASSTariff'");
                    namespaceManager.CreateSubscription("fulfillmentrequest", "GBASSTariffSubscription", GBASSFilter);
                }

                //// Create a "CRMSubscription" filtered subscription.
                if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "CRMSubscription"))
                {
                    SqlFilter CRMFilter = new SqlFilter("channelType = 'CRM'");
                    namespaceManager.CreateSubscription("fulfillmentrequest", "CRMSubscription", CRMFilter);
                }

                //// Create a "SmartConnectSubscription" filtered subscription.
                if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "SmartConnectSubscription"))
                {
                    SqlFilter SmartConnectFilter = new SqlFilter("channelType = 'SmartConnectCheque'");
                    namespaceManager.CreateSubscription("fulfillmentrequest", "SmartConnectSubscription", SmartConnectFilter);
                }
                #endregion

                RewardFulfillmentRequest RewardsRequestObj = new RewardFulfillmentRequest();
                foreach (Common.Model.GetRewardsRequest item in lstRewardsTrx)
                {
                    RewardFulfillmentRequestList rewardFulfillmentRequestList = new RewardFulfillmentRequestList();
                    rewardFulfillmentRequestList.RewardFulfillmentRequest = new RewardFulfillmentRequest();

                    RewardsRequestObj.RequestId       = item.RequestId;
                    RewardsRequestObj.TransactionType = item.TransactionType;
                    RewardsRequestObj.RMSRewardID     = item.RMSRewardID;

                    RewardsRequestObj.Reward               = new Reward();
                    RewardsRequestObj.Reward.ProductCode   = item.ProductCode;
                    RewardsRequestObj.Reward.ProductValue  = item.ProductValue.ToString();
                    RewardsRequestObj.Reward.ProgramName   = item.ProgramName;
                    RewardsRequestObj.Reward.EffectiveDate = item.EffectiveDate;
                    RewardsRequestObj.Reward.RewardType    = item.RewardType;

                    RewardsRequestObj.Customer                            = new CustomerJSON();
                    RewardsRequestObj.Customer.CustomerID                 = item.CustomerID;
                    RewardsRequestObj.Customer.SourceSystemID             = item.DBSourceSystemID.ToString();
                    RewardsRequestObj.Customer.SourceSystemName           = item.SourceSystemShortName;
                    RewardsRequestObj.Customer.SourceSystemUniqueID       = item.SourceSystemUniqueID;
                    RewardsRequestObj.Customer.SourceSystemUniqueIDType   = item.SourceSystemUniqueIDType;
                    RewardsRequestObj.Customer.MasterID                   = item.MasterID;
                    RewardsRequestObj.Customer.Email                      = item.Email;
                    RewardsRequestObj.Customer.FirstName                  = item.FirstName;
                    RewardsRequestObj.Customer.LastName                   = item.LastName;
                    RewardsRequestObj.Customer.CompanyName                = item.CompanyName;
                    RewardsRequestObj.Customer.AddressLine1               = item.AddressLine1;
                    RewardsRequestObj.Customer.AddressLine2               = item.AddressLine2;
                    RewardsRequestObj.Customer.City                       = item.City;
                    RewardsRequestObj.Customer.StateProvince              = item.StateProvince;
                    RewardsRequestObj.Customer.ZipPostalCode              = item.ZipPostalCode;
                    RewardsRequestObj.Customer.Phone1                     = item.Phone1;
                    RewardsRequestObj.Customer.Product                    = item.Product;
                    RewardsRequestObj.Customer.Language                   = item.LanguageCode;
                    RewardsRequestObj.AdditionalData                      = JsonConvert.DeserializeObject <AdditionalData[]>(item.AdditionalData);
                    rewardFulfillmentRequestList.RewardFulfillmentRequest = RewardsRequestObj;
                    var reqObject = JsonConvert.SerializeObject(rewardFulfillmentRequestList);
                    if (item.FulfillmentChannelID != (int)Common.Constants.FulfillmentChannel.EnergyEarth)
                    {
                        var json           = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(reqObject);
                        var serializedJson = (JObject)JsonConvert.DeserializeObject(reqObject);
                        foreach (var response in serializedJson["RewardFulfillmentRequest"]["Customer"])
                        {
                            if (response.Path.Contains("CustomerID"))
                            {
                                response.Remove();
                                break;
                            }
                        }
                        reqObject = JsonConvert.SerializeObject(serializedJson);
                    }

                    log.Verbose($"Reward fulfillment request push to different channel :={reqObject.ToString()}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment");
                    var message = new BrokeredMessage(reqObject);
                    if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.EnergyEarth)
                    {
                        message.Properties["channelType"] = FulfillmentChannel.EnergyEarth.ToString();
                        FulfillmentRequestTopicClient.Send(message);
                    }
                    else if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSTariff)
                    {
                        message.Properties["channelType"] = FulfillmentChannel.GBASSTariff.ToString();
                        FulfillmentRequestTopicClient.Send(message);
                    }
                    else if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSCTLAdj)
                    {
                        message.Properties["channelType"] = FulfillmentChannel.GBASSCTLAdj.ToString();
                        FulfillmentRequestTopicClient.Send(message);
                    }
                    else if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.Cheque)
                    {
                        message.Properties["channelType"] = "SmartConnectCheque";
                        FulfillmentRequestTopicClient.Send(message);
                    }

                    //Call stored procedure to Update RewardTrx
                    List <SqlParameter> RewardTrxParams = new List <SqlParameter>();
                    RewardTrxParams.Add(new SqlParameter("@RewardTrxID", item.RewardTrxID));
                    var RewardTrxID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.UpdateFulfillmentRequestTimestamp, RewardTrxParams);
                    log.Verbose($"RewardTrx updated successfully. RewardTrID={RewardTrxID[0]}", "JE.RMS.Services.EvaluateRewardsTrx");

                    //Call stored procedure to Save MessageLog
                    List <SqlParameter> MessageLogParams = new List <SqlParameter>();
                    MessageLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID));
                    MessageLogParams.Add(new SqlParameter("@MessageType", MessageType.RewardFulfillmentRequest.GetDescription()));
                    MessageLogParams.Add(new SqlParameter("@IPAddress", ""));
                    MessageLogParams.Add(new SqlParameter("@Message", reqObject));
                    MessageLogParams.Add(new SqlParameter("@RMSRewardID", null));
                    var MessageLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveMessageLog, MessageLogParams);
                    log.Verbose($"MessageLog stored successfully. MessageLogID={MessageLogID[0]}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment");


                    //Call stored procedure to Save RewardTrxChangeLog
                    List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>();
                    RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID.ToString()));
                    RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", "Sent for fulfillment"));
                    RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", string.Empty));
                    RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", null));
                    var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams);
                    log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment");
                }

                log.Verbose($"C# Timer trigger function executed at: {DateTime.Now}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment");
            }
            catch (Exception ex)
            {
                log.Error($"Exception ={ex}", ex, "JE.RMS.Services.GetRewardsTrxReadyForFulfillment");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
            }
        }
Пример #42
0
 public static string ObjectToJson <T>(T obj)
 {
     System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();   //实例化一个能够序列化数据的类
     return(js.Serialize(obj));
 }
Пример #43
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(Request.QueryString["id"]))
        {
            newsid.Attributes["ref"] = Request.QueryString["id"];
            string          newsitem      = "<div class='subitem top10 newsitem'><div class='delete-item'>DELETE</div><div class='top10 itemtitle'>~name~</div><div class='formitem top10'><label for='newstitle'>News Title</label><input name='' class='newstitle' value='~title~' /></div><div class='formitem top10'><label for='newstitle'>News Source</label><input name='' class='newssource'  value='~source~' /></div><div class='formitem top10'><label for='newstitle'>News Date</label><input name='' class='newsdate'  value='~date~' /></div><div class='top10'>Story Content</div><textarea class='leadin rtf top10' id='~newsid~'>~content~</textarea></div>";
            string          highlightitem = "<div class='subitem top10 highlightitem'><div class='delete-item'>DELETE</div><div class='top10 itemtitle'>~name~</div><div class='formitem top10'><label for='highlighttitle'>Highlight Title</label><input name='' class='highlighttitle' value='~title~' /></div><div class='formitem top10'><label for='highlightlink'>Highlight Link: Please put the full URL in this field including the 'http://'</label><input name='' class='highlightlink' value='~source~' /></div></div>";
            Entry           item          = new Entry();
            DataTable       dtFB          = null;
            GenericDatabase db            = new GenericDatabase(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, DbProviderFactories.GetFactory("MySql.Data.MySqlClient"));
            DbCommand       cmd           = db.GetSqlStringCommand("Select * from media where id ='" + Request.QueryString["id"] + "'");
            dtFB = db.ExecuteDataSet(cmd).Tables[0];
            cmd.Dispose();
            foreach (DataRow row in dtFB.Rows)
            {
                item.LeadIn         = row["leadin"].ToString();
                item.Count          = row["newscount"].ToString();
                item.NewItems       = row["newsitem"].ToString();
                item.HighlightItems = row["highlightitem"].ToString();
                newsid.InnerText    = row["name"].ToString();
            }
            leadin.Value = item.LeadIn;
            List <News> newitems = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <List <News> >(item.NewItems);
            string      tmp      = "";
            Int32       ctr      = 1;
            foreach (News x in newitems)
            {
                tmp += newsitem.Replace("~name~", "News " + ctr.ToString()).Replace("~title~", x.Title).Replace("~source~", x.Source).Replace("~date~", x.Date).Replace("~newsid~", "news" + ctr.ToString()).Replace("~content~", x.Content);
                ctr++;
            }
            news.InnerHtml = tmp;
            tmp            = "";
            List <Highlight> highitems = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <List <Highlight> >(item.HighlightItems);
            ctr = 1;
            foreach (Highlight x in highitems)
            {
                tmp += highlightitem.Replace("~name~", "Highlight  " + ctr.ToString()).Replace("~title~", x.Title).Replace("~source~", x.Source);
                ctr++;
            }
            highlights.InnerHtml = tmp;
            //leadin.Value = item.LeadIn;
            storycount.Value = item.Count;
        }
        DataTable       dtFBa = null;
        GenericDatabase dba   = new GenericDatabase(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, DbProviderFactories.GetFactory("MySql.Data.MySqlClient"));
        DbCommand       cmda  = dba.GetSqlStringCommand("Select id, name from media order by id desc");

        dtFBa = dba.ExecuteDataSet(cmda).Tables[0];
        cmda.Dispose();
        ListItem mn = new ListItem();

        mn.Text  = "Select Saved Email Template";
        mn.Value = "0";
        ddmenu.Items.Add(mn);
        foreach (DataRow row in dtFBa.Rows)
        {
            mn       = new ListItem();
            mn.Text  = row["name"].ToString();
            mn.Value = row["id"].ToString();
            ddmenu.Items.Add(mn);
        }
    }
Пример #44
0
        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <param name="json">json</param>
        /// <param name="objType">对象类型</param>
        /// <returns></returns>
        public object Deserialize(string json, Type objType)
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            return(serializer.Deserialize(json, objType));
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                StringBuilder sb = new StringBuilder();
                if (!string.IsNullOrEmpty(Request.Form["_r"])
                    ||
                    !string.IsNullOrEmpty(Request.QueryString["_r"])
                    )
                {
                    DirectPost();
                    return;
                }
                if (Request.QueryString["tbl"] != null && Request.QueryString["key"] != null)
                {
                    /* prevent manually constructed request that would lead to information leakage via hashing of
                     * query string and session secret, only apply for database related retrieval which are all generated by the system
                     */
                    if (!string.IsNullOrEmpty(Request.QueryString["_h"]))
                    {
                        ValidateQSV2();
                    }
                    else
                    {
                        ValidatedQS();
                    }
                    string dbConnectionString;
                    if (Request.QueryString["sys"] != null)
                    {
                        sid = byte.Parse(Request.QueryString["sys"].ToString());
                    }
                    else
                    {
                        throw new Exception("Please make sure '&sys=' is present and try again.");
                    }
                    if (new AdminSystem().IsMDesignDb(Request.QueryString["tbl"].ToString()))
                    {
                        dbConnectionString = base.SysConnectStr(sid);
                    }
                    else
                    {
                        dbConnectionString = base.AppConnectStr(sid);
                    }
                    DataTable dt = null;
                    try
                    {
                        if (Request.QueryString["knm"] != null && Request.QueryString["col"] != null)     // ImageButton
                        {
                            string emptyFile = "iVBORw0KGgoAAAANSUhEUgAAAhwAAAABCAQAAAA/IL+bAAAAFElEQVR42mN89p9hFIyCUTAKSAIABgMB58aXfLgAAAAASUVORK5CYII=";
                            dt = (new AdminSystem()).GetDbImg(Request.QueryString["key"].ToString(), Request.QueryString["tbl"].ToString(), Request.QueryString["knm"].ToString(), Request.QueryString["col"].ToString(), dbConnectionString, base.AppPwd(sid));
                            if (Request.QueryString["ico"] != null)
                            {
                                string icon = RO.Common3.Utils.BlobPlaceHolder(dt.Rows[0][0] as byte[], true);
                                if (icon != null)
                                {
                                    icon = icon.Replace("data:application/base64;base64,", "");
                                }
                                else
                                {
                                    icon = emptyFile;
                                }
                                ReturnAsAttachment(Convert.FromBase64String(icon), "");
                                return;
                            }
                            Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent();
                            string fileContent   = dt.Rows[0][0] as byte[] == null ? emptyFile : RO.Common3.Utils.DecodeFileStream(dt.Rows[0][0] as byte[]);
                            string fileName      = "";
                            string mimeType      = "application/octet";
                            string contentBase64 = "";
                            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                            try
                            {
                                RO.Common3.FileUploadObj fileInfo = jss.Deserialize <RO.Common3.FileUploadObj>(fileContent);
                                mimeType      = fileInfo.mimeType;
                                fileName      = fileInfo.fileName;
                                contentBase64 = fileInfo.base64;
                            }
                            catch
                            {
                                try
                                {
                                    List <RO.Common3._ReactFileUploadObj> fileList = jss.Deserialize <List <RO.Common3._ReactFileUploadObj> >(fileContent);
                                    List <FileUploadObj> x = new List <FileUploadObj>();
                                    foreach (var fileInfo in fileList)
                                    {
                                        mimeType      = fileInfo.mimeType;
                                        fileName      = fileInfo.fileName;
                                        contentBase64 = fileInfo.base64;
                                        break;
                                    }
                                }
                                catch
                                {
                                    contentBase64 = fileContent;
                                    fileName      = "";
                                    mimeType      = "image/jpeg";
                                }
                            }

                            string contentDisposition = "attachment";
                            if (!string.IsNullOrEmpty(Request.QueryString["inline"]) && Request.QueryString["inline"] == "Y")
                            {
                                contentDisposition = "inline";
                            }

                            byte[] content = new byte[0];
                            try
                            {
                                content = (byte[])Convert.FromBase64String(contentBase64);
                                Response.ContentType = mimeType;
                                Response.AppendHeader("Content-Disposition", contentDisposition + "; Filename=" + fileName);
                            }
                            catch (Exception ex)
                            {
                                if (ex != null)
                                {
                                    try
                                    {
                                        content = (byte[])dt.Rows[0][0];
                                        Response.ContentType = "image/jpeg";
                                        Response.AppendHeader("Content-Disposition", contentDisposition + "; Filename=");
                                    }
                                    catch { }
                                }
                            }
                            Response.Flush();
                            Response.BinaryWrite(content);
                            Response.End();
                        }
                        else // Document.
                        {
                            dt = (new AdminSystem()).GetDbDoc(Request.QueryString["key"].ToString(), Request.QueryString["tbl"].ToString(), dbConnectionString, base.AppPwd(sid));
                            Response.Buffer      = true; Response.ClearHeaders(); Response.ClearContent();
                            Response.ContentType = dt.Rows[0]["MimeType"].ToString();
                            string contentDisposition = "attachment";
                            if (!string.IsNullOrEmpty(Request.QueryString["inline"]) && Request.QueryString["inline"] == "Y")
                            {
                                contentDisposition = "inline";
                            }
                            Response.AppendHeader("Content-Disposition", contentDisposition + "; Filename=" + dt.Rows[0]["DocName"].ToString());
                            //Response.AppendHeader("Content-Disposition", "Attachment; Filename=" + dt.Rows[0]["DocName"].ToString());
                            Response.BinaryWrite((byte[])dt.Rows[0]["DocImage"]);
                            Response.End();
                        }
                    }
                    catch (Exception err)
                    {
                        if (!(err is ThreadAbortException))
                        {
                            ApplicationAssert.CheckCondition(false, "DnLoadModule", "", err.Message);
                        }
                    }
                }
                else if (Request.QueryString["file"] != null)
                {
                    /* file based download needs to be catered manually by webrule for protected contents
                     * via access control in the IIS directory level(no access) and gated by dnloadmodule via server side transfer
                     */
                    try
                    {
                        bool pub = true;
                        if (LImpr != null)
                        {
                            string[] allowedGroupId = (Config.DownloadGroupLs ?? "5").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            string   UsrGroup       = (char)191 + base.LImpr.UsrGroups + (char)191;
                            foreach (var id in allowedGroupId)
                            {
                                if (UsrGroup.IndexOf((char)191 + id.ToString() + (char)191) >= 0
                                    ||
                                    UsrGroup.IndexOf((char)191 + "5" + (char)191) >= 0
                                    )
                                {
                                    pub = false;
                                    break;
                                }
                            }
                        }

                        string fileName = (Request.QueryString["file"] ?? "").ToString().Replace("../", "");
                        fileName = (fileName.StartsWith("~/") ? "" : "~/") + fileName;
                        string key = (Request.QueryString["key"] ?? "").ToString();
                        //string DownloadLinkCode = Session.SessionID;
                        //byte[] Download_code = System.Text.Encoding.ASCII.GetBytes(DownloadLinkCode);
                        //System.Security.Cryptography.HMACMD5 bkup_hmac = new System.Security.Cryptography.HMACMD5(Download_code);
                        //byte[] Download_hash = bkup_hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(fileName));
                        //string Download_hashString = BitConverter.ToString(Download_hash);
                        bool allowDownload = string.IsNullOrEmpty(Request.QueryString["_h"]) ? ValidatedQS(false) : ValidateQSV2(false);
                        fileName = (fileName.StartsWith("~/") ? "" : "~/") + fileName.ToLower().Replace("~/guarded/", "~/secure/").Replace("/guarded/", "/secure/");
                        string             url          = fileName;
                        string             fullfileName = Server.MapPath(fileName); // we enforce everything file for download is under ../files
                        System.IO.FileInfo file         = new System.IO.FileInfo(fullfileName);
                        string             oname        = file.Name;

                        if (oname.ToLower().EndsWith(".config"))
                        {
                            throw new Exception("Access Denied");
                        }

                        if (pub &&
                            !allowDownload &&
                            !(file.Name.StartsWith("Pub")
                              ||
                              file.Name.StartsWith("pub")
                              )
                            )
                        {
                            if (file.Name.EndsWith(".wmv"))
                            {
                                file = new FileInfo(file.DirectoryName + "/PubMsg.wmv");
                                url  = fileName.Replace(oname, "PubMsg.wmv");
                            }
                            else
                            {
                                if (LUser == null || LUser.LoginName == "Anonymous")
                                {
                                    string loginUrl = System.Web.Security.FormsAuthentication.LoginUrl;
                                    if (string.IsNullOrEmpty(loginUrl))
                                    {
                                        loginUrl = "MyAccount.aspx";
                                    }
                                    this.Redirect(loginUrl + (loginUrl.IndexOf('?') > 0 ? "&" : "?") + "wrn=1&ReturnUrl=" + Server.UrlEncode(Request.Url.PathAndQuery));
                                }
                                else
                                {
                                    throw new Exception("Access Denied");
                                }
                            }
                        }
                        Response.Buffer      = true; Response.ClearHeaders(); Response.ClearContent();
                        Response.ContentType = GetMimeTypeFromExtension(file.Extension);
                        Response.AddHeader("Content-Disposition", "Attachment; Filename=" + file.Name);
                        Response.AddHeader("Content-Length", file.Length.ToString());
                        Server.Transfer(url);
                    }
                    catch (ThreadAbortException)
                    {
                    }
                    catch (Exception err) { ApplicationAssert.CheckCondition(false, "DnLoadModule", "", err.Message); }
                }
            }
        }
Пример #46
0
        public static void Serialize <T>(T obj, string filePath)
        {
            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj);

            File.WriteAllText(filePath, json);
        }
Пример #47
0
        public JsonResult dispatch(string inputs, string type, string CID)
        {
            System.Web.Script.Serialization.JavaScriptSerializer jser = new System.Web.Script.Serialization.JavaScriptSerializer();
            Helpers.CtxService service     = new Helpers.CtxService(null, CID);
            string             userMessage = "";
            int msid = 0;

            if (inputs.Length == 0)
            {
                return(Json("Input Box Objects cannot be empty.", JsonRequestBehavior.AllowGet));
            }

            try
            {
                FlagBoard_mvc.Models.pageInputs[] inputObjects    = jser.Deserialize <FlagBoard_mvc.Models.pageInputs[]>(inputs);
                Helpers.jqGrid <FlagBoard_mvc.Models.schedule> jq = new Helpers.jqGrid <FlagBoard_mvc.Models.schedule>();
                FlagBoard_mvc.Models.schedule record = jq.mapToObjectProperty(inputObjects);
                switch (type)
                {
                case "edit":
                    if (record.MS_Unscheduled_Reason.Trim().Length > 50)
                    {
                        throw new Exception("Unscheduled Reason cannot be greater than 50 characters long.");
                    }

                    int rows = service.Update(record);
                    if (rows > 0 && record.MS_Maint_Code == 1 && record.MS_Main_Comp_Date == "True")
                    {
                        if (record.MS_Frequency < 1)
                        {
                            throw new Exception("Interval must be greater than 0");
                        }
                        AutoAddScheduledOrder(record, service);
                    }
                    userMessage = "true";
                    break;

                case "add":
                    if (record.MS_Unscheduled_Reason.Length > 50)
                    {
                        throw new Exception("Unscheduled Reason cannot be greater than 50 characters long.");
                    }

                    int rowsaff = service.Add(record);
                    service.Dispose();
                    if (rowsaff == 0)
                    {
                        throw new Exception("unknown error adding rows. ");
                    }
                    userMessage = "true";
                    msid        = service.rowKey;
                    break;

                case "delete":
                    service.delete(record.MS_Id);
                    userMessage = "true";
                    break;
                }
            } catch (Exception ex)
            {
                userMessage = "ERROR: " + ex.Message;
            } finally
            {
                service.Dispose();
                service.clearCache();
            }

            return(Json(new { message = userMessage, id = msid }, JsonRequestBehavior.AllowGet));
        }
        protected byte[] AddDoc(string docJson, string docId, string tableName, string keyColumnName, string columnName, string dbConnectionString, string dbPwd, string height, bool resizeToIcon = false)
        {
            byte[] storedContent = null;
            bool   dummyImage    = false;
            int    maxHeight     = 360;

            int.TryParse(height, out maxHeight);
            try
            {
                System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                jss.MaxJsonLength = Int32.MaxValue;
                FileUploadObj fileObj = jss.Deserialize <FileUploadObj>(docJson);
                if (!string.IsNullOrEmpty(fileObj.base64))
                {
                    byte[] content = Convert.FromBase64String(fileObj.base64);
                    dummyImage = fileObj.base64 == "iVBORw0KGgoAAAANSUhEUgAAAhwAAAABCAQAAAA/IL+bAAAAFElEQVR42mN89p9hFIyCUTAKSAIABgMB58aXfLgAAAAASUVORK5CYII=";
                    if (resizeToIcon && fileObj.base64.Length > 0 && fileObj.mimeType.StartsWith("image/"))
                    {
                        try
                        {
                            content = ResizeImage(Convert.FromBase64String(fileObj.base64), maxHeight);
                        }
                        catch
                        {
                        }
                    }

                    /* store as 256 byte UTF8 json header + actual binary file content
                     * if header info > 256 bytes use compact header(256 bytes) + actual header + actual binary file content
                     */
                    string fileName      = System.IO.Path.GetFileName(fileObj.fileName);
                    string contentHeader = jss.Serialize(new FileInStreamObj()
                    {
                        fileName      = fileName,
                        lastModified  = fileObj.lastModified,
                        mimeType      = fileObj.mimeType, ver = "0100",
                        extensionSize = 0,
                        contentIsJSON = true,
                    });
                    byte[] streamHeader  = Enumerable.Repeat((byte)0x20, 256).ToArray();
                    int    headerLength  = System.Text.UTF8Encoding.UTF8.GetBytes(contentHeader).Length;
                    string compactHeader = jss.Serialize(new FileInStreamObj()
                    {
                        fileName      = "",
                        lastModified  = fileObj.lastModified,
                        mimeType      = fileObj.mimeType,
                        ver           = "0100",
                        extensionSize = headerLength,
                        contentIsJSON = true,
                    });
                    int compactHeaderLength = System.Text.UTF8Encoding.UTF8.GetBytes(compactHeader).Length;
                    if (headerLength <= 256)
                    {
                        Array.Copy(System.Text.UTF8Encoding.UTF8.GetBytes(contentHeader), streamHeader, headerLength);
                    }
                    else
                    {
                        Array.Resize(ref streamHeader, 256 + contentHeader.Length);
                        Array.Copy(System.Text.UTF8Encoding.UTF8.GetBytes(compactHeader), streamHeader, compactHeaderLength);
                        Array.Copy(System.Text.UTF8Encoding.UTF8.GetBytes(compactHeader), 0, streamHeader, 256, headerLength);
                    }
                    if (content.Length == 0 || dummyImage)
                    {
                        storedContent = null;
                    }
                    //no longer needed 2020.3.3 gary
                    //else if (fileObj.mimeType.StartsWith("image/") && false)
                    //{
                    //    // backward compatability with asp.net side, only store image and not fileinfo
                    //    storedContent = content;
                    //}
                    else
                    {
                        System.Collections.Generic.List <_ReactFileUploadObj> fo = new System.Collections.Generic.List <_ReactFileUploadObj>();
                        fo.Add(new _ReactFileUploadObj()
                        {
                            fileName     = fileName,
                            base64       = Convert.ToBase64String(content),
                            mimeType     = fileObj.mimeType,
                            height       = maxHeight,
                            lastModified = fileObj.lastModified,
                            previewUrl   = null,
                            size         = 0,
                            width        = 0
                        }
                               );
                        string foJSON = jss.Serialize(fo);
                        content       = System.Text.UTF8Encoding.UTF8.GetBytes(foJSON);
                        storedContent = new byte[content.Length + streamHeader.Length];
                        Array.Copy(streamHeader, storedContent, streamHeader.Length);
                        Array.Copy(content, 0, storedContent, streamHeader.Length, content.Length);
                    }
                    byte[] savedContent = content.Length == 0 || dummyImage ? null : storedContent;
                    new AdminSystem().UpdDbImg(docId, tableName, keyColumnName, columnName, savedContent, dbConnectionString, dbPwd);

                    return(savedContent);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex) { throw new Exception("invalid attachment format: " + Server.HtmlEncode(ex.Message)); }
        }
Пример #49
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;
        }
    }
 public static string GetDepartmentList()
 {
     System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
     return(js.Serialize(StatisticHelper.GetDepartmentList()));
 }
        private void SaveUpload(string dbConnectionString, byte sid)
        {
            if (Request.Files.Count > 0 && Request.Files[0].FileName != string.Empty
                //&& "image/gif,image/jpeg,image/png,image/tiff,image/pjpeg,image/x-png".IndexOf(Request.Files[0].ContentType) >= 0
                )
            {
                byte[] dc;
                using (System.IO.BinaryReader sm = new BinaryReader(Request.Files[0].InputStream))
                {
                    dc = new byte[Request.Files[0].InputStream.Length];
                    sm.Read(dc, 0, dc.Length); sm.Close();
                }

                System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                jss.MaxJsonLength = Int32.MaxValue;
                FileUploadObj fileObj = new FileUploadObj()
                {
                    fileName     = Request.Files[0].FileName,
                    mimeType     = Request.Files[0].ContentType,
                    lastModified = RO.Common3.Utils.ToUnixTime(DateTime.UtcNow),
                    base64       = Convert.ToBase64String(dc),
                };

                string docJson       = jss.Serialize(fileObj);
                string docId         = Request.QueryString["key"];
                string tableName     = Request.QueryString["tbl"];
                string keyColumnName = Request.QueryString["knm"];
                string columnName    = Request.QueryString["col"].ToString();

                byte[] savedContent = AddDoc(docJson, docId, tableName, keyColumnName, columnName, dbConnectionString, base.AppPwd(sid), Request.QueryString["hgt"], true);

                //byte[] dc;
                //System.Drawing.Image oBMP = System.Drawing.Image.FromStream(Request.Files[0].InputStream);
                //int nHeight = int.Parse(oBMP.Height.ToString());
                //int nWidth = int.Parse(oBMP.Width.ToString());
                //if (!string.IsNullOrEmpty(Request.QueryString["hgt"].ToString()))
                //{
                //    nHeight = int.Parse(Request.QueryString["hgt"].ToString());
                //    nWidth = int.Parse((Math.Round(decimal.Parse(oBMP.Width.ToString()) * (nHeight / decimal.Parse(oBMP.Height.ToString())))).ToString());
                //}
                //else if (!string.IsNullOrEmpty(Request.QueryString["wth"].ToString()))
                //{
                //    nWidth = int.Parse(Request.QueryString["wth"].ToString());
                //    nHeight = int.Parse((Math.Round(decimal.Parse(oBMP.Height.ToString()) * (nWidth / decimal.Parse(oBMP.Width.ToString())))).ToString());
                //}

                //Bitmap nBMP = new Bitmap(oBMP, nWidth, nHeight);
                //using (System.IO.MemoryStream sm = new System.IO.MemoryStream())
                //{
                //    nBMP.Save(sm, System.Drawing.Imaging.ImageFormat.Jpeg);
                //    sm.Position = 0;
                //    dc = new byte[sm.Length + 1];
                //    sm.Read(dc, 0, dc.Length); sm.Close();
                //}
                //oBMP.Dispose(); nBMP.Dispose();
                //new AdminSystem().UpdDbImg(Request.QueryString["key"], Request.QueryString["tbl"], Request.QueryString["knm"], Request.QueryString["col"].ToString(), dc, dbConnectionString, base.AppPwd(sid));
                Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent();
                //string imgEmbedded = "data:application/base64;base64," + Convert.ToBase64String(dc);

                string imgEmbedded = savedContent != null ? (RO.Common3.Utils.BlobPlaceHolder(savedContent, true) ?? "").Replace("../", "") : "images/DefaultImg.png";
                string json        = "{\"imgUrl\":\"" + imgEmbedded + "\"}";
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.Write(json);
                Response.End();
            }
            else if (Request.QueryString["del"] != null)
            {
                //delete image
                new AdminSystem().UpdDbImg(Request.QueryString["key"], Request.QueryString["tbl"], Request.QueryString["knm"], Request.QueryString["col"].ToString(), null, dbConnectionString, base.AppPwd(sid));
                Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent();
                string json = "{\"imgUrl\":\"" + "images/DefaultImg.png" + "\"}";
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.Write(json);
                Response.End();
            }
        }
        public String combos(String tabla)
        {
            MySqlConnection  con = new MySqlConnection();
            MySqlCommand     cmd = new MySqlCommand();
            DataTable        t   = new DataTable();
            MySqlDataAdapter adp = new MySqlDataAdapter();

            con = conexion.conexion.obtnerconexion();
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            String resultado = "";
            String sql       = "";

            sql = "SELECT * FROM " + tabla;

            cmd.Connection  = con;
            cmd.CommandText = sql;

            try
            {
                cmd.ExecuteNonQuery();
                adp.SelectCommand = cmd;
                adp.Fill(t);
                List <Dictionary <Object, String> > filas = new List <Dictionary <Object, String> >();
                Dictionary <Object, String>         fila;
                foreach (DataRow row in t.Rows)
                {
                    fila = new Dictionary <object, string>();


                    if (tabla == "fescolaridad")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fpais")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fprofesion")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fpromotor")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                        fila.Add("telefono", row[2].ToString());
                        fila.Add("sucursal", row[3].ToString());
                    }
                    else if (tabla == "fsucursal")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fzona")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                        fila.Add("sucursal", row[2].ToString());
                        fila.Add("posicion", row[3].ToString());
                        fila.Add("circun", row[4].ToString());
                    }
                    else if (tabla == "fciudad")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fcomites")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fcargo")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fcliente")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[2].ToString());
                        fila.Add("codcliente", row[34].ToString());
                    }
                    else if (tabla == "ftipoestudio")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                    }
                    else if (tabla == "fnomestudio")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                        fila.Add("tipoestudio", row[2].ToString());
                    }
                    else if (tabla == "ftemas")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[1].ToString());
                        fila.Add("nomestudio", row[2].ToString());
                    }
                    else
                    {
                        foreach (DataColumn col in t.Columns)
                        {
                            String valor = row[col.ColumnName].ToString();
                            if (col.DataType == typeof(DateTime) && valor != "")
                            {
                                DateTime fecha = DateTime.Parse(valor);
                                valor = fecha.ToString("yyyy-MM-dd");
                            }
                            fila.Add(col.ColumnName, valor);
                        }
                    }


                    filas.Add(fila);
                }
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

                resultado = js.Serialize(filas);


                con.Close();
            }
            catch (Exception e)
            {
                String error = e.Message;
            }
            return(resultado);
        }
Пример #53
0
        public static string GetcurrentTimeSystem()
        {
            var js = new System.Web.Script.Serialization.JavaScriptSerializer();

            return(js.Serialize(DateTime.Now));
        }
        public string StudentAssessment(string ChildId, int termID)
        {
            bool Submited_flag;

            try
            {
                var check = db.AspNetStudent_Term_Assessment.Where(x => x.TermID == termID && x.StudentID == ChildId && x.Status == "Principle_submit").Select(x => x.Id).ToList();

                if (check.Count == 0)
                {
                    Submited_flag = false;
                }
                else
                {
                    Submited_flag = true;
                }
            }
            catch
            {
                Submited_flag = false;
            }



            Student_data Assessment_DATA = new Student_data();

            Assessment_DATA.assessment_data = new List <subject>();

            if (Submited_flag)
            {
                var STAID = db.AspNetStudent_Term_Assessment.Where(x => x.TermID == termID && x.StudentID == ChildId).Select(x => x.Id).ToList();
                Assessment_DATA.PrincipleComment = db.AspNetStudent_Term_Assessment.Where(x => x.TermID == termID && x.StudentID == ChildId).Select(x => x.PrincipalComments).FirstOrDefault();


                var catageory = db.AspNetStudent_Term_Assessments_Answers.Where(x => x.AspNetStudent_Term_Assessment.TermID == termID && x.AspNetStudent_Term_Assessment.StudentID == ChildId).Select(x => x.Catageory).Distinct().ToList();

                foreach (var item in STAID)
                {
                    subject Subject = new subject();
                    Subject.SubjectName    = db.AspNetStudent_Term_Assessments_Answers.Where(x => x.STAID == item).Select(x => x.AspNetStudent_Term_Assessment.AspNetSubject.SubjectName).First();
                    Subject.TeacherComment = db.AspNetStudent_Term_Assessment.Where(x => x.Id == item).Select(x => x.TeacherComments).FirstOrDefault();
                    Subject.CatageoryList  = new List <Catageory>();

                    foreach (var Catag in catageory)
                    {
                        Catageory Catageory = new Catageory();
                        Catageory.catageoryName = Catag;
                        Catageory.QuestionList  = new List <Questions>();

                        var AQID = db.AspNetStudent_Term_Assessments_Answers.Where(x => x.STAID == item && x.Catageory == Catag).ToList();

                        if (AQID.Count != 0)
                        {
                            foreach (var aqid in AQID)
                            {
                                Questions question = new Questions();
                                question.Question = aqid.Question;
                                question.Answer   = aqid.Answer;
                                Catageory.QuestionList.Add(question);
                            }
                            Subject.CatageoryList.Add(Catageory);
                        }
                    }

                    Assessment_DATA.assessment_data.Add(Subject);
                }
            }

            var javaScriptSerializer = new
                                       System.Web.Script.Serialization.JavaScriptSerializer();
            string jsonString = javaScriptSerializer.Serialize(Assessment_DATA);

            return(jsonString);
        }
        public String buscarcampo(String tabla, String condicion)
        {
            MySqlConnection  con = new MySqlConnection();
            MySqlCommand     cmd = new MySqlCommand();
            DataTable        t   = new DataTable();
            MySqlDataAdapter adp = new MySqlDataAdapter();

            con = conexion.conexion.obtnerconexion();
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            String resultado = "";
            String sql       = "";

            if (tabla == "fcargos")
            {
                sql = "SELECT * FROM " + tabla + " WHERE id='" + condicion + "'";
            }
            else if (tabla == "festudios")
            {
                sql = "SELECT * FROM " + tabla + " WHERE id='" + condicion + "'";
            }
            else if (tabla == "movescrituras")
            {
                sql = "SELECT * FROM " + tabla + " WHERE escritura='" + condicion + "'";
            }
            else if (tabla == "vcréditos")
            {
                condicion = condicion.Replace(",", " or id=");
                sql       = "SELECT * FROM " + tabla + " WHERE id=" + condicion + "";
            }
            else if (tabla == "vcargos")
            {
                sql = "SELECT * FROM " + tabla + " WHERE idcliente='" + condicion + "'";
            }
            else if (tabla == "vestudios")
            {
                sql = "SELECT * FROM " + tabla + " WHERE idcliente='" + condicion + "'";
            }
            else if (tabla == "vcliente")
            {
                sql = "SELECT * FROM " + tabla + " WHERE id='" + condicion + "'";
            }
            else if (tabla == "vapertura")
            {
                sql = "SELECT * FROM " + tabla + " WHERE codcliente='" + condicion + "'";
            }
            else if (tabla == "vdesembolso")
            {
                sql = "SELECT * FROM " + tabla + " WHERE codcliente='" + condicion + "'";
            }
            else if (tabla == "vinstitucion")
            {
                sql = "SELECT * FROM " + tabla + " WHERE id='" + condicion + "'";
            }
            else
            {
                sql = "SELECT * FROM " + tabla + " WHERE value='" + condicion + "'";
            }


            cmd.Connection  = con;
            cmd.CommandText = sql;

            try
            {
                cmd.ExecuteNonQuery();
                adp.SelectCommand = cmd;
                adp.Fill(t);
                List <Dictionary <Object, String> > filas = new List <Dictionary <Object, String> >();
                Dictionary <Object, String>         fila;
                foreach (DataRow row in t.Rows)
                {
                    fila = new Dictionary <object, string>();
                    if (tabla == "fzona")
                    {
                        fila.Add("posicion", row[3].ToString());
                        fila.Add("circun", row[4].ToString());
                    }
                    else if (tabla == "fcargosxx")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("idcliente", row[1].ToString());
                        fila.Add("comite", row[2].ToString());
                        fila.Add("cargo", row[3].ToString());
                        fila.Add("fechainicial", row[4].ToString());
                        fila.Add("fechafinal", row[5].ToString());
                        fila.Add("actual", row[6].ToString());
                    }
                    else if (tabla == "festudiosxx")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("idcliente", row[1].ToString());
                        fila.Add("tipoestudio", row[2].ToString());
                        fila.Add("nomestudio", row[3].ToString());
                        fila.Add("temas", row[4].ToString());
                        fila.Add("fechainicio", row[5].ToString());
                        fila.Add("fechafinal", row[6].ToString());
                    }
                    else if (tabla == "vcargos")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("idcliente", row[1].ToString());
                        fila.Add("comite", row[2].ToString());
                        fila.Add("cargo", row[3].ToString());
                        fila.Add("fechainicial", row[4].ToString());
                        fila.Add("fechafinal", row[5].ToString());
                        fila.Add("actual", row[6].ToString());
                    }
                    else if (tabla == "vestudios")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("idcliente", row[1].ToString());
                        fila.Add("tipoestudio", row[2].ToString());
                        fila.Add("nomestudio", row[3].ToString());
                        fila.Add("temas", row[4].ToString());
                        fila.Add("fechainicio", row[5].ToString());
                        fila.Add("fechafinal", row[6].ToString());
                    }
                    else if (tabla == "vcliente")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("fecha", row[1].ToString());
                        fila.Add("nombre", row[2].ToString());
                        fila.Add("iden", row[3].ToString());
                        fila.Add("dir", row[4].ToString());
                        fila.Add("fechana", row[5].ToString());
                        fila.Add("edad", row[6].ToString());
                        fila.Add("escolaridad", row[7].ToString());
                        fila.Add("profesion", row[8].ToString());
                        fila.Add("telefono", row[9].ToString());
                        fila.Add("ocupacion", row[10].ToString());
                        fila.Add("hijos", row[11].ToString());
                        fila.Add("pais", row[12].ToString());
                        fila.Add("ciudad", row[13].ToString());
                        fila.Add("sucursal", row[14].ToString());
                        fila.Add("zona", row[15].ToString());
                        fila.Add("correo", row[16].ToString());
                        fila.Add("referente", row[17].ToString());
                        fila.Add("telereferente", row[18].ToString());
                        fila.Add("promotor", row[19].ToString());
                        fila.Add("esdelegado", row[20].ToString());
                        fila.Add("inscrito", row[21].ToString());
                        fila.Add("estadocivil", row[22].ToString());
                        fila.Add("circun", row[23].ToString());
                    }
                    else if (tabla == "vinstitucion")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("fecha", row[1].ToString());
                        fila.Add("nombre", row[2].ToString());
                        fila.Add("ruc", row[3].ToString());
                        fila.Add("dir", row[4].ToString());
                        fila.Add("telefono", row[5].ToString());
                        fila.Add("fechana", row[6].ToString());
                        fila.Add("edad", row[7].ToString());
                        fila.Add("ocupacion", row[8].ToString());
                        fila.Add("pais", row[9].ToString());
                        fila.Add("ciudad", row[10].ToString());
                        fila.Add("sucursal", row[11].ToString());
                        fila.Add("zona", row[12].ToString());
                        fila.Add("posicion", row[13].ToString());
                        fila.Add("promotor", row[14].ToString());
                        fila.Add("correo", row[15].ToString());
                        fila.Add("rep1", row[16].ToString());
                        fila.Add("idenrep1", row[17].ToString());
                        fila.Add("dirrep1", row[18].ToString());
                        fila.Add("telerep1", row[19].ToString());
                        fila.Add("cargorep1", row[20].ToString());
                        fila.Add("rep2", row[21].ToString());
                        fila.Add("idenrep2", row[22].ToString());
                        fila.Add("dirrep2", row[23].ToString());
                        fila.Add("telerep2", row[24].ToString());
                        fila.Add("cargorep2", row[25].ToString());
                        fila.Add("circun", row[28].ToString());
                        fila.Add("inscrito", row[29].ToString());
                    }
                    else if (tabla == "vapertura")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("tipocuenta", row[2].ToString());
                        fila.Add("codcuenta", row[3].ToString());
                        fila.Add("documentos", row[4].ToString());
                    }
                    else if (tabla == "vdesembolso")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("codcredito", row[2].ToString());
                        fila.Add("sector", row[3].ToString());
                        fila.Add("documentos", row[4].ToString());
                    }
                    else
                    {
                        foreach (DataColumn col in t.Columns)
                        {
                            String valor = row[col.ColumnName].ToString();
                            if (col.DataType == typeof(DateTime) && valor != "")
                            {
                                DateTime fecha = DateTime.Parse(valor);
                                valor = fecha.ToString("yyyy-MM-dd");
                            }
                            fila.Add(col.ColumnName, valor);
                        }
                    }
                    filas.Add(fila);
                }
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                resultado = js.Serialize(filas);

                con.Close();
            }
            catch (Exception e)
            {
                resultado = e.Message;
            }
            return(resultado);
        }
Пример #56
0
        protected void bAjaxPostback_Click(object sender, EventArgs e)
        {
            string status = string.Empty;

            try
            {
                aqufitEntities entities = new aqufitEntities();
                Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                switch (hiddenAjaxAction.Value)
                {
                case "page1":
                    int    skip1  = Convert.ToInt32(hiddenAjaxValue.Value);
                    var    users1 = userQueryLiveNear.Skip(skip1).Take(PEOPLE_TAKE).Select(u => new { Id = u.Id, UserName = u.UserName, FName = u.UserFirstName, LName = u.UserLastName, UserKey = u.UserKey, Duration = 0 }).ToArray();
                    string json1  = users1.ToJson();
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.atiPeopleList1.generateStreamDom('" + json1 + "');");
                    break;

                case "page2":
                    int    skip2  = Convert.ToInt32(hiddenAjaxValue.Value);
                    var    users2 = userQueryRecentActive.Skip(skip2).Take(PEOPLE_TAKE).Select(u => new { Id = u.Id, UserName = u.UserName, FName = u.UserFirstName, LName = u.UserLastName, UserKey = u.UserKey, Duration = 0 }).ToArray();
                    string json2  = users2.ToJson();
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.atiPeopleList2.generateStreamDom('" + json2 + "');");
                    break;

                case "page3":
                    int    skip3  = Convert.ToInt32(hiddenAjaxValue.Value);
                    var    users3 = userQueryMostWatched.Skip(skip3).Take(PEOPLE_TAKE).Select(u => new { Id = u.Id, UserName = u.UserName, FName = u.UserFirstName, LName = u.UserLastName, UserKey = u.UserKey, Duration = 0 }).ToArray();
                    string json3  = users3.ToJson();
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.atiPeopleList3.generateStreamDom('" + json3 + "');");
                    break;

                case "pageFast1":
                    int    skip4  = Convert.ToInt32(hiddenAjaxValue.Value);
                    var    users4 = workoutQueryFastest1.Skip(skip4).Select(w => new { Id = w.UserSetting.Id, UserName = w.UserSetting.UserName, FName = w.UserSetting.UserFirstName, LName = w.UserSetting.UserLastName, UserKey = w.UserSetting.UserKey, Duration = w.Duration }).Take(PEOPLE_TAKE).ToArray();
                    string json4  = users4.ToJson();
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.atiPeopleListFast1.generateStreamDom('" + json4 + "');");
                    break;

                case "configAddWorkout":
                    long workoutKey = Convert.ToInt64(hiddenWodKey.Value);
                    int  numshow    = Convert.ToInt32(hiddenAjaxValue.Value);
                    hiddenWodKey.Value = "";     // clear the workout key now
                    Affine.Data.json.LeaderBoardWOD[] data = dataMan.SaveCustomLeaderBoardWorkout(ProfileSettings.Id, UserSettings.Id, workoutKey, numshow, 0);
                    System.Web.Script.Serialization.JavaScriptSerializer serial = new System.Web.Script.Serialization.JavaScriptSerializer();
                    string json = serial.Serialize(data);
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page." + atiLeaderBoard2Config.ID + ".appendLeaderBoardJson('" + json + "');  Aqufit.Windows.WorkoutSelectDialog.close();");
                    break;

                case "RestoreDefault":
                    dataMan.DeleteCustomLeaderBoard(ProfileSettings.Id, UserSettings.Id);
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page." + atiLeaderBoard2Config.ID + ".clear(); ");
                    break;

                case "configDelWorkout":
                    long wodKey = Convert.ToInt32(hiddenAjaxValue.Value);
                    dataMan.DeleteCustomLeaderBoardWorkout(ProfileSettings.Id, UserSettings.Id, wodKey);
                    break;
                }
            }
            catch (Exception ex)
            {
                status = "ERROR: There was a problem with the action (" + ex.Message + ")";
            }
        }
        public String buscardatos(String tabla)
        {
            MySqlConnection  con = new MySqlConnection();
            MySqlCommand     cmd = new MySqlCommand();
            DataTable        t   = new DataTable();
            MySqlDataAdapter adp = new MySqlDataAdapter();

            con = conexion.conexion.obtnerconexion();
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            String resultado = "";
            String sql       = "";

            sql = "SELECT * FROM " + tabla;

            cmd.Connection  = con;
            cmd.CommandText = sql;

            try
            {
                cmd.ExecuteNonQuery();
                adp.SelectCommand = cmd;
                adp.Fill(t);
                List <Dictionary <Object, String> > filas = new List <Dictionary <Object, String> >();
                Dictionary <Object, String>         fila;
                foreach (DataRow row in t.Rows)
                {
                    fila = new Dictionary <object, string>();

                    if (tabla == "fclientexxx")
                    {
                        DateTime fecha   = DateTime.Parse(row[1].ToString());
                        String   fechaa  = fecha.ToString("yyyy-MM-dd");
                        DateTime fecha2  = DateTime.Parse(row[5].ToString());
                        String   fechana = fecha2.ToString("yyyy-MM-dd");


                        fila.Add("id", row[0].ToString());
                        fila.Add("fecha", fechaa);
                        fila.Add("nombre", row[2].ToString());
                        fila.Add("iden", row[3].ToString());
                        fila.Add("dir", row[4].ToString());
                        fila.Add("fechana", fechana);
                        fila.Add("edad", row[6].ToString());
                        fila.Add("sexo", row[7].ToString());
                        fila.Add("escolaridad", row[8].ToString());
                        fila.Add("profesion", row[9].ToString());
                        fila.Add("telefono", row[10].ToString());
                        fila.Add("ocupacion", row[11].ToString());
                        fila.Add("hijos", row[12].ToString());
                        fila.Add("estadocivil", row[13].ToString());
                        fila.Add("nacionalidad", row[14].ToString());
                        fila.Add("ciudad", row[15].ToString());
                        fila.Add("sucursal", row[16].ToString());
                        fila.Add("zona", row[17].ToString());
                        fila.Add("correo", row[18].ToString());
                        fila.Add("lugartrabajo", row[19].ToString());
                        fila.Add("dirtrabajo", row[20].ToString());
                        fila.Add("teletrabajo", row[21].ToString());
                        fila.Add("conyugue", row[22].ToString());
                        fila.Add("teleconyugue", row[23].ToString());
                        fila.Add("referente", row[24].ToString());
                        fila.Add("telereferente", row[25].ToString());
                        fila.Add("dirreferente", row[26].ToString());
                        fila.Add("promotor", row[27].ToString());
                        fila.Add("esdelegado", row[28].ToString());
                        fila.Add("inscrito", row[29].ToString());
                        if (row[30].ToString() == "")
                        {
                            fila.Add("foto", "../img/avatar.png");
                        }
                        else
                        {
                            fila.Add("foto", row[30].ToString());
                        }

                        fila.Add("retiro", row[31].ToString());
                        fila.Add("fecharetiro", row[32].ToString());
                        fila.Add("fechadelegado", row[33].ToString());
                    }
                    else if (tabla == "finstitucionxxx")
                    {
                        fila.Add("id", row[0].ToString());
                        fila.Add("fecha", row[1].ToString());
                        fila.Add("nombre", row[2].ToString());
                        fila.Add("ruc", row[3].ToString());
                        fila.Add("dir", row[4].ToString());
                        fila.Add("telefono", row[5].ToString());
                        fila.Add("fechana", row[6].ToString());
                        fila.Add("edad", row[7].ToString());
                        fila.Add("ocupacion", row[8].ToString());
                        fila.Add("pais", row[9].ToString());
                        fila.Add("ciudad", row[10].ToString());
                        fila.Add("sucursal", row[11].ToString());
                        fila.Add("zona", row[12].ToString());
                        fila.Add("promotor", row[13].ToString());
                        fila.Add("correo", row[14].ToString());
                        fila.Add("rep1", row[15].ToString());
                        fila.Add("idenrep1", row[16].ToString());
                        fila.Add("dirrep1", row[17].ToString());
                        fila.Add("telerep1", row[18].ToString());
                        fila.Add("cargorep1", row[19].ToString());
                        fila.Add("rep2", row[20].ToString());
                        fila.Add("idenrep2", row[21].ToString());
                        fila.Add("dirrep2", row[22].ToString());
                        fila.Add("telerep2", row[23].ToString());
                        fila.Add("cargorep2", row[24].ToString());
                        fila.Add("retiro", row[25].ToString());
                        fila.Add("fecharetiro", row[26].ToString());
                        fila.Add("inscrito", row[27].ToString());
                    }
                    else if (tabla == "vinstitucion")
                    {
                        fila.Add("value", row[0].ToString());
                        fila.Add("text", row[2].ToString());
                    }
                    else
                    {
                        foreach (DataColumn col in t.Columns)
                        {
                            String valor = row[col.ColumnName].ToString();
                            if (col.DataType == typeof(DateTime) && valor != "")
                            {
                                DateTime fecha = DateTime.Parse(valor);
                                valor = fecha.ToString("yyyy-MM-dd");
                            }
                            fila.Add(col.ColumnName, valor);
                        }
                    }

                    filas.Add(fila);
                }
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                js.MaxJsonLength = 999999999;
                resultado        = js.Serialize(filas);

                con.Close();
            }
            catch (Exception e)
            {
                String error = e.Message;
            }
            return(resultado);
        }
 public string ToJSON()
 {
     System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer
         = new System.Web.Script.Serialization.JavaScriptSerializer();
     return(jsonSerializer.Serialize(this));
 }
Пример #59
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (IsBasicAuthorized(actionContext))
            {
                ((apiController)actionContext.ControllerContext.Controller).Init();
                return;
            }

            if (IsServerAuthorized(actionContext))
            {
                return;
            }

            if (IsAnonymous(actionContext))
            {
                return;
            }

            base.OnAuthorization(actionContext);

            ClaimsPrincipal principal = actionContext.Request.GetRequestContext().Principal as ClaimsPrincipal;

            var ci = principal.Identity as ClaimsIdentity;

            if (!ci.IsAuthenticated)
            {
                AuthorizationTokenExpiredException authorizationTokenExpiredException = new AuthorizationTokenExpiredException();
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.Unauthorized,
                    authorizationTokenExpiredException.Message,
                    authorizationTokenExpiredException);
                return;
            }

            try
            {
                var usernameObj = principal.Claims.Where(c => c.Type == Database.Username).Single();


                var appnameObj = principal.Claims.Where(c => c.Type == Database.AppName).Single();

                var infoObj = principal.Claims.Where(c => c.Type == Database.TokenInfo).SingleOrDefault();

                if (usernameObj == null)
                {
                    HandleUnauthorized(actionContext, null, null);
                    return;
                }

                if (appnameObj == null)
                {
                    HandleUnauthorized(actionContext, null, null);
                    return;
                }

                string username         = usernameObj.Value;
                string appname          = appnameObj.Value;
                string appNameFromToken = appnameObj.Value;
                bool   mainAppFromToken = appNameFromToken == Maps.DuradosAppName;

                string appNameInHeader = null;
                if (actionContext.Request.Headers.Contains("AppName"))
                {
                    appNameInHeader = actionContext.Request.Headers.GetValues("AppName").FirstOrDefault();
                }
                else if (actionContext.Request.Headers.Contains("appName"))
                {
                    appNameInHeader = actionContext.Request.Headers.GetValues("appName").FirstOrDefault();
                }
                else if (actionContext.Request.Headers.Contains("appname"))
                {
                    appNameInHeader = actionContext.Request.Headers.GetValues("appname").FirstOrDefault();
                }

                Durados.Web.Mvc.Controllers.AccountMembershipService accountMembershipService = new Durados.Web.Mvc.Controllers.AccountMembershipService();

                if (appNameInHeader != null)
                {
                    if (appname.ToLower() == Maps.DuradosAppName)
                    {
                        appname = appNameInHeader;
                    }
                    else
                    {
                        if (appname != appNameInHeader)
                        {
                            // BackandSSO
                            if (!IsSso(appname, appNameInHeader))
                            {
                                actionContext.Response = actionContext.Request.CreateErrorResponse(
                                    HttpStatusCode.Unauthorized,
                                    string.Format(Durados.Web.Mvc.UI.Helpers.UserValidationErrorMessages.AccessTokenNotAllowedToApp, appNameInHeader));
                                return;
                            }
                            else
                            {
                                appname = appNameInHeader;
                                if (!System.Web.HttpContext.Current.Items.Contains(Database.AppName))
                                {
                                    System.Web.HttpContext.Current.Items.Add(Database.AppName, appname);
                                }
                                else
                                {
                                    System.Web.HttpContext.Current.Items[Database.AppName] = appname;
                                }
                                if (!accountMembershipService.IsApproved(username))
                                {
                                    try
                                    {
                                        userController uc          = new userController();
                                        string         provider    = GetDomainControllerProvider(appname);
                                        var            userRow     = (DataRow)GetUserRow(appnameObj.Value, username);
                                        string         socialId    = GetSocialId(provider, username, appnameObj.Value);
                                        bool           hasSocialId = socialId != null;
                                        string         password    = GetPassword();
                                        System.Web.HttpContext.Current.Items.Add(Database.SignupInProcess, true);
                                        if (hasSocialId)
                                        {
                                            uc.SignUpCommand(appname, username, provider, socialId, GetValues(userRow, username), GetFirstName(userRow), GetLastName(userRow), password, true);
                                        }
                                        else
                                        {
                                            bool hasMembership = Maps.Instance.GetMap(appname).GetMembershipProvider().GetUser(username, false) != null;
                                            if (hasMembership)
                                            {
                                                var signUpResults = uc.SignUp(appname, null, null, true, GetFirstName(userRow), username, GetLastName(userRow), password, password, new Dictionary <string, object>());
                                            }
                                            else
                                            {
                                                actionContext.Response = actionContext.Request.CreateErrorResponse(
                                                    HttpStatusCode.Unauthorized,
                                                    string.Format(Durados.Web.Mvc.UI.Helpers.UserValidationErrorMessages.AccessTokenNotAllowedToApp, appNameInHeader));
                                                return;
                                            }
                                        }
                                    }
                                    catch (Exception exception)
                                    {
                                        actionContext.Response = actionContext.Request.CreateErrorResponse(
                                            HttpStatusCode.Unauthorized,
                                            exception.Message,
                                            exception);
                                    }
                                }

                                string key = appname + "_userRow_" + username;

                                System.Web.HttpContext.Current.Items.Remove(key);
                            }
                        }
                    }
                }


                if (!System.Web.HttpContext.Current.Items.Contains(Database.Username))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.Username, username);
                }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.AppName))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.AppName, appname);
                }
                else
                {
                    System.Web.HttpContext.Current.Items[Database.AppName] = appname;
                }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.MainAppFromToken))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.MainAppFromToken, mainAppFromToken);
                }

                string infoJson = null;
                object info     = null;
                if (infoObj != null)
                {
                    infoJson = infoObj.Value;
                    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                    info = jss.Deserialize <Dictionary <string, object> >(infoJson);
                }

                const string ForToken = "forToken";

                IDictionary <string, object> tokenInfo = new Dictionary <string, object>();
                if (info != null && info is IDictionary <string, object> && ((IDictionary <string, object>)info).ContainsKey(ForToken) && ((IDictionary <string, object>)info)[ForToken] is IDictionary <string, object> )
                {
                    tokenInfo = (IDictionary <string, object>)((IDictionary <string, object>)info)[ForToken];
                }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.TokenInfo))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.TokenInfo, tokenInfo);
                }

                try
                {
                    if (SharedMemorySingeltone.Instance.Contains(appname, SharedMemoryKey.DebugMode))
                    {
                        System.Web.HttpContext.Current.Items[Durados.Workflow.JavaScript.Debug] = true;
                    }
                }
                catch { }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.RequestId))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.RequestId, Guid.NewGuid().ToString());
                }
                //NewRelic.Api.Agent.NewRelic.AddCustomParameter(Durados.Database.RequestId, System.Web.HttpContext.Current.Items[Database.RequestId].ToString());
                //if (actionContext.Request.Headers.Contains("AppName"))
                //{
                try
                {
                    //if (!IsAppReady())
                    //{
                    //    throw new Durados.DuradosException("App is not ready yet");
                    //}
                    //if (!accountMembershipService.ValidateUser(username) || !accountMembershipService.IsApproved(username) || Revoked(appname, GetAuthToken(actionContext)))
                    if (!accountMembershipService.IsApproved(username) || Revoked(appname, GetAuthToken(actionContext)))
                    {
                        HandleUnauthorized(actionContext, appname, username);
                        return;
                    }

                    if (!(Maps.IsDevUser(username) || System.Web.HttpContext.Current.Request.Url.Segments.Contains("general/")) && (new Durados.Web.Mvc.UI.Helpers.DuradosAuthorizationHelper().IsAppLocked(appname) || IsAdminLocked(appname, appNameFromToken, username)))
                    {
                        actionContext.Response = actionContext.Request.CreateErrorResponse(
                            HttpStatusCode.Unauthorized,
                            string.Format(Durados.Web.Mvc.UI.Helpers.UserValidationErrorMessages.AppLocked, appname));
                        return;
                    }
                }
                catch (Durados.Web.Mvc.UI.Helpers.AppNotReadyException exception)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(
                        HttpStatusCode.NoContent,
                        exception.Message);
                    return;
                }
                catch (Exception exception)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.InternalServerError,
                        string.Format(Messages.Unexpected, exception.Message));

                    try
                    {
                        Maps.Instance.DuradosMap.Logger.Log(actionContext.ControllerContext.Controller.GetType().Name, actionContext.Request.RequestUri.ToString(), "BackAndAuthorizeAttribute", exception, 1, "authorization failure");
                    }
                    catch { }

                    try
                    {
                        if (Maps.Instance.AppInCach(appname))
                        {
                            Durados.Web.Mvc.UI.Helpers.RestHelper.Refresh(appname);
                        }
                    }
                    catch { }
                    return;
                }
                //}
                if (_allowedRoles == "Admin")
                {
                    string userRole = Maps.Instance.GetMap(appname).Database.GetUserRole();
                    if (!(userRole == "Admin" || userRole == "Developer"))
                    {
                        actionContext.ActionArguments.Add(Database.backand_serverAuthorizationAttempt, true);
                        actionContext.ActionArguments.Add(UserRoleNotSufficient, true);

                        HandleUnauthorized(actionContext, appname, username);
                        return;
                    }
                }
                if (_allowedRoles == "Developer")
                {
                    string userRole = Maps.Instance.GetMap(appname).Database.GetUserRole();
                    if (userRole != "Developer")
                    {
                        actionContext.ActionArguments.Add(Database.backand_serverAuthorizationAttempt, true);
                        actionContext.ActionArguments.Add(UserRoleNotSufficient, true);

                        HandleUnauthorized(actionContext, appname, username);
                        return;
                    }
                }
                try
                {
                    string message = null;
                    if (!mainAppFromToken && IsCustomDeny(appname, username, out message))
                    {
                        HandleUnauthorized(actionContext, appname, username, message);
                        return;
                    }
                }
                catch (Exception exception)
                {
                    HandleUnauthorized(actionContext, appname, username, "Unexpected error: " + exception.Message);
                    return;
                }
                ((apiController)actionContext.ControllerContext.Controller).Init();
            }
            catch
            {
                HandleUnauthorized(actionContext, null, null);
                return;
            }
        }
Пример #60
-16
        public HttpResponseMessage Upload(long selectedCollectionID)
        {
            // Get a reference to the file that our jQuery sent.  Even with multiple files, they will all be their own request and be the 0 index
            HttpPostedFile file = HttpContext.Current.Request.Files[0];

            var temp = Path.Combine(PathManager.GetUserCollectionPath(), "Temp");
            if (!Directory.Exists(temp))
            {
                Directory.CreateDirectory(temp);
            }

            User user = UserRepository.First(u => u.ProviderID == this.User.Identity.Name);
            Photo photo = PhotoService.ProcessUserPhoto(file.InputStream, Guid.NewGuid().ToString(), user, selectedCollectionID);

            // Now we need to wire up a response so that the calling script understands what happened
            HttpContext.Current.Response.ContentType = "text/plain";
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var result = new { name = file.FileName, id = photo.ID };

            HttpContext.Current.Response.Write(serializer.Serialize(result));
            HttpContext.Current.Response.StatusCode = 200;

            // For compatibility with IE's "done" event we need to return a result as well as setting the context.response
            return new HttpResponseMessage(HttpStatusCode.OK);
        }