Esempio n. 1
0
        public string TreeRefresh()
        {
            int    showType  = Request.Querys("showtype").ToString().ToInt(0);
            bool   showUser  = !"0".Equals(Request.Querys("shouser"));
            string refreshId = Request.Querys("refreshid");

            Business.Organize           organize = new Business.Organize();
            Newtonsoft.Json.Linq.JArray jArray   = new Newtonsoft.Json.Linq.JArray();

            #region 显示工作组
            if (1 == showType)
            {
                return("");
            }
            #endregion

            if (refreshId.IsGuid(out Guid guid))
            {
                var childs = organize.GetChilds(guid);
                foreach (var child in childs)
                {
                    Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                    {
                        { "id", child.Id },
                        { "parentID", child.ParentId },
                        { "title", child.Name },
                        { "ico", "" },
                        { "link", "" },
                        { "type", child.Type },
                        { "hasChilds", organize.HasChilds(child.Id) ? 1 : showUser?organize.HasUsers(child.Id) ? 1 : 0 : 0 }
                    };
                    jArray.Add(jObject);
                }
                if (showUser)
                {
                    var users         = organize.GetUsers(guid);
                    var organizeUsers = new Business.OrganizeUser().GetListByOrganizeId(guid);
                    foreach (var userModel in users)
                    {
                        var  organizeUserModel1 = organizeUsers.Find(p => p.UserId == userModel.Id);
                        bool isPartTime         = organizeUserModel1.IsMain != 1;//是否是兼职
                        Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", isPartTime ? organizeUserModel1.Id : userModel.Id },
                            { "parentID", guid },
                            { "title", userModel.Name + (isPartTime ? "<span style='color:#666;'>[兼任]</span>" : "") },
                            { "ico", "fa-user" },
                            { "link", "" },
                            { "userID", userModel.Id },
                            { "type", isPartTime ? 6 : 4 },
                            { "hasChilds", 0 }
                        };
                        jArray.Add(jObject);
                    }
                }
            }
            return(jArray.ToString());
        }
Esempio n. 2
0
        //Creating JArray
        public Newtonsoft.Json.Linq.JArray GetJArray2()
        {
            Newtonsoft.Json.Linq.JArray array = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JValue text  = new Newtonsoft.Json.Linq.JValue("Manual text");
            Newtonsoft.Json.Linq.JValue date  = new Newtonsoft.Json.Linq.JValue(new DateTime(2000, 5, 23));
            //add to JArray
            array.Add(text);
            array.Add(date);

            return(array);
        }
        public string QueryDeleteList()
        {
            string form_name = Request.Forms("form_name");
            string typeid    = Request.Querys("typeid");
            string sidx      = Request.Forms("sidx");
            string sord      = Request.Forms("sord");

            int    size   = Tools.GetPageSize();
            int    number = Tools.GetPageNumber();
            string order  = (sidx.IsNullOrEmpty() ? "CreateDate" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);

            Business.Form form  = new Business.Form();
            var           forms = form.GetPagerList(out int count, size, number, Current.UserId, form_name, "", order, 2);

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();
            foreach (System.Data.DataRow dr in forms.Rows)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Name", dr["Name"].ToString() },
                    { "CreateUserName", dr["CreateUserName"].ToString() },
                    { "CreateTime", dr["CreateDate"].ToString().ToDateTime().ToDateTimeString() },
                    { "LastModifyTime", dr["EditDate"].ToString().ToDateTime().ToDateTimeString() },
                    { "Edit", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"reply('" + dr["Id"].ToString() + "', '" + dr["Name"].ToString() + "');return false;\"><i class=\"fa fa-reply\"></i>还原</a>" }
                };
                jArray.Add(jObject);
            }
            return("{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}");
        }
Esempio n. 4
0
        /// <summary>
        /// 得到一个流程所有的表和字段
        /// </summary>
        /// <returns></returns>
        public string GetTableJSON()
        {
            string dbs = Request.Forms("dbs");

            if (dbs.IsNullOrWhiteSpace())
            {
                return("[]");
            }
            Newtonsoft.Json.Linq.JArray jArray = null;
            try
            {
                jArray = Newtonsoft.Json.Linq.JArray.Parse(dbs);
            }
            catch
            {
                return("[]");
            }
            if (null == jArray)
            {
                return("[]");
            }
            Business.DbConnection       dbConnection = new Business.DbConnection();
            Newtonsoft.Json.Linq.JArray jArray1      = new Newtonsoft.Json.Linq.JArray();
            foreach (Newtonsoft.Json.Linq.JObject jObject in jArray)
            {
                string table  = jObject.Value <string>("table");
                string connId = jObject.Value <string>("link");
                int    type   = 0;
                if (!connId.IsGuid(out Guid cid))
                {
                    continue;
                }
                var dbConnModel = dbConnection.Get(cid);
                if (null == dbConnModel)
                {
                    continue;
                }
                Newtonsoft.Json.Linq.JObject jObject1 = new Newtonsoft.Json.Linq.JObject
                {
                    { "table", table },
                    { "connId", connId },
                    { "type", type },
                    { "connName", dbConnModel.Name + "(" + dbConnModel.ConnType + ")" }
                };
                var fields = dbConnection.GetTableFields(cid, table);
                Newtonsoft.Json.Linq.JArray fieldArray = new Newtonsoft.Json.Linq.JArray();
                foreach (var field in fields)
                {
                    Newtonsoft.Json.Linq.JObject jObject2 = new Newtonsoft.Json.Linq.JObject
                    {
                        { "name", field.FieldName },
                        { "comment", field.Comment }
                    };
                    fieldArray.Add(jObject2);
                }
                jObject1.Add("fields", fieldArray);
                jArray1.Add(jObject1);
            }
            return(jArray1.ToString());
        }
Esempio n. 5
0
        public Newtonsoft.Json.Linq.JArray GetEXP(string sql, out string outStr)
        {
            outStr = "";
            Newtonsoft.Json.Linq.JArray data = new Newtonsoft.Json.Linq.JArray();
            var dt = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(sql);

            if (dt.Rows.Count > 0)
            {
                //提取公式内{}内容获取规则明细名称
                string exp = dt.Rows[0]["EXPRESSION"] + string.Empty;
                exp.Replace('×', '*');
                exp.Replace('÷', '/');
                outStr = exp;
                MatchCollection mc = Regex.Matches(exp, @"{([^}]+)}");
                foreach (var item in mc)
                {
                    string s       = item.ToString();
                    string s0      = s.Substring(1, s.Length - 2);
                    string Namesql = string.Format("select DETAILENAME from C_RULEDETAILS where objectid='{0}' ", s0);
                    var    name    = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteScalar(Namesql) + string.Empty;
                    string s1      = "<button style='margin:1px' value='" + s0 + "'>" + name + "</button>";
                    exp = exp.Replace(s, s1);
                }
                Newtonsoft.Json.Linq.JObject ret = new Newtonsoft.Json.Linq.JObject();
                ret.Add("exp", exp);
                data.Add(ret);
            }
            return(data);
        }
        public string TreeRefresh()
        {
            string refreshId = Request.Querys("refreshid");

            if (!refreshId.IsGuid(out Guid rid))
            {
                return("[]");
            }
            Business.Dictionary dictionary = new Business.Dictionary();
            var childs = dictionary.GetChilds(rid);

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var child in childs)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", child.Id },
                    { "parentID", child.ParentId },
                    { "title", child.Status == 1 ? "<span style='color:#999'>" + child.Title + "[作废]</span>" : child.Title },
                    { "type", "2" },
                    { "ico", "" },
                    { "hasChilds", dictionary.HasChilds(child.Id) ? 1 :0 }
                };
                jArray.Add(jObject);
            }
            return(jArray.ToString());
        }
        public IActionResult Index()
        {
            bool isoneself = "1".Equals(Request.Querys("isoneself"));
            Guid userId    = Current.UserId;
            var  all       = new Business.FlowComment().GetAll();

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();
            foreach (var comment in all)
            {
                if (isoneself && comment.UserId != userId)
                {
                    continue;
                }
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", comment.Id },
                    { "Comments", comment.Comments },
                    { "UserId", !comment.UserId.IsEmptyGuid() ? user.GetName(comment.UserId) : "全部人员" },
                    { "AddType", comment.AddType == 0 ? "用户添加" : "管理员添加" },
                    { "Sort", comment.Sort },
                    { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + comment.Id + "');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" }
                };

                jArray.Add(jObject);
            }

            ViewData["json"]      = jArray.ToString();
            ViewData["appId"]     = Request.Querys("appid");
            ViewData["tabId"]     = Request.Querys("tabid");
            ViewData["isoneself"] = Request.Querys("isoneself");
            return(View());
        }
Esempio n. 8
0
        public IActionResult InstanceManage()
        {
            string groupId = Request.Querys("groupid");

            Business.FlowTask flowTask = new Business.FlowTask();
            var groupTasks             = flowTask.GetListByGroupId(groupId.ToGuid());

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var groupTask in groupTasks)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject();
                string opation = "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"cngStatus('" + groupTask.Id.ToString() + "');\"><i class=\"fa fa-exclamation\"></i>状态</a>";
                if (groupTask.ExecuteType.In(0, 1) && 5 != groupTask.TaskType)
                {
                    opation += "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"designate('" + groupTask.Id.ToString() + "');\"><i class=\"fa fa-hand-o-right\"></i>指派</a>"
                               + "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"goTo('" + groupTask.Id.ToString() + "');\"><i class=\"fa fa-level-up\"></i>跳转</a>";
                }
                jObject.Add("id", groupTask.Id);
                jObject.Add("StepID", groupTask.StepName);
                jObject.Add("SenderName", groupTask.SenderName);
                jObject.Add("ReceiveTime", groupTask.ReceiveTime.ToDateTimeString());
                jObject.Add("ReceiveName", groupTask.ReceiveName);
                jObject.Add("CompletedTime1", groupTask.CompletedTime1.HasValue ? groupTask.CompletedTime1.Value.ToDateTimeString() : "");
                jObject.Add("Status", flowTask.GetExecuteTypeTitle(groupTask.ExecuteType));
                jObject.Add("Comment", groupTask.Comments);
                jObject.Add("Note", groupTask.Note);
                jObject.Add("Opation", opation);
                jArray.Add(jObject);
            }
            ViewData["json"]     = jArray.ToString();
            ViewData["appid"]    = Request.Querys("appid");
            ViewData["iframeid"] = Request.Querys("iframeid");
            return(View());
        }
Esempio n. 9
0
        public void AddBook(Book book)
        {
            Newtonsoft.Json.Linq.JArray books = connector.GetInfo();

            books.Add(Newtonsoft.Json.Linq.JToken.FromObject(book));
            connector.WriteInfo(books);
        }
Esempio n. 10
0
        public static List <T> GetList <T>(DbDataReader dataReader)
        {
            // 列名
            var cols = new List <string>();

            for (int index = 0; index < dataReader.FieldCount; index++)
            {
                cols.Add(dataReader.GetName(index));
            }

            // 赋值
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            while (dataReader.Read() == true)
            {
                var toAdd_JObject = new Newtonsoft.Json.Linq.JObject();

                foreach (string col in cols)
                {
                    if (dataReader[col] != DBNull.Value)
                    {
                        toAdd_JObject.Add(col, dataReader[col].ToString());
                    }
                    else
                    {
                        toAdd_JObject.Add(col, null);
                    }
                }

                jArray.Add(toAdd_JObject);
            }

            return(jArray.ToObject <List <T> >());
        }
        public string QueryDelete()
        {
            string flow_name = Request.Forms("flow_name");
            string typeid    = Request.Forms("typeid");
            string sidx      = Request.Forms("sidx");
            string sord      = Request.Forms("sord");

            int    size   = Tools.GetPageSize();
            int    number = Tools.GetPageNumber();
            string order  = (sidx.IsNullOrEmpty() ? "CreateDate" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);

            Business.Flow flow  = new Business.Flow();
            var           flows = flow.GetPagerList(out int count, size, number, flow.GetManageFlowIds(Current.UserId), flow_name, "", order, 3);

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();
            foreach (System.Data.DataRow dr in flows.Rows)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Name", dr["Name"].ToString() },
                    { "CreateDate", dr["CreateDate"].ToString().ToDateTime().ToDateTimeString() },
                    { "CreateUser", user.GetName(dr["CreateUser"].ToString().ToGuid()) },
                    { "Status", flow.GetStatusTitle(dr["Status"].ToString().ToInt()) },
                    { "Note", dr["Note"].ToString() },
                    { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"reply('" + dr["Id"].ToString() + "', '" + dr["Name"].ToString() + "');return false;\"><i class=\"fa fa-reply\"></i>还原</a>" }
                };
                jArray.Add(jObject);
            }
            return("{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}");
        }
 public static void AddNonNullItem(ref Newtonsoft.Json.Linq.JArray array, Newtonsoft.Json.Linq.JToken json)
 {
     if (json != null)
     {
         array.Add(json);
     }
 }
            public Newtonsoft.Json.Linq.JArray GetJson(string page, string size, out int total)
            {
                total = 0;
                Newtonsoft.Json.Linq.JArray data = new Newtonsoft.Json.Linq.JArray();
                if (!string.IsNullOrWhiteSpace(page) && !string.IsNullOrWhiteSpace(size))
                {
                    string query = "";
                    if (!string.IsNullOrWhiteSpace(DEALERNAME))
                    {
                        query += (query == "" ? " WHERE" : " AND") + " DEALERNAME LIKE '%" + DEALERNAME + "%'";
                    }
                    //if (!string.IsNullOrWhiteSpace(NWWW))
                    //{
                    //    query += (query == "" ? " WHERE" : " AND") + " NWWW LIKE '%" + NWWW + "%'";
                    //}
                    //if (!string.IsNullOrWhiteSpace(KIND))
                    //{
                    //    query += (query == "" ? " WHERE" : " AND") + " KIND LIKE '%" + KIND + "%'";
                    //}
                    //if (!string.IsNullOrWhiteSpace(JXS_LEVEL))
                    //{
                    //    query += (query == "" ? " WHERE" : " AND") + " JXS_LEVEL LIKE '%" + JXS_LEVEL + "%'";
                    //}
                    int _size = int.Parse(size);
                    int start = int.Parse(page) * _size;
                    System.Data.DataTable products = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable("select * from DZ_V_H3_BUSINESSDATACOLLECT " + query + " ORDER BY DEALERNAME ASC");

                    foreach (DataRow row in products.Rows)
                    {
                        if (total >= start && this.products.Count < _size)
                        {
                            this.products.Add(new MortgageList()
                            {
                                DEALERNAME  = ReadCell(row, "DEALERNAME"),
                                RISK        = ReadCell(row, "RISK"),
                                TOW         = ReadCell(row, "TOW"),
                                PUNISH      = ReadCell(row, "PUNISH"),
                                ARCHIVING   = ReadCell(row, "ARCHIVING"),
                                COMPLAIN    = ReadCell(row, "COMPLAIN"),
                                UPDATETIME  = ReadCell(row, "UPDATETIME"),
                                ObjectID    = ReadCell(row, "ObjectID"),
                                DealerId    = ReadCell(row, "DealerId"),
                                CRMDEALERID = ReadCell(row, "CRMDEALERID")
                            });
                        }
                        total++;
                    }
                    this.products.Sort();
                    foreach (MortgageList p in this.products)
                    {
                        data.Add(p.GetJson(++start));
                    }
                }
                else
                {
                }
                return(data);
            }
Esempio n. 14
0
        private string GetResult(NeoArrayContainer container)
        {
            var array = new Newtonsoft.Json.Linq.JArray();

            foreach (var x in container.GetVariables())
            {
                array.Add(GetResult(x));
            }
            return(array.ToString(Newtonsoft.Json.Formatting.Indented));
        }
Esempio n. 15
0
        public string QueryCompleted()
        {
            string appid  = Request.Querys("appid");
            string tabid  = Request.Querys("tabid");
            string flowid = Request.Forms("flowid");
            string title  = Request.Forms("title");
            string date1  = Request.Forms("date1");
            string date2  = Request.Forms("date2");
            string sidx   = Request.Forms("sidx");
            string sord   = Request.Forms("sord");
            string order  = (sidx.IsNullOrEmpty() ? "CompletedTime1" : sidx) + " " + (sord.IsNullOrEmpty() ? "ASC" : sord);
            int    size   = Tools.GetPageSize();
            int    number = Tools.GetPageNumber();

            Business.FlowTask flowTask  = new Business.FlowTask();
            DataTable         dataTable = flowTask.GetCompletedTask(size, number, Current.UserId, flowid, title, date1, date2, order, out int count);

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (DataRow dr in dataTable.Rows)
            {
                int           openModel = 0, width = 0, height = 0;
                StringBuilder opation = new StringBuilder(
                    "<a href=\"javascript:void(0);\" class=\"list\" onclick=\"openTask('" + Url.Content("~/RoadFlowCore/FlowRun/Index") + "?" + string.Format("flowid={0}&stepid={1}&instanceid={2}&taskid={3}&groupid={4}&appid={5}&display=1",
                                                                                                                                                              dr["FlowId"], dr["StepId"], dr["InstanceId"], dr["Id"], dr["GroupId"], appid
                                                                                                                                                              ) + "','" + dr["Title"].ToString().RemoveHTML().UrlEncode() + "','" + dr["Id"] + "'," + openModel + "," + width + "," + height + ");return false;\"><i class=\"fa fa-file-text-o\"></i>表单</a>" +
                    "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"detail('" + dr["FlowId"] + "','" + dr["GroupId"] + "','" + dr["Id"] + "');return false;\"><i class=\"fa fa-navicon\"></i>过程</a>");
                bool isHasten = flowTask.IsHasten(dr["Id"].ToString().ToGuid(), out bool isWithdraw);
                if (isWithdraw)
                {
                    opation.Append("<a class=\"list\" href=\"javascript:void(0);\" onclick=\"withdraw('" + dr["Id"] + "','" + dr["GroupId"] + "');return false;\"><i class=\"fa fa-mail-reply\"></i>收回</a>");
                }
                if (isHasten)
                {
                    opation.Append("<a class=\"list\" href=\"javascript:void(0);\" onclick=\"hasten('" + dr["Id"] + "','" + dr["GroupId"] + "');return false;\"><i class=\"fa fa-bullhorn\"></i>催办</a>");
                }
                string taskTitle = "<a href=\"javascript:void(0);\" class=\"list\" onclick=\"openTask('" + Url.Content("~/RoadFlowCore/FlowRun/Index") + "?" + string.Format("flowid={0}&stepid={1}&instanceid={2}&taskid={3}&groupid={4}&appid={5}&display=1",
                                                                                                                                                                             dr["FlowId"], dr["StepId"], dr["InstanceId"], dr["Id"], dr["GroupId"], appid
                                                                                                                                                                             ) + "','" + dr["Title"].ToString().RemoveHTML().UrlEncode() + "','" + dr["Id"] + "'," + openModel + "," + width + "," + height + ");return false;\">" + dr["Title"] + "</a>";
                string note = dr["Note"].ToString();
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Title", taskTitle },
                    { "FlowName", dr["FlowName"].ToString() },
                    { "StepName", dr["StepName"].ToString() },
                    { "SenderName", dr["SenderName"].ToString() },
                    { "ReceiveTime", dr["ReceiveTime"].ToString().ToDateTime().ToDateTimeString() },
                    { "CompletedTime", dr["CompletedTime1"].ToString().ToDateTime().ToDateTimeString() },
                    { "Note", note },
                    { "Opation", opation.ToString() }
                };
                jArray.Add(jObject);
            }
            return("{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}");
        }
Esempio n. 16
0
        public static string GetAllRequestJSON(string search_text, string RequestID)
        {
            //Security Check
            if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "read"))
            {
                throw new Exception("No Access.");
            }
            //Get current user info
            SYS_UserView            current_user = Controller_User.GetUser(RequestID, RequestID);
            LINQ_MeetingDataContext dc           = new LINQ_MeetingDataContext();

            //Security Check For AllDepartment
            string departmentID = "";

            if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "allDepartment"))
            {
                departmentID = current_user.DepartmentID;
            }

            List <MET_RequestView> the_requestlist = (from c in dc.MET_RequestViews
                                                      where c.Active == true && (departmentID == "" || (departmentID != "" && c.DepartmentID == departmentID)) &&
                                                      ((search_text == "") ||
                                                       (search_text != "" && (

                                                            c.RequestNo.Contains(search_text) ||
                                                            c.RequestStatus.Contains(search_text) ||
                                                            c.RequestTitle.Contains(search_text) ||
                                                            c.RequestType.Contains(search_text) ||
                                                            c.Description.Contains(search_text) ||
                                                            c.Remark.Contains(search_text) ||
                                                            c.DepartmentName.Contains(search_text))))
                                                      orderby c.CreatedOn descending
                                                      select c
                                                      ).ToList();
            var lists = new Newtonsoft.Json.Linq.JArray() as dynamic;

            foreach (var row in the_requestlist)
            {
                dynamic request = new Newtonsoft.Json.Linq.JObject();

                request.RequestID       = row.RequestID;
                request.DepartmentID    = row.DepartmentID;
                request.RequestType     = row.RequestType;
                request.RequestNo       = row.RequestNo;
                request.RequestUserName = row.RequestUserName;
                request.RequestTitle    = row.RequestTitle;
                request.RequestStatus   = row.RequestStatus;
                request.RequestOn       = row.RequestOn;
                request.DepartmentName  = row.DepartmentName;
                request.ApprovalStatus  = row.ApprovalStatus;
                lists.Add(request);
            }

            return(lists.ToString());
        }
Esempio n. 17
0
        /// <summary>
        /// 得到所有按钮JSON
        /// </summary>
        /// <returns></returns>
        public Newtonsoft.Json.Linq.JArray GetAllJson()
        {
            var buttons = GetAll();

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var button in buttons)
            {
                jArray.Add(Newtonsoft.Json.Linq.JObject.Parse(button.ToString()));
            }
            return(jArray);
        }
        /// <summary>
        /// get all bills filtered by both subject and start dates.
        /// The start dates of the sessions helps keep us from making quite so many
        /// bill queries.
        /// </summary>
        /// <param name="state"></param>
        /// <param name="startdate"></param>
        /// <param name="subjects">each space delimited token is searched for and all bill subjects that contain any token are returned</param>
        /// <param name="cursor"></param>
        /// <param name="f">action for each bill. null means no action.</param>
        public async Task <Newtonsoft.Json.Linq.JArray> GetBillsFilteredAsync(string state, DateTime startdate, DateTime enddate, string subjects, string cursor, ExtraActionPerBill f)
        {
            OpenStateClientLib.OpenStateClient cli;
            cli = new OpenStateClientLib.OpenStateClient();

            Newtonsoft.Json.Linq.JArray AllBills = new Newtonsoft.Json.Linq.JArray();

            var results = await cli.GetStateLegesAsync(state);

            var aaa = results.Data;

            List <string>   SessionNames;
            List <string>   SessionIds;
            List <DateTime> SessionStarts;
            bool            Ok = ExtractSessionNames(results, out SessionNames, out SessionIds, out SessionStarts);

            if (SessionNames != null && SessionIds != null)
            {
                int nn = SessionNames.Count;
                for (int ii = 0; ii < nn; ii++)
                {
                    string SessionI   = SessionNames[ii];
                    string SessionIdI = SessionIds[ii];
                    if (startdate <= SessionStarts[ii])
                    {
                        Newtonsoft.Json.Linq.JArray Bills = await cli.GetBillsAllAsync(state, SessionIdI, "", null);

                        if (Bills != null)
                        {
                            int n = Bills.Count;
                            for (int i = 0; i < n; i++)
                            {
                                Newtonsoft.Json.Linq.JToken OneBill = Bills[i]["node"];

                                Newtonsoft.Json.Linq.JArray SubjectsFound = OneBill["subject"] as Newtonsoft.Json.Linq.JArray;
                                string          updatedAt = OneBill["updatedAt"].ToString();
                                System.DateTime updatedAtDate;
                                bool            OkUpdatedAtDate = System.DateTime.TryParse(updatedAt, out updatedAtDate);
                                if (OkUpdatedAtDate && updatedAtDate >= startdate &&
                                    updatedAtDate <= enddate &&
                                    OpenStateClientLib.OpenStateClient.IsBillSubjectFound(subjects, SubjectsFound))
                                {
                                    f?.Invoke(OneBill);
                                    AllBills.Add(OneBill);
                                }
                            }
                        }
                    }
                }
            }
            return(AllBills);
        }
Esempio n. 19
0
        private void SaveSeans(List <FilmEntry> newData)
        {
            Newtonsoft.Json.Linq.JArray  res  = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JObject data = new Newtonsoft.Json.Linq.JObject();
            foreach (var c in newData)
            {
                var temp = Newtonsoft.Json.Linq.JObject.Parse(JsonConvert.SerializeObject(c));
                res.Add(temp);
            }
            data["data"] = res;

            File.WriteAllText("filmList.json", data.ToString());
        }
Esempio n. 20
0
        /// <summary>
        /// Lists the holidays for the company and its permanent establishments for the specified year( and country).
        /// </summary>
        /// <param name="year"></param>
        /// <returns>A collection of holiday objects in JSON format, sorted by country codes and categorized into
        /// general holidays(for the whole country), state holidays(for specific regions or states) and
        /// permanent establishment holidays(that only affect certain permanent establishments of the company).</returns>
        public async System.Threading.Tasks.Task <HRworksConnector.Models.GeneralActions.HolidaysResponse> GetHolidaysAsync(int year)
        {
            const string Target = @"GetHolidays";

            Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject();
            json["year"] = year;

            Newtonsoft.Json.Linq.JArray countryCodesAsJson = new Newtonsoft.Json.Linq.JArray();
            countryCodesAsJson.Add("DEU");
            json["countryCodes"] = countryCodesAsJson;

            return(await PostAsync <HRworksConnector.Models.GeneralActions.HolidaysResponse>(Target, json));
        }
Esempio n. 21
0
 static void SQLADONETQuery(SQLQuery q, SQLResult result, ConnectionParams cp, bool rollbackOnly)
 {
     using (SqlConnection t = new SqlConnection(cp.getConnectionString()))             //{ t.Open();
         using (SqlCommand sqlCommand = new SqlCommand {
             Connection = t
         }) {
             sqlCommand.Connection.Open();
             if (!string.IsNullOrEmpty(q.userQuery))
             {
                 if (!string.IsNullOrEmpty(q.SQL))
                 {
                     throw new Exception("SQL must be empty for a user query request");
                 }
                 q.SQL = getUserQuerySQL(t, q, cp);
                 checkRollbackOnlyConditions(result.rollbackOnly, q.SQL);
             }
             result.SQL             = q.SQL;
             result.userQuery       = !string.IsNullOrEmpty(q.userQuery) ? q.uqCategory + "." + q.userQuery : null;
             result.extendedUQ      = q.uqCategory != null && q.uqCategory.EndsWith(UQCATEGORY_EXTENSION);
             sqlCommand.CommandText = q.SQL;
             using (SqlDataReader rs = sqlCommand.ExecuteReader(System.Data.CommandBehavior.Default)) {
                 result.statusCode = System.Net.HttpStatusCode.OK;
                 var data = new Newtonsoft.Json.Linq.JArray();
                 do
                 {
                     while (rs.Read())
                     {
                         var row = new Newtonsoft.Json.Linq.JObject();
                         for (int i = 0; i < rs.FieldCount; i++)
                         {
                             row.Add(rs.GetName(i), rs.GetValue(i).ToString());
                         }
                         data.Add(row);
                     }
                     result.data = data;
                     if (q.columnInfo)
                     {
                         int cc = rs.FieldCount;
                         for (int i = 0; i < cc; i++)
                         {
                             SQLResult.Column column = new SQLResult.Column();
                             column.name     = rs.GetName(i);
                             column.dataType = rs.GetDataTypeName(i);
                             //column.subType = ;//Hmm, What to give here?
                             result.columns.Add(column);
                         }
                     }
                 } while (rs.NextResult());
             }
         }
 }
Esempio n. 22
0
        /// <summary>
        /// 得到导出的JSON字符串
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetExportString(string id)
        {
            if (!id.IsGuid(out Guid dictId))
            {
                return(string.Empty);
            }
            var dicts = GetAllChilds(dictId, true);

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var dict in dicts)
            {
                jArray.Add(Newtonsoft.Json.Linq.JObject.FromObject(dict));
            }
            return(jArray.ToString());
        }
Esempio n. 23
0
        internal void DeleteMux(Mux mux)
        {
            var wr = NewWebRequest("api/idnode/delete");

            wr.Method = "POST";
            var param = "uuid=";
            var obj   = new Newtonsoft.Json.Linq.JArray();

            obj.Add(mux.UUID);
            var byteArray = Encoding.UTF8.GetBytes(param + System.Web.HttpUtility.UrlEncode(obj.ToString()));

            SetRequestStream(wr, byteArray);

            wr.GetResponse();
        }
        public async Task CreateDeepnetFromRemoteSource()
        {
            // Prepare connection
            Client c = new Client(userName, apiKey);

            // Create source
            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "http://static.bigml.com/csv/iris.csv");
            Source s = await c.CreateSource(args);

            s = await c.Wait <Source>(s.Resource);

            Assert.AreEqual(s.StatusMessage.StatusCode, Code.Finished);

            // Create dataset
            DataSet.Arguments argsDS = new DataSet.Arguments();
            argsDS.Add("source", s.Resource);
            DataSet ds = await c.CreateDataset(argsDS);

            ds = await c.Wait <DataSet>(ds.Resource);

            Assert.AreEqual(ds.StatusMessage.StatusCode, Code.Finished);

            // Create deepnet
            Deepnet.Arguments argsDn = new Deepnet.Arguments();
            argsDn.Add("dataset", ds.Resource);
            Deepnet dn = await c.CreateDeepnet(argsDn);

            dn = await c.Wait <Deepnet>(dn.Resource);

            Assert.AreEqual(dn.StatusMessage.StatusCode, Code.Finished);

            // test UPDATE method
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("Bindings C# test");
            changes.Add("tags", tags);
            dn = await c.Update <Deepnet>(dn.Resource, changes);

            Assert.AreEqual(dn.Code, System.Net.HttpStatusCode.Accepted);

            // test DELETE method
            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(dn);
        }
Esempio n. 25
0
        public static string GetAllAgendaJSON(string search_text, string RequestID)
        {
            //Security Check
            if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "read"))
            {
                throw new Exception("No Access.");
            }
            //Get current user info
            SYS_UserView            current_user = Controller_User.GetUser(RequestID, RequestID);
            LINQ_MeetingDataContext dc           = new LINQ_MeetingDataContext();

            //Security Check For AllDepartment
            string departmentID = "";

            if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "allDepartment"))
            {
                departmentID = current_user.DepartmentID;
            }
            List <MET_AgendaView> the_agendalist = (from c in dc.MET_AgendaViews
                                                    where c.Active == true && (departmentID == "" || (departmentID != "" && c.DepartmentID == departmentID)) &&
                                                    ((search_text == "") ||
                                                     (search_text != "" && (

                                                          c.AgendaNo.Contains(search_text) ||
                                                          c.AgendaRemark.Contains(search_text) ||
                                                          c.AgendaStatus.Contains(search_text) ||
                                                          c.CUserCode.Contains(search_text) ||
                                                          c.MUserCode.Contains(search_text)
                                                          )))
                                                    orderby c.CreatedOn descending
                                                    select c
                                                    ).ToList();
            var lists = new Newtonsoft.Json.Linq.JArray() as dynamic;

            foreach (var row in the_agendalist)
            {
                dynamic agenda = new Newtonsoft.Json.Linq.JObject();

                agenda.AgendaID     = row.AgendaID;
                agenda.AgendaNo     = row.AgendaNo;
                agenda.AgendaDate   = row.AgendaDate.ToString();
                agenda.AgendaRemark = row.AgendaRemark;
                agenda.AgendaStatus = row.AgendaStatus;
                lists.Add(agenda);
            }

            return(lists.ToString());
        }
        public Newtonsoft.Json.Linq.JArray GetPerproty(string id)
        {
            Newtonsoft.Json.Linq.JArray data = new Newtonsoft.Json.Linq.JArray();
            DataTable dt  = new DataTable();
            string    sql = "SELECT ENUMVALUE   from OT_EnumerableMetadata t where CATEGORY='" + id + "'";

            dt = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(sql);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Newtonsoft.Json.Linq.JObject ret = new Newtonsoft.Json.Linq.JObject();
                ret.Add("ENUMVALUE", dt.Rows[i]["ENUMVALUE"].ToString());
                data.Add(ret);
            }
            return(data);
        }
Esempio n. 27
0
        public void Index()
        {
            var context = HttpContext;
            Dictionary <int, int> baseProducts = new Dictionary <int, int>();
            string Dealer = UserValidatorFactory.CurrentUser.UserCode;

            System.Data.DataTable allProducts = this.ExecuteDataTableSql("CAPDB", @"SELECT distinct FD.FINANCIAL_PRODUCT_ID ProductID,FP.FINANCIAL_PRODUCT_NME ProductName
FROM 
FP_DEALER@to_cms FD 
JOIN FINANCIAL_PRODUCT@to_cms FP ON FD.FINANCIAL_PRODUCT_ID=FP.FINANCIAL_PRODUCT_ID
JOIN 
(SELECT BSU.WORKFLOW_LOGIN_NME , BM2.BUSINESS_PARTNER_ID ,BM2.BUSINESS_PARTNER_NME 
FROM BP_SYS_USER@to_cms BSU 
JOIN BP_MAIN@to_cms BM ON BSU.BP_SECONDARY_ID=BM.BUSINESS_PARTNER_ID 
JOIN BP_RELATIONSHIP@to_cms BRE ON BRE.BP_SECONDARY_ID=BM.BUSINESS_PARTNER_ID AND BRE.RELATIONSHIP_CDE='00112'
JOIN BP_MAIN@to_cms BM2 ON BM2.BUSINESS_PARTNER_ID=BRE.BP_PRIMARY_ID
WHERE  BSU.WORKFLOWLOGIN_ACTIVE_IND='T' ) 
WORKFLOW_LOGIN ON 
WORKFLOW_LOGIN.BUSINESS_PARTNER_ID=FD.BUSINESS_PARTNER_ID
WHERE to_char(FP.VALID_FROM_DTE,'yyyymmdd')< to_char(sysdate,'yyyymmdd') and to_char(FP.VALID_TO_DTE,'yyyymmdd')>to_char(sysdate,'yyyymmdd')"
                                                                         + " and WORKFLOW_LOGIN.WORKFLOW_LOGIN_NME='" + Dealer + "'"
                                                                         + " ORDER BY FD.FINANCIAL_PRODUCT_ID ASC");
            Newtonsoft.Json.Linq.JArray ret = new Newtonsoft.Json.Linq.JArray();
            if (allProducts != null)
            {
                for (int i = 0; i < allProducts.Rows.Count; i++)
                {
                    Newtonsoft.Json.Linq.JObject token = new Newtonsoft.Json.Linq.JObject();
                    token.Add("ProductID", int.Parse(ReadCell(allProducts.Rows[i], "ProductID")));
                    token.Add("ProductName", ReadCell(allProducts.Rows[i], "ProductName"));
                    token.Add("ProductDescription", "暂无描述");
                    ret.Add(token);
                    baseProducts.Add(int.Parse(ReadCell(allProducts.Rows[i], "ProductID")), i);
                }
            }

            System.Data.DataTable products = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable("SELECT p.* FROM C_PRODUCTS p LEFT JOIN OT_USER u ON p.dealer=u.appellation WHERE u.Code='" + UserValidatorFactory.CurrentUser.UserCode + "' ORDER BY ProductId ASC");
            foreach (DataRow row in products.Rows)
            {
                if (baseProducts.ContainsKey(int.Parse(ReadCell(row, "ProductID"))))
                {
                    ret[baseProducts[int.Parse(ReadCell(row, "ProductID"))]]["ProductName"]        = ReadCell(row, "ProductAlias");
                    ret[baseProducts[int.Parse(ReadCell(row, "ProductID"))]]["ProductDescription"] = ReadCell(row, "ProductDescription");
                }
            }
            context.Response.Write(ret);
        }
Esempio n. 28
0
        public Newtonsoft.Json.Linq.JArray GetDealer()
        {
            Newtonsoft.Json.Linq.JArray data = new Newtonsoft.Json.Linq.JArray();
            DataTable dt  = new DataTable();
            string    sql = "Select DISTINCT * FROM (SELECT \"DealerName\" as \"经销商编号\",\"DealerName\" as \"经销商名称\" FROM DEALERACCEDE UNION ALL SELECT cast(\"经销商名称\" as nvarchar2(1000)) as 经销商编号, cast(\"经销商名称\" as nvarchar2(1000)) as 经销商名称 FROM in_cms.MV_H3_DEALER_OD_INFO_CN)";

            dt = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(sql);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Newtonsoft.Json.Linq.JObject ret = new Newtonsoft.Json.Linq.JObject();
                ret.Add("key", dt.Rows[i]["经销商编号"].ToString());
                ret.Add("value", dt.Rows[i]["经销商名称"].ToString());
                data.Add(ret);
            }
            return(data);
        }
Esempio n. 29
0
        public static string RandomSampleJson(
            string json,
            int?seed             = null,
            int maxNumberOfItems = 10)
        {
            Newtonsoft.Json.Linq.JToken root = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
            Random random = seed.HasValue ? new Random(seed.Value) : new Random();

            string sampledJson;

            if (root.Type == Newtonsoft.Json.Linq.JTokenType.Array)
            {
                Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)root;
                IEnumerable <Newtonsoft.Json.Linq.JToken> tokens = array
                                                                   .OrderBy(x => random.Next())
                                                                   .Take(random.Next(maxNumberOfItems));
                Newtonsoft.Json.Linq.JArray newArray = new Newtonsoft.Json.Linq.JArray();
                foreach (Newtonsoft.Json.Linq.JToken token in tokens)
                {
                    newArray.Add(token);
                }

                sampledJson = newArray.ToString();
            }
            else if (root.Type == Newtonsoft.Json.Linq.JTokenType.Object)
            {
                Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)root;
                IEnumerable <Newtonsoft.Json.Linq.JProperty> properties = jobject
                                                                          .Properties()
                                                                          .OrderBy(x => random.Next())
                                                                          .Take(maxNumberOfItems);
                Newtonsoft.Json.Linq.JObject newObject = new Newtonsoft.Json.Linq.JObject();
                foreach (Newtonsoft.Json.Linq.JProperty property in properties)
                {
                    newObject.Add(property);
                }

                sampledJson = newObject.ToString();
            }
            else
            {
                sampledJson = json;
            }

            return(sampledJson);
        }
        public async Task CreateLogisticRegressionFromRemoteSource()
        {
            Client c = new Client(userName, apiKey);

            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "https://static.bigml.com/csv/iris.csv");
            args.Add("name", "C# tests - Iris");

            Source s = await c.CreateSource(args);

            s = await c.Wait <Source>(s.Resource);

            Assert.AreEqual(s.StatusMessage.StatusCode, Code.Finished);

            DataSet.Arguments argsDS = new DataSet.Arguments();
            argsDS.Add("source", s.Resource);
            DataSet ds = await c.CreateDataset(argsDS);

            ds = await c.Wait <DataSet>(ds.Resource);

            Assert.AreEqual(ds.StatusMessage.StatusCode, Code.Finished);

            LogisticRegression.Arguments argsTM = new LogisticRegression.Arguments();
            argsTM.Add("dataset", ds.Resource);
            LogisticRegression lr = await c.CreateLogisticRegression(argsTM);

            lr = await c.Wait <LogisticRegression>(lr.Resource);

            // test it is finished
            Assert.AreEqual(lr.StatusMessage.StatusCode, Code.Finished);

            // test update method
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("Bindings C# test");
            changes.Add("tags", tags);
            lr = await c.Update <LogisticRegression>(lr.Resource, changes);

            Assert.AreEqual(lr.Code, System.Net.HttpStatusCode.Accepted);

            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(lr);
        }
Esempio n. 31
0
        private void readJson(int month) /* 读取动画详细信息json */
        {
            Newtonsoft.Json.Linq.JArray jsonList1;
            string url = "";
            int t_month = month >= 10 ? 10 : month >= 7 ? 7 : month >= 4 ? 4 : month >= 1 ? 1 : 1;
            int t_year = comboBox3.SelectedIndex == -1 ? year : Int32.Parse(comboBox3.Items[comboBox3.SelectedIndex].ToString());
            foreach (archive a in archiveList)
            {
                if (a.year == t_year + "")
                {
                    foreach (months m in a.months)
                    {
                        if (m.month == t_month + "")
                        {
                            url = bgmlist + m.json;
                        }
                    }
                }
            }
            int adasd = "http://bgmlist.com/json/".Length;
            jsonName = url.Substring(adasd, url.Length - adasd);

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

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

                    ProxyDetails.ProxyType = pt;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            dataGridView1.DataSource = (from a in jsonList
                                        where Convert.ToInt32(a.weekDayCN) == day
                                        select a).ToList(); ;
        }
Esempio n. 32
0
        private Newtonsoft.Json.Linq.JToken parseField(OEIShared.IO.GFF.GFFField gffField)
        {
            Newtonsoft.Json.Linq.JToken j = null;

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

            return j;
        }
Esempio n. 33
0
        public void Deploy()
        {
            Console.WriteLine("");
            Console.WriteLine("Deploying JSON");

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

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

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

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

            checked
            {
                manager.AddRepository(directoryResourceRepository);

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

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

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

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

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

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

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

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

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

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

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

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

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

                System.IO.File.WriteAllText(@".\nwn2.json", json.ToString());
            }
        }
Esempio n. 34
0
        public static void SendTemplate( string template_name, Dictionary<string, object> data, TemplateOverrides overrides = null )
        {
            var template_path = System.Web.HttpContext.Current.Server.MapPath(Config.Manager.Framework.Email.Template.Path);
            var base_path = Path.Combine( template_path, template_name );

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

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

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

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

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

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

                    config["to"] = arr;
                }

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

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

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

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

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

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

                        var list = data[loop_over] as IEnumerable;

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

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

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

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

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

                            builder.AppendLine( t_content );
                        }

                        inner_content = builder.ToString();
                    }

                    data[name] = inner_content;
                }
            }

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

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

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

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

            // MJL 2014-01-13 - If you use the "To" field in the overrides, then the config["to"] is an array
            // the original code seems to assume it's not a collection.  I've added a simple check to see
            // if the object is a collection, of so, loop.
            if(!(config["to"] is ICollection))
                SendEmail((string)(config["to"]["email"]), (string)(config["subject"]), content, (string)(config["from"]["email"]), (string)(config["from"]["name"]));
            else
                foreach(var item in config["to"])
                    SendEmail((string)(item["email"]), (string)(config["subject"]), content, (string)(config["from"]["email"]), (string)(config["from"]["name"]));
        }
Esempio n. 35
0
 public static TradeRecordsCommand createTradeRecordsCommand(LinkedList<long?> orders, bool prettyPrint)
 {
     JSONObject args = new JSONObject();
     JSONArray arr = new JSONArray();
     foreach (long? order in orders)
     {
         arr.Add(order);
     }
     args.Add("orders", arr);
     return new TradeRecordsCommand(args, prettyPrint);
 }
Esempio n. 36
0
 public static TradingHoursCommand createTradingHoursCommand(LinkedList<string> symbols, bool prettyPrint)
 {
     JSONObject args = new JSONObject();
     JSONArray arr = new JSONArray();
     foreach (string symbol in symbols)
     {
         arr.Add(symbol);
     }
     args.Add("symbols", arr);
     return new TradingHoursCommand(args, prettyPrint);
 }
        public ActionResult Create()
        {
            int contactId = -1;
            ViewModels.Tasks.CreateTaskViewModel viewModel;
            Common.Models.Matters.Matter matter;
            List<ViewModels.Account.UsersViewModel> userList;
            List<ViewModels.Contacts.ContactViewModel> employeeContactList;
            Newtonsoft.Json.Linq.JArray taskTemplates;

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

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

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

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

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

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

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

            return View(new ViewModels.Tasks.CreateTaskViewModel()
            {
                TaskTemplates = viewModel.TaskTemplates,               
                TaskContact = new ViewModels.Tasks.TaskAssignedContactViewModel()
                {
                    AssignmentType = ViewModels.AssignmentTypeViewModel.Direct,
                    Contact = viewModel.TaskContact.Contact
                }
            });
        }
Esempio n. 38
0
        public static TickPricesCommand createTickPricesCommand(LinkedList<string> symbols, long? timestamp, bool prettyPrint)
        {
            JSONObject args = new JSONObject();
            JSONArray arr = new JSONArray();
            foreach (string symbol in symbols)
            {
                arr.Add(symbol);
            }

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