Exemplo n.º 1
0
        /// <summary>
        /// 当超过65536行后不能导出(可能是excel版本问题,暂时采用分sheet解决)--benjamin20191216
        /// </summary>
        /// <param name="y"></param>
        /// <param name="newY"></param>
        /// <param name="sheet"></param>
        private void GetSheetByY(int y, out int newY, out Worksheet newSheet)
        {
            int pageSize = 60000;

            if (y < pageSize)
            {
                newY     = y;
                newSheet = sheet;
                return;
            }
            else
            {
                //10
                //0~9:0
                //10~19:1

                //page从0开始的
                //var page = Math.Ceiling(Convert.ToDecimal(y) / Convert.ToDecimal(pageSize));
                var page = PFDataHelper.ObjectToInt(Math.Floor(Convert.ToDecimal(y) / Convert.ToDecimal(pageSize))) ?? 0;
                //var page=int.Parse(Math.Ceiling(y / pageSize).ToString())+1;
                if (page >= sheets.Count)
                {
                    //count=2,page=4, 2~4
                    for (var i = sheets.Count; i <= page; i++)
                    {
                        sheets.Add(workbook.Worksheets.Add("sheet" + (i + 1).ToString()));
                    }
                }
                newY     = y % pageSize;
                newSheet = sheets[page];
            }
        }
Exemplo n.º 2
0
        private static void TextBoxBind(TextBox textBox, PFModelConfig modelConfig)
        {
            if (modelConfig != null)
            {
                if (modelConfig.FieldType == typeof(decimal))
                {
                    textBox.Attributes.Add("onfocus", "this.oldvalue = this.value; ");
                    if (modelConfig.Precision.HasValue)
                    {
                        textBox.Attributes.Add("onchange", "if(!$pf.isDecimal(this.value," + modelConfig.Precision + ")){this.value=this.oldvalue;}");
                    }
                    else
                    {
                        textBox.Attributes.Add("onchange", "if(!$pf.isDecimal(this.value)){this.value=this.oldvalue;}");
                    }
                }
                else if (modelConfig.FieldType == typeof(int))
                {
                    textBox.Attributes.Add("onfocus", "this.oldvalue = this.value; ");
                    textBox.Attributes.Add("onchange", "if(!$pf.isInt(this.value)){this.value=this.oldvalue;}");
                }

                if (textBox.Width != null && textBox.Width.IsEmpty &&
                    (!PFDataHelper.StringIsNullOrWhiteSpace(modelConfig.FieldWidth)))
                {
                    textBox.Width = new Unit(modelConfig.FieldWidth);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 控件绑定模型配置
        /// </summary>
        /// <param name="page"></param>
        /// <param name="modelName">实现IPFConfigMapper的类中定义</param>
        /// <param name="list"></param>
        public static void BindModel(string modelName, List <ModelBindConfig> list)
        {
            var modelConfig = PFDataHelper.GetMultiModelConfig(modelName);

            foreach (var i in list)
            {
                PFModelConfig config = null;
                if (modelConfig != null)
                {
                    config = modelConfig[i.GetPropertyName()];
                }
                if (i.GetComponent() is System.Web.UI.WebControls.Label)
                {
                    System.Web.UI.WebControls.Label tmpControl = (System.Web.UI.WebControls.Label)i.GetComponent();
                    LabelBind(tmpControl, config);
                }
                else if (i.GetComponent() is System.Web.UI.WebControls.TextBox)
                {
                    System.Web.UI.WebControls.TextBox tmpControl = (System.Web.UI.WebControls.TextBox)i.GetComponent();
                    BindValidator(tmpControl, config, i.GetValidator());
                    LabelBind(i.GetLabel(), config);
                    TextBoxBind(tmpControl, config);
                }
                else if (i.GetComponent() is System.Web.UI.WebControls.DropDownList)
                {
                    System.Web.UI.WebControls.DropDownList tmpControl = (System.Web.UI.WebControls.DropDownList)i.GetComponent();
                    BindValidator(tmpControl, config, i.GetValidator());
                    LabelBind(i.GetLabel(), config);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 读取控件的value到object
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="list"></param>
        public static void ReadControlToObject(object obj, Dictionary <Control, string> list)
        {
            string property = string.Empty;
            Type   ot       = obj.GetType();

            try
            {
                foreach (var i in list)
                {
                    var ti = ot.GetProperty(i.Value);
                    property = ti.Name;
                    var  type = ti.PropertyType;
                    Type pt   = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>) ? type.GetGenericArguments()[0] : type;//获得非空类型

                    if (i.Key is System.Web.UI.WebControls.TextBox)
                    {
                        System.Web.UI.WebControls.TextBox tmpControl = (System.Web.UI.WebControls.TextBox)i.Key;
                        if (pt == typeof(String) || pt == typeof(string))
                        {
                            ti.SetValue(obj, tmpControl.Text, null);
                        }
                        else if (pt == typeof(decimal) || pt == typeof(int))
                        {
                            if (PFDataHelper.StringIsNullOrWhiteSpace(tmpControl.Text))
                            {
                                ti.SetValue(obj, null, null);//当ti为不可空的属性时,设null值不会报错,值为0
                            }
                            else
                            {
                                if (pt == typeof(decimal))
                                {
                                    ti.SetValue(obj, decimal.Parse(tmpControl.Text), null);
                                }
                                else if (pt == typeof(int))
                                {
                                    ti.SetValue(obj, int.Parse(tmpControl.Text), null);
                                }
                            }
                        }
                        else if (pt == typeof(DateTime))
                        {
                            DateTime d = new DateTime();
                            if (DateTime.TryParse(tmpControl.Text, out d))
                            {
                                ti.SetValue(obj, d, null);
                            }
                        }
                    }
                    else if (i.Key is System.Web.UI.WebControls.DropDownList)
                    {
                        System.Web.UI.WebControls.DropDownList tmpControl = (System.Web.UI.WebControls.DropDownList)i.Key;
                        ti.SetValue(obj, tmpControl.SelectedValue, null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + " Property:" + property);
            }
        }
Exemplo n.º 5
0
        public void SetColumnWidth(int x, string px)
        {
            double width = PFDataHelper.WebWidthToExcel(px).Value;

            sheet.Cells.SetColumnWidth(x, width);
            //sheet.Cells.SetColumnWidth(x, width);
        }
        public static RequestHostInfo GetRequestHostInfo(HttpRequestBase request)
        {
            var result = new RequestHostInfo
            {
                OSVersion = PFDataHelper.GetOSVersion(request), //ok
                Browser   = PFDataHelper.GetBrowser(request)
                                                                //,//,ok
                                                                //IPAddress = PFDataHelper.GetIPAddress(request),
                ,                                               //,ok
                IPAddress = request.UserHostAddress,
            };

            ////跨域访问时,这段代码报错:不知道这样的主机
            //string HostName = string.Empty;
            //string ip = string.Empty;
            //string ipv4 = String.Empty;

            //if (!string.IsNullOrEmpty(request.ServerVariables["HTTP_VIA"]))
            //    ip = Convert.ToString(request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            //if (string.IsNullOrEmpty(ip))
            //    ip = request.UserHostAddress;

            //// 利用 Dns.GetHostEntry 方法,由获取的 IPv6 位址反查 DNS 纪录,<br> // 再逐一判断何者为 IPv4 协议,即可转为 IPv4 位址。
            //foreach (IPAddress ipAddr in Dns.GetHostEntry(ip).AddressList)
            //{
            //    if (ipAddr.AddressFamily.ToString() == "InterNetwork")
            //    {
            //        ipv4 = ipAddr.ToString();
            //    }
            //}
            //result.HostName = Dns.GetHostEntry(ip).HostName;

            return(result);
            //HostName = "主机名: " + Dns.GetHostEntry(ip).HostName + " IP: " + ipv4;
        } /// <summary>
Exemplo n.º 7
0
 /// <summary>
 /// 根据row设置控件的value
 /// </summary>
 /// <param name="row"></param>
 /// <param name="list"></param>
 public static void SetControlByRow(DataRow row, Dictionary <Control, string> list)
 {
     foreach (var i in list)
     {
         object val = row[i.Value];
         if (i.Key is System.Web.UI.WebControls.TextBox)//现时使用TextBox的有:decimal,int,string,DateTime.(NumberEditor是继承TextBox的)
         {
             System.Web.UI.WebControls.TextBox tmpControl = (System.Web.UI.WebControls.TextBox)i.Key;
             if (val != null && val != DBNull.Value)
             {
                 if (val is DateTime)
                 {
                     tmpControl.Text = PFDataHelper.ObjectToDateString(val, tmpControl.Attributes["dateFmt"]);
                 }
                 if (val is string)
                 {
                     tmpControl.Text = val.ToString();
                 }
                 if (val is decimal)
                 {
                     tmpControl.Text = val.ToString();
                 }
                 if (val is int)
                 {
                     tmpControl.Text = val.ToString();
                 }
             }
         }
         else if (i.Key is System.Web.UI.WebControls.DropDownList)
         {
             System.Web.UI.WebControls.DropDownList tmpControl = (System.Web.UI.WebControls.DropDownList)i.Key;
             tmpControl.SelectedValue = val.ToString();
         }
     }
 }
Exemplo n.º 8
0
        public void BuildPFEmailMqConsumer(PFMqHelper.PFConsumerResponseTask pfDeliverCallback)
        {
            PFMqConfig mqConfig = pfDeliverCallback.GetMqConfig(_mqConfig);
            //string producerEmailTitle = "PFEmailMq_producer_" + "会员资料表";//中文有问题--benjamin todo
            //string producerEmailTitle = "PFEmailMq_producer_" + "hyzl";
            //消费方(使用系统邮箱)
            string result = "";
            //bool success = false;
            var consumerTask = new PFListenEmailTask("PFEmailMqConsumerListener_" + mqConfig.getTopic(),
                                                     new PFEmailManager(PFDataHelper.SysEmailHostName, PFDataHelper.SysEmailUserName, PFDataHelper.SysEmailPwd),
                                                     email =>
            {
                //result = "{success:true}";
                PFMqMessage pfMessage = new PFMqMessage(email);
                var r = pfDeliverCallback.handle(mqConfig.getTag(), pfMessage);
                if (r != null)
                {
                    var UserEmailUserName = PFDataHelper.SysEmailUserName;
                    ////消费方回复邮件(暂不回复--benjamin)
                    PFDataHelper.SendEmail(PFDataHelper.SysEmailUserName, PFDataHelper.SysEmailPwd, PFDataHelper.SysEmailHostName,
                                           new string[] { UserEmailUserName }, "PFEmailMq_consumer_Response_" + mqConfig.getTopic() + email.Body,
                                           JsonConvert.SerializeObject(r));
                }
            },
                                                     (email//, task
                                                     ) =>
            {
                //消费方监听生产方邮件
                //return email.Subject != null && email.Subject.IndexOf("TestForceUpdateHyzl_") == 0;//这里不要用>-1,否则可能把自动回复的邮件也当作是了
                return(email.Subject == "PFEmailMq_product_" + mqConfig.getTopic());
            });

            consumerTask.Start();
        }
Exemplo n.º 9
0
        public virtual void FillData(int x, int y, string field, object value)
        {
            //if (!field.StartsWith("title_"))
            //    cell.SetStyle(GetDataStyle());

            switch ((value ?? string.Empty).GetType().Name.ToLower())
            {
            case "int32":
            case "int64":
            case "decimal":
                sheet.Cells[y, x].PutValue(PFDataHelper.ObjectToType <double>(value, 0));
                break;

            //case "System.String[]":
            //    var s = String.Join(",", (string[])value);
            //    sheet.Cells[y, x].PutValue(s);
            //    break;
            default:
                if (value is string[])
                {
                    var s = String.Join(",", value as string[]);
                    sheet.Cells[y, x].PutValue(s);
                }
                else
                {
                    sheet.Cells[y, x].PutValue(PFDataHelper.ObjectToString(value));
                }
                break;
            }
        }
Exemplo n.º 10
0
        ///**
        //* "pm_coupon_grant为分表,会员卡号作为分表键,查询需要根据卡号求出表索引,再找到对应分表查询
        //* 得到hsah子表名
        //* </p>
        //* @param splitKeyVal
        //*        表拆分键的值(根据splitKeyVal值来取模)<br>
        //* @param subTableCount
        //*        要拆分子表总数<br>
        //* @return
        //*/
        //public static String GetSplitTableName(String tableName, Object splitKeyVal, int subTableCount)
        //{
        //    if (splitKeyVal == null)
        //    {
        //        throw new Exception("splitKeyVal is null.tableName:" + tableName);
        //    }
        //    long hashVal = splitKeyVal.ToString().GetHashCode();
        //    // 斐波那契(Fibonacci)散列
        //    hashVal = (hashVal * 2654435769L) >> 28;
        //    // 避免hashVal超出 MAX_VALUE = 0x7fffffff时变为负数,取绝对值
        //    hashVal = Math.Abs(hashVal) % subTableCount;
        //    return tableName + "_" + hashVal;
        //}


        public static void SendEmail(string[] toEmails, string mailTitle, string mailBody)
        {
            var sendHostName = "smtp.qq.com";
            var userName     = "******";
            var pwd          = "llcffwhxezsicadi";

            PFDataHelper.SendEmail(userName, pwd, sendHostName, toEmails, mailTitle, mailBody, a => { a.IsBodyHtml = false; });
        }
Exemplo n.º 11
0
 /// <summary>
 /// 其实最后用到的只是汇总后的_dt,如果原dt很大的话,这样可以节省性能
 /// </summary>
 public PFPivotTable GroupDataTable()
 {
     _dt = PFDataHelper.DataTableGroupBy(_dt,
                                         PFDataHelper.MergeList(new List <string>(_pivotLeft), _pivotTop).ToArray(),
                                         new PFKeyValueCollection <SummaryType>(_pivotValue.Select(a => new PFKeyValue <SummaryType> {
         Key = a, Value = SummaryType.Sum
     }))
                                         );
     return(this);
 }
Exemplo n.º 12
0
        public object handle(String consumerTag, PFMqMessage message)
        {
            var lastCMonth = ProjDataHelper.GetLastCMonthByDate(DateTime.Now);

            var p = JsonConvert.DeserializeObject <PagingParameters>(message.ToString());
            var backupDatabase = PFDataHelper.ObjectToString(p["backupDatabase"]) ?? "";
            var service        = new DbReportService(lastCMonth);
            var list           = service.GetCompareCntList(backupDatabase, false);

            return(list);
        }
Exemplo n.º 13
0
        public void Add <TProperty>(Expression <Func <T, TProperty> > expression, Action <StoreColumn> action = null)//, bool setWidthByHeaderWord = true)
        {
            var propertyName = ExpressionHelper.GetExpressionText(expression);

            Add(propertyName, c =>
            {
                c.dataType = PFDataHelper.GetStringByType(typeof(TProperty));
                if (action != null)
                {
                    action(c);
                }
            });
        }
Exemplo n.º 14
0
 public void SetFinish(string alertMessage)
 {
     //MessageBox.Show("总耗时:" + Newtonsoft.Json.JsonConvert.SerializeObject(PFDataHelper.GetTimeSpan(DateTime.Now - _beginTime)));
     //// 采用Invoke形式进行操作
     this.Invoke(new MethodInvoker(() =>
     {
         this.lbl_tips.Text          = "操作已完成";
         this.lbl_tips_son.Text      = "总耗时:" + PFDataHelper.GetTimeSpan(DateTime.Now - _beginTime).ToString();
         this.lbl_tips.ForeColor     = System.Drawing.Color.Blue;
         this.lbl_tips_son.ForeColor = System.Drawing.Color.Blue;
         MessageBox.Show(alertMessage);
     }));
 }
Exemplo n.º 15
0
        public void StartThread(object ps)
        {
            _lastBackupCmonth = null;
            while (_running == true)
            {
                try
                {
                    var cmonth = Cmonth;
                    if (cmonth == _lastBackupCmonth)//该月已执行
                    {
                        //Thread.Sleep(ProjDataHelper.CheckMessageInterval);
                        Thread.Sleep(CheckMessageInterval);
                        continue;
                    }

                    var now = DateTime.Now;

                    var backupDay = new DateTime(now.Year, now.Month, BackupDay, BackupHour, BackupMinute, 0);
                    if (backupDay > now || FirstRunTime > now)//未到执行的日期
                    {
                        Thread.Sleep(PFTaskHelper.CheckMessageInterval);
                        continue;
                    }

                    if (!CanDoAction(cmonth, this))
                    {
                        Thread.Sleep(CheckMessageInterval);
                        continue;
                    }

                    _lastBackupCmonth = cmonth;
                    _nextRunTime      = backupDay.AddMonths(1);

                    PFDataHelper.WriteLog(string.Format("任务{0}开始执行,月份为:{1}", HashId, cmonth));//调用这个方法来写这个值并不好,因为每天都单独一个txt的
                    try
                    {
                        DoAction(cmonth, this);
                        PFDataHelper.WriteLog(string.Format("任务{0}执行完毕,月份为:{1}", HashId, cmonth));
                    }
                    catch (Exception e)
                    {
                        PFDataHelper.WriteError(e);
                    }
                    GC.Collect();//一定要有句,否则SendMobileMessage里面的所有List会使内存越来越高
                }
                catch (Exception e)
                {
                    PFDataHelper.WriteError(e);
                }
            }
        }
 private static bool IsDataRowMatchUpdate(DataRow row, SqlUpdateCollection update)
 {
     foreach (var i in update)
     {
         if (PFDataHelper.ObjectToString(i.Value.Value) == PFDataHelper.ObjectToString(row[i.Key]))
         {
         }
         else
         {
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 17
0
 public static void Crack()
 {
     try
     {
         //XlsExport.InitializeAsposeCells();
         Aspose.Cells.License l = new Aspose.Cells.License();
         //l.SetLicense(Path.Combine(HttpRuntime.AppDomainAppPath, "lib/Aid/License.lic"));
         l.SetLicense(Path.Combine(PFDataHelper.BaseDirectory, "lib/Aid/License.lic"));
     }
     catch (Exception e)
     {
         PFDataHelper.WriteError(e);
     }
 }
Exemplo n.º 18
0
        public static List <string> GetRecentCMonthList()
        {
            var now    = DateTime.Now;
            int idx    = 0;
            var result = new List <string>();

            //cmonthDGView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            for (int i = 0; i < 12; i++)
            {
                var cmonth = PFDataHelper.ObjectToDateString(now, "yyyy.MM");
                result.Add(cmonth);
                now = now.AddMonths(-1);
                idx++;
            }
            return(result);
        }
Exemplo n.º 19
0
 /// <summary>
 /// 绑定label
 /// </summary>
 /// <typeparam name="TComponent">支持textbox</typeparam>
 /// <param name="component"></param>
 /// <param name="modelConfig"></param>
 /// <param name="label"></param>
 private static void LabelBind(Label label, PFModelConfig modelConfig)
 {
     if (modelConfig != null)
     {
         if (PFDataHelper.StringIsNullOrWhiteSpace(label.Text) || label.Text == modelConfig.FieldName ||
             label.Text == "Label"   //Label控件的默认Text是Label
             )
         {
             label.Text = modelConfig.FieldText;
         }
         if (modelConfig.Required)
         {
             label.Text += "<span style='color:red'>*</span>";
         }
         label.Text += ":";
     }
 }
Exemplo n.º 20
0
        //private void SaveToLocal(string fileName)
        //{
        //    //测试xlsx下载后打不开的问题,暂保存到本地试试--benjamin todo
        //    var path = Path.Combine(PFDataHelper.BaseDirectory, "output", fileName);
        //    var directoryName = Path.GetDirectoryName(path);
        //    PFDataHelper.DeleteFile(path);
        //    PFDataHelper.CreateDirectory(directoryName);
        //    var tmpEx = _exporter as XlsxExport;
        //    if (tmpEx != null)
        //    {
        //        tmpEx.workbook.Save(path);
        //    }
        //}
        public void Download()
        {
            ////var tmpEx = _exporter as XlsxExport;
            //var tmpEx = _exporter as XlsxExport1048576;
            Aspose.Cells.Workbook book = null;
            if (_exporter is XlsxExport1048576)
            {
                book = (_exporter as XlsxExport1048576).workbook;
            }
            if (_exporter is XlsxExport)
            {
                book = (_exporter as XlsxExport).workbook;
            }
            if (book != null)
            {
                //if (PFDataHelper.IsDebug)
                //{
                //    var fileName = string.Format("test_{0}.{1}", _fileName, _suffix);
                //    var tmpFileName = Guid.NewGuid().ToString("N") + DateTime.Now.ToString("yyyyMMddHHmmss") + fileName;
                //    var path = Path.Combine(PFDataHelper.BaseDirectory, "TempFile", tmpFileName);
                //    var directoryName = Path.GetDirectoryName(path);
                //    PFDataHelper.CreateDirectory(directoryName);
                //    //book.Save(path, Aspose.Cells.FileFormatType.Xlsx);
                //    book.Save(path, Aspose.Cells.SaveFormat.Xlsx);
                //}
                PFDataHelper.DownloadExcel(HttpContext.Current, book, string.Format("{0}.{1}", _fileName, _suffix), PFDataHelper.GetConfigMapper().GetNetworkConfig().DownloadSpeed);
            }
            else
            {
                //SaveToLocal("excelPo.xlsx");

                if (_fileStream == null)
                {
                    _fileStream = _exporter.SaveAsStream();
                    //SaveToLocal("excelPoAfterSaveStream.xlsx");
                }
                if (_fileStream != null && _fileStream.Length > 0)
                {
                    //PFDataHelper.DownloadFile(HttpContext.Current, _fileStream, string.Format("{0}.{1}", _fileName, _suffix), 1024 * 1024 * 10);
                    PFDataHelper.DownloadFile(HttpContext.Current, _fileStream, string.Format("{0}.{1}", _fileName, _suffix), PFDataHelper.GetConfigMapper().GetNetworkConfig().DownloadSpeed);
                }
            }

            _exporter.Dispose();
        }
Exemplo n.º 21
0
        public void StartThread(object ps)
        {
            _lastBackupCDay = null;
            _lastBackupTime = null;
            while (_running == true)
            {
                try
                {
                    var cDay = CDay;
                    if (cDay == _lastBackupCDay)//该日已执行
                    {
                        Thread.Sleep(PFTaskHelper.CheckMessageInterval);
                        continue;
                    }
                    var now = DateTime.Now;

                    var backupDay = new DateTime(now.Year, now.Month, now.Day, BackupHour, BackupMinute, 0);
                    if (backupDay > now || FirstRunTime > now)//未到执行的时间
                    {
                        Thread.Sleep(PFTaskHelper.CheckMessageInterval);
                        continue;
                    }

                    _lastBackupCDay = cDay;
                    _nextRunTime    = backupDay.AddDays(1);

                    PFDataHelper.WriteLog(string.Format("任务{0}开始执行,日期为:{1}", HashId, cDay));
                    try
                    {
                        DoAction(cDay, _lastBackupTime, this);
                        _lastBackupTime = now;
                        PFDataHelper.WriteLog(string.Format("任务{0}执行完毕,日期为:{1}", HashId, cDay));
                    }
                    catch (Exception e)
                    {
                        PFDataHelper.WriteError(e);
                    }
                    GC.Collect();//一定要有句,否则SendMobileMessage里面的所有List会使内存越来越高
                }
                catch (Exception e)
                {
                    PFDataHelper.WriteError(e);
                }
            }
        }
Exemplo n.º 22
0
 public void Download()
 {
     // var _fileStream = SaveAsStream();
     if (_fileStream == null)
     {
         _fileStream = SaveAsStream();
     }
     if (PFDataHelper.StringIsNullOrWhiteSpace(_downloadFileName))
     {
         _downloadFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
     }
     if (_fileStream != null && _fileStream.Length > 0)
     {
         //PFDataHelper.DownloadFile(HttpContext.Current, _fileStream, string.Format("{0}.{1}", _fileName, _suffix), 1024 * 1024 * 10);
         PFDataHelper.DownloadFile(HttpContext.Current, _fileStream, string.Format("{0}.{1}", _downloadFileName, suffix), PFDataHelper.GetConfigMapper().GetNetworkConfig().DownloadSpeed);
     }
     Dispose();
 }
Exemplo n.º 23
0
        public virtual void FillData(int x, int y, string field, object value)//x列y行
        {
            FixXY(x, y);

            switch ((value ?? string.Empty).GetType().Name.ToLower())
            {
            case "int32":
            case "int64":
            case "decimal":
                BuildCell(PFDataHelper.ObjectToType <double>(value, 0).ToString());
                break;

            default:
                BuildCell(PFDataHelper.ObjectToString(value) ?? "");
                break;
            }

            //if (y > curRow) {

            //}
            //if (table.Rows.Count < y+1) {
            //    for (int i = table.Rows.Count - 1; i < y; i++) {
            //        if (i < 0) { continue; }
            //        builder.MoveToCell(0,i,table.Rows[i].Count-1,0);
            //        builder.EndRow();
            //    }
            //}
            //sheet.MoveToCell(y,x);

            ////if (!field.StartsWith("title_"))
            ////    cell.SetStyle(GetDataStyle());

            //switch ((value ?? string.Empty).GetType().Name.ToLower())
            //{
            //    case "int32":
            //    case "int64":
            //    case "decimal":
            //        sheet.Cells[y, x].PutValue(PFDataHelper.ObjectToType<double>(value, 0));
            //        break;
            //    default:
            //        sheet.Cells[y, x].PutValue(PFDataHelper.ObjectToString(value));
            //        break;
            //}
        }
Exemplo n.º 24
0
        public static List <Dictionary <string, object> > ExcelToDictList(Workbook workbook)
        {
            var list = new List <Dictionary <string, object> >();
            var cols = new List <string>();

            //if (Request.Files.Count < 1)
            //{
            //    return Json(JsonData.SetFault("文件为空"));
            //}
            //Workbook wb = new Workbook(Request.Files[0].InputStream);
            //if (wb == null)
            //{
            //    return Json(JsonData.SetFault("excel打开失败"));
            //}
            var sheet  = workbook.Worksheets[0];
            int rowCnt = sheet.Cells.Rows.Count;
            int colCnt = sheet.Cells.Columns.Count;

            for (int j = 0; j < colCnt; j++)
            {
                cols.Add(PFDataHelper.ObjectToString(sheet.Cells[0, j].Value));
            }
            var telephoneIdx = cols.IndexOf("telephone");

            if (telephoneIdx < 0)
            {
                return(null);
            }
            for (int i = 1; i < rowCnt; i++)
            {
                var item      = new Dictionary <string, object>();
                var telephone = PFDataHelper.ObjectToString(sheet.Cells[i, telephoneIdx].Value);
                if (PFDataHelper.StringIsNullOrWhiteSpace(telephone))//只要有一行为空,就返回
                {
                    return(list);
                }
                for (int j = 0; j < colCnt; j++)
                {
                    item[cols[j]] = sheet.Cells[i, j].Value;
                }
                list.Add(item);
            }
            return(list);
        }
Exemplo n.º 25
0
 public void Dispose()
 {
     if (_fileStream != null)
     {
         _fileStream.Dispose();
     }
     //2848 kbs
     //_data = null;
     //PFDataHelper.DisaposeObject<PagingResult>(_data);
     PFDataHelper.DisaposeObject(_data);
     _data = null;
     //if(_data!=null&&_data is PagingResult)
     //{
     //    (_data as PagingResult).Dispose();
     //    _data = null;
     //}
     PFDataHelper.GCCollect();
     //GC.Collect(); //2848-500=2329
 }
Exemplo n.º 26
0
        //	public  void BuildMqProducer(String message) {
        //        ConnectionFactory factory = new ConnectionFactory();
        //        factory.setHost("localhost");
        //        try (Connection connection = factory.newConnection();
        //             Channel channel = connection.createChannel()
        //                   ) {
        //          try {
        //            channel.queueDeclare(_mqConfig.getQueueName(), false, false, false, null);
        //            channel.basicPublish("", _mqConfig.getQueueName(), null, message.getBytes("UTF-8"));
        //	        String logMsg="\r\n [x][rabbitMq] queueName:"+_mqConfig.getQueueName()+" \r\n    Sent '" + message + "' \r\n";
        //	        WriteLog(logMsg);
        //          }catch(Exception e) {

        //          }
        //        } catch (IOException e1) {
        //			// TODO Auto-generated catch block
        //			e1.printStackTrace();
        //		} catch (TimeoutException e1) {
        //			// TODO Auto-generated catch block
        //			e1.printStackTrace();
        //		}

        //	}
        //	public  void BuildRocketMqProducer(String message) {

        ////		org.apache.rocketmq.client.producer.DefaultMQProducer producer = new org.apache.rocketmq.client.producer.DefaultMQProducer("test-group");
        ////        producer.setNamesrvAddr("localhost:9876");
        ////        producer.setInstanceName("rmq-instance");
        //		org.apache.rocketmq.client.producer.DefaultMQProducer producer = new org.apache.rocketmq.client.producer.DefaultMQProducer(_mqConfig.getGroupId());
        //        producer.setNamesrvAddr(_mqConfig.getNameSrvAddr());

        //        if(!PFDataHelper.StringIsNullOrWhiteSpace(_mqConfig.getInstanceName())) {
        //          producer.setInstanceName(_mqConfig.getInstanceName());
        //        }

        //        try {
        //          producer.start();
        //            org.apache.rocketmq.common.message.Message mmessage = new org.apache.rocketmq.common.message.Message(_mqConfig.getTopic(), _mqConfig.getTag(),message.getBytes());
        //            //System.out.println("生产者发送消息:"+JSON.toJSONString(user));
        //            org.apache.rocketmq.client.producer.SendResult sendResult= producer.send(mmessage);
        //            if (sendResult != null) {
        //              String logMsg="\r\n [x][rocketMq] topic:"+_mqConfig.getTopic()+" tag:"+_mqConfig.getTag()+" \r\n    Sent '" + message + "' \r\n";
        //              WriteLog(logMsg);
        //            }
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //        }
        //        producer.shutdown();
        //	}
        //public  void BuildAliMqProducer(String message) {

        //	//参考:D:\eclipse_workspace\IpaasTest\src\com\mq\simple\ProducerTest.java
        //	Properties properties = GetAliMqProperties() ;

        //       Producer producer = ONSFactory.createProducer(properties);

        //       // 在发送消息前,必须调用 start 方法来启动 Producer,只需调用一次即可
        //       producer.start();

        //       Message msg = new Message( //
        //              _mqConfig.getTopic(),
        //              _mqConfig.getTag(),// "*"
        //               message.getBytes()
        //               );
        //       // 设置代表消息的业务关键属性,请尽可能全局唯一。
        //       // 以方便您在无法正常收到消息情况下,可通过阿里云服务器管理控制台查询消息并补发
        //       // 注意:不设置也不会影响消息正常收发
        //       String msgKey="ORDERID_" + _mqConfig.getTopic()+ PFDataHelper.ObjectToDateString(Calendar.getInstance(), "yyyyMMddHHmmss");
        //       msg.setKey(msgKey);
        //       try {
        //           SendResult sendResult = producer.send(msg);
        //           // 同步发送消息,只要不抛异常就是成功
        //           if (sendResult != null) {
        //              String logMsg="\r\n [x][aliMq] topic:"+_mqConfig.getTopic()+" tag:"+_mqConfig.getTag()+" \r\n    Sent '" + message + "' \r\n";
        //              WriteLog(logMsg);
        //           }
        //       }
        //       catch (Exception e) {
        //           // 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理
        //           System.out.println("\r\n"+new Date() + " TIANGONG TEST -Send mq message failed. Topic is:" + msg.getTopic()+" \r\n");
        //           e.printStackTrace();
        //       }

        //       // 在应用退出前,销毁 Producer 对象
        //       // 注意:如果不销毁也没有问题
        //       producer.shutdown();
        //}

        //参考TestSendEmailAsync()
        public void BuildPFEmailMqProducer(String message)
        {
            var UserEmailUserName = PFDataHelper.SysEmailUserName;
            var UserEmailPwd      = PFDataHelper.SysEmailPwd;
            var UserEmailHostName = PFDataHelper.SysEmailHostName;

            ////生产方(使用User邮箱,也可以用系统邮箱吧)
            //var rt = PFDataHelper.SendEmailAsync(UserEmailUserName, UserEmailPwd, UserEmailHostName,
            //    new string[] { PFDataHelper.SysEmailUserName },
            //    _mqConfig.getTopic(), message);
            var rt = PFDataHelper.SendEmail(UserEmailUserName, UserEmailPwd, UserEmailHostName,
                                            new string[] { PFDataHelper.SysEmailUserName },
                                            "PFEmailMq_product_" + _mqConfig.getTopic(), message);


            //rt.Wait();//先不测试回调
            //var resultTitle = rt.Result.Subject;
            ////Assert.IsTrue(resultTitle == "PFEmailMq_consumer_" + producerEmailTitle);
        }
Exemplo n.º 27
0
        public object GetData(IController controller, HttpContext context)//控制器一定要传过来,不要用反射获得,否则Session等成员无法处理
        {
            dynamic data  = null;
            var     url   = context.Request.Form["dataAction"];
            JObject param = JsonConvert.DeserializeObject <dynamic>(context.Request.Form["dataParams"]);

            //var route = url.Replace("/api/", "").Split('/'); // route[0]=mms,route[1]=send,route[2]=get
            var route = url.Split('/');

            route = route.Skip(1).ToArray();

            var action = route.Length > 2 ? route[2] : "Get";

            if (action.IndexOf('?') > -1)
            {
                NameValueCollection urlParams = PFDataHelper.GetQueryStringParams(action);
                action = action.Split('?')[0];
                foreach (var i in urlParams.AllKeys)
                {
                    param[i] = urlParams[i];
                }
            }

            var methodInfo = controller.GetType().GetMethod(action);

            var parameters = new object[] { new PagingParameters().SetRequestData(param) };

            data = methodInfo.Invoke(controller, parameters);

            if (data.GetType() == typeof(ExpandoObject))
            {
                if ((data as ExpandoObject).Where(x => x.Key == "rows").Count() > 0)
                {
                    data = data.rows;
                }
            }

            if (data.Data is PagingResult)
            {
                return(data.Data);
            }
            return(data);
        }
        /// <summary>
        /// 适用场境,在测试库时,更新完数据后,验证数据是否有异常
        ///
        /// 常用方法:
        ///var update = new SqlUpdateCollection(new
        ///{
        ///    id = id,
        ///    agentno = agentno
        ///})
        ///.PrimaryKeyFields("id");
        ///PFSqlUpdateValidateHelper.TestUpdate("t_hyzl_orders", update, sqlExec);
        ///
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="update"></param>
        /// <param name="sql"></param>
        public static void TestUpdate(string tableName, SqlUpdateCollection update, ProcManager sql)
        {
            string updateSqlString = string.Format(@" select * from {0} {1}
                ", tableName, update.ToWhereSql());
            string totalSqlString  = string.Format(@" select count(*) from {0}
                ", tableName);

            //用set条件的字段做where来查总数,如果行数等于全表行数,那说明把整个表的值都更新了(where没有生效)
            var updateSet = new SqlWhereCollection();

            foreach (var i in update)
            {
                updateSet.Add(i.Key, i.Value.Value);
            }
            string updateSetTotalSqlString = string.Format(@" select count(*) from {0} {1}
                ", tableName, updateSet.ToSql());

            var updated  = sql.GetQueryTable(updateSqlString);
            var total    = PFDataHelper.ObjectToInt(sql.QuerySingleValue(totalSqlString));
            var setTotal = PFDataHelper.ObjectToInt(sql.QuerySingleValue(updateSetTotalSqlString));

            if (updated == null)
            {
                throw new Exception("更新后的数据全部丢失.异常");
            }
            if (total < 2)
            {
                throw new Exception("测试数据少于2条,这样不保险");
            }
            if (total == updated.Rows.Count)
            {
                throw new Exception("更新了整个表的数据,请确认是否缺少where条件.异常");
            }
            if (total == setTotal)
            {
                throw new Exception("更新了整个表的数据,请确认是否缺少where条件.异常");
            }
            AssertIsTrue(updated != null && updated.Rows.Count == 1);
            AssertIsTrue(total > 1);
            AssertIsTrue(IsDataRowMatchUpdate(updated.Rows[0], update));
            AssertIsTrue(setTotal >= updated.Rows.Count && setTotal < total);
        }
Exemplo n.º 29
0
        public void SaveToFileTest(string path)
        {
            var fileName = Path.GetFileName(path);

            //var dt = _dt;

            var dt = PFDataHelper.DataTableGroupBy(_dt,
                                                   PFDataHelper.MergeList(_pivotLeft, _pivotTop).ToArray(),
                                                   new PFKeyValueCollection <SummaryType>(_pivotValue.Select(a => new PFKeyValue <SummaryType> {
                Key = a, Value = SummaryType.Sum
            }))
                                                   );

            //var dt = PFDataHelper.DataTableGroupBy(_dt,
            //    _pivotTop.ToArray(),
            //    new PFKeyValueCollection<SummaryType>(_pivotTop.Select(a => new PFKeyValue<SummaryType> { Key = a, Value = SummaryType.Sum }))
            //    );

            StoreColumnCollection columns = null;

            var pagingResult = PFDataHelper.PagingStore(dt, new PagingParameters {
            },
                                                        columns,
                                                        false, null);
            var exporter = Exporter.Instance(pagingResult ?? new PagingResult(), new ExporterOption
            {
                FileType = "xlsx",//benjamin todo
                Scheme   = Exporter.FinancialScheme
                ,
                SheetTitle = fileName
                               //,
                               //SheetTitle = GetWordCMonth(cmonthff) + hr + fgsname
            }).FileName("总表"); //这里的下载名没用到
            var export = (exporter.GetExport() as XlsxExport);

            //var path = Path.Combine(PFDataHelper.BaseDirectory, "output", "excelPo.xlsx");
            var directoryName = Path.GetDirectoryName(path);

            PFDataHelper.DeleteFile(path);
            PFDataHelper.CreateDirectory(directoryName);
            export.workbook.Save(path);
        }
Exemplo n.º 30
0
        /// <summary>
        /// 控件绑定模型配置
        /// </summary>
        /// <param name="page"></param>
        /// <param name="modelName">实现IPFConfigMapper的类中定义</param>
        /// <param name="list"></param>
        public static void GridBindModel(DataGrid grid, string modelName)
        {
            var modelConfig = PFDataHelper.GetMultiModelConfig(modelName);

            if (modelConfig != null)
            {
                if (grid.Columns != null)
                {
                    foreach (DataGridColumn c in grid.Columns)
                    {
                        if (c is BoundColumn)
                        {
                            BoundColumn   tc     = c as BoundColumn;
                            PFModelConfig config = null;
                            if (modelConfig != null)
                            {
                                config = modelConfig[tc.DataField];
                            }
                            if (config != null && (PFDataHelper.StringIsNullOrWhiteSpace(tc.HeaderText) || tc.HeaderText == config.FieldName))
                            {
                                tc.HeaderText = config.FieldText;
                            }
                        }
                        else if (c is TemplateColumn)
                        {
                            TemplateColumn tc     = c as TemplateColumn;
                            PFModelConfig  config = null;
                            if (modelConfig != null)
                            {
                                config = modelConfig[tc.HeaderText];
                            }
                            if (config != null && (PFDataHelper.StringIsNullOrWhiteSpace(tc.HeaderText) || tc.HeaderText == config.FieldName))
                            {
                                tc.HeaderText = config.FieldText;
                            }
                        }
                    }
                }
            }
        }