示例#1
0
		public ImportExecutor(HttpPostedFile file, MCS.Web.WebControls.UploadProgressResult result)
		{
			this.file = file;
			this.result = result;
			this.log = new System.Text.StringBuilder(4096);
			this.status = new UploadProgressStatus();
		}
		protected void uploadProgress_DoPostedData(object sender, PostProgressDoPostedDataEventArgs eventArgs)
		{
			UploadProgressStatus status = new UploadProgressStatus();

			StringBuilder strB = new StringBuilder();

			status.CurrentStep = 1;
			status.MinStep = 0;
			status.MaxStep = eventArgs.Steps.Count;

			for (int i = status.MinStep; i < status.MaxStep; i++)
			{
				//处理订单,改变状态
				string orderID = (string)eventArgs.Steps[i];

				TestOrder order = Orders.Find(o => o.OrderID == orderID);

				if (order != null)
					order.Status = TestOrderStatus.Processed;

				status.CurrentStep = i;
				status.Response();

				if (strB.Length > 0)
					strB.Append("\n");

				strB.AppendFormat("Processed = {0}", (i + 1));
				Thread.Sleep(500);	//假装等待
			}

			status.CurrentStep = status.MaxStep;
			status.Response();

			eventArgs.Result.DataChanged = true;
			eventArgs.Result.CloseWindow = false;
			eventArgs.Result.ProcessLog = strB.ToString();
		}
		protected void uploadProgress_DoUploadProgress(HttpPostedFile file, UploadProgressResult result)
		{
			ExceptionHelper.FalseThrow(Path.GetExtension(file.FileName).ToLower() == ".xml", "'{0}'权限矩阵必须是xml电子表格", file.FileName);

			UploadProgressStatus status = new UploadProgressStatus();
			status.CurrentStep = 1;
			status.MinStep = 0;
			status.MaxStep = 20;

			WfMatrix.ImportExistMatrixFromExcelXml(file.InputStream, () =>
			{
				if (status.CurrentStep + 1 < status.MaxStep)
				{
					status.CurrentStep++;
				}
				status.Response();
			}, Request["processkey"]);

			status.MaxStep = 20;
			status.Response();

			string logInfo = string.Format("导入完成");
			PrepareResultInfo(result, logInfo);
		}
		protected void postControl_DoPostedData(object sender, MCS.Web.WebControls.PostProgressDoPostedDataEventArgs e)
		{
			string unitID = e.ClientExtraPostedData;

			var unit = DbUtil.GetEffectiveObject<AU.AdminUnit>(unitID);
			var status = new UploadProgressStatus();
			StringBuilder output = new StringBuilder();
			try
			{
				status.MinStep = 1;
				status.MaxStep = e.Steps.Count + 1;
				status.CurrentStep = 1;

				AU.AUSchemaRole currentRole = null;

				foreach (Dictionary<string, object> item in e.Steps)
				{
					currentRole = DoAction(unit, status, output, currentRole, item);

					status.Response();
					status.CurrentStep++;
				}
			}
			catch (Exception ex)
			{
				status.StatusText = ex.Message;
				output.AppendLine(ex.ToString());
				status.Response();
			}
			finally
			{
				output.AppendLine("结束");
				e.Result.CloseWindow = false;
				e.Result.ProcessLog = output.ToString();
			}
		}
		private static AU.AUSchemaRole DoAction(AU.AdminUnit unit, UploadProgressStatus status, StringBuilder output, AU.AUSchemaRole currentRole, Dictionary<string, object> item)
		{
			string roleID, schemaRoleID, userID;
			int type;

			try
			{
				roleID = (string)item["RoleID"];
				schemaRoleID = (string)item["SchemaRoleID"];
				userID = (string)item["UserID"];
				type = (int)item["Type"];

				if (currentRole == null || currentRole.ID != roleID)
					currentRole = DbUtil.GetEffectiveObject<AU.AUSchemaRole>(schemaRoleID);

				status.StatusText = string.Format("正在向角色{0}{1}用户{2}", roleID, type == 0 ? "添加" : "删除", userID);
				output.AppendLine(status.StatusText);


				if (type == 0)
				{
					AU.Operations.Facade.InstanceWithPermissions.AddUserToRole(new PC.SCUser() { ID = userID }, unit, currentRole);
				}
				else
				{
					AU.Operations.Facade.InstanceWithPermissions.RemoveUserFromRole(new PC.SCUser() { ID = userID, CodeName = "abc", Name = "abc" }, unit, currentRole);
				}
			}
			catch (Exception ex)
			{
				status.StatusText = ex.Message;
				output.AppendLine(ex.ToString());
			}
			return currentRole;
		}
		protected void uploadProgress_DoUploadProgress(HttpPostedFile file, UploadProgressResult result)
		{
			string tag = uploadProgress.Tag;

			const int baseRowIndex = 3;

			ExceptionHelper.FalseThrow(Path.GetExtension(file.FileName).ToLower() == ".xml",
				"'{0}' must be a xml file.", file.FileName);

			WorkbookNode workbook = new WorkbookNode();

			workbook.Load(file.InputStream);

			ExceptionHelper.FalseThrow(workbook.Worksheets.Contains("PC Tracker Form"),
				"The workbook must contains a 'PC Tracker Form' worksheet.");

			Dictionary<string, CellLocation> fieldLocations = BuildNameColumnDictionary(workbook);

			TableNode table = workbook.Worksheets["PC Tracker Form"].Table;

			StringBuilder strB = new StringBuilder();

			if (table.Rows.Count > 3)
			{
				int currentRowIndex = baseRowIndex;

				UploadProgressStatus status = new UploadProgressStatus();

				status.CurrentStep = 1;
				status.MinStep = 0;
				status.MaxStep = table.Rows.Count - currentRowIndex;

				int currentVirtualRow = baseRowIndex;

				for (int i = status.MinStep; i < status.MaxStep; i++)
				{
					currentRowIndex = baseRowIndex + i;

					RowNode row = table.Rows[currentRowIndex];

					if (row.Index > 0)
						currentVirtualRow = row.Index;
					else
						currentVirtualRow++;

					if (strB.Length > 0)
						strB.Append("\n");

					strB.AppendFormat("Processed={0}, Row={1}:", (i + 1), currentVirtualRow);

					foreach (KeyValuePair<string, CellLocation> kp in fieldLocations)
					{
						CellNode cell = row.GetCellByIndex(kp.Value.Column);

						strB.AppendFormat(";Name={0}, Value={1}", kp.Key, cell != null ? cell.Data.Value : string.Empty);
					}

					status.CurrentStep = i;
					status.Response();

					int ms = 1000;

					if (Request.Form["longProgress"] == "true")
						ms = 2000;

					Thread.Sleep(ms);	//假装等待
				}

				status.CurrentStep = status.MaxStep;
				status.Response();
			}

			result.DataChanged = true;
			result.CloseWindow = false;
			result.ProcessLog = strB.ToString();
		}
        /// <summary>
        /// 导入Excel Xml格式的文件
        /// </summary>
        /// <param name="stream"></param>
        private void ImportFromXml(Stream stream)
        {
            WorkbookNode workbook = new WorkbookNode();

            workbook.Load(stream);

            ExceptionHelper.FalseThrow(workbook.Worksheets.Contains("Matrix"),
                "The workbook must contains a 'Matrix' worksheet.");

            SOARole role = null;

            ServiceBrokerContext.Current.SaveContextStates();
            try
            {
                if (this.AppCodeName.IsNotEmpty() && this.RoleCodeName.IsNotEmpty())
                    role = new SOARole(this.AppCodeName + ":" + this.RoleCodeName);
                else
                    role = new SOARole(this.Definition) { ID = RoleID };

                role.Rows.Clear();

                NamedLocationCollection fieldLocations = workbook.Names.ToLocations();

                TableNode table = workbook.Worksheets["Matrix"].Table;

                int baseRowIndex = GetStartRow(fieldLocations);

                RowNode titleRow = table.GetRowByIndex(baseRowIndex);

                int currentRowIndex = table.Rows.IndexOf(titleRow) + 1;

                if (table.Rows.Count > currentRowIndex)
                {
                    UploadProgressStatus status = new UploadProgressStatus();

                    status.CurrentStep = 1;
                    status.MinStep = 0;
                    status.MaxStep = table.Rows.Count - currentRowIndex;

                    int currentVirtualRow = baseRowIndex;

                    for (int i = status.MinStep; i < status.MaxStep; i++)
                    {
                        RowNode row = table.Rows[currentRowIndex];

                        if (row.Index > 0)
                            currentVirtualRow = row.Index;
                        else
                            currentVirtualRow++;

                        GenerateMatrixRow(role, row, fieldLocations, i);

                        status.CurrentStep = i;
                        status.Response();

                        currentRowIndex++;
                    }

                    status.CurrentStep = status.MaxStep;
                    status.Response();
                }
                //插入记录
                SOARolePropertiesAdapter.Instance.Update(role);
            }
            finally
            {
                ServiceBrokerContext.Current.RestoreSavedStates();
            }
        }
        /// <summary>
        /// 上传属性定义
        /// </summary>
        /// <param name="file"></param>
        /// <param name="result"></param>
        protected void ImportSOARole_DoUploadProgress(HttpPostedFile file, UploadProgressResult result)
        {
            var fileType = Path.GetExtension(file.FileName).ToLower();

            if (string.Compare(fileType, ".xml", true) == 0)
            {
                StringBuilder logger = new StringBuilder();
                try
                {
                    CheckEditMode();

                    var xmlDoc = XDocument.Load(file.InputStream);
                    var wfProcesses = xmlDoc.Descendants("Root");
                    XElementFormatter formatter = new XElementFormatter();
                    UploadProgressStatus status = new UploadProgressStatus();

                    status.CurrentStep = 1;
                    status.MinStep = 0;
                    status.MaxStep = wfProcesses.Count() + 1;
                    logger.AppendFormat("开始导入角色属性定义...\n", file.FileName, status.MaxStep);

                    SOARole role = new SOARole { ID = this.DefinitionID };

                    SOARolePropertyDefinitionAdapter.Instance.Delete(role);

                    foreach (var wfProcess in wfProcesses)
                    {
                        SOARolePropertyDefinitionCollection rowsColl = (SOARolePropertyDefinitionCollection)formatter.Deserialize(wfProcess);

                        SOARolePropertyDefinitionAdapter.Instance.Update(role, rowsColl);

                        logger.Append("保存成功...\n");

                        status.CurrentStep++;
                        status.Response();
                    }
                    logger.AppendFormat("导入完成!", file.FileName);
                }
                catch (Exception ex)
                {
                    logger.AppendFormat("导入错误,{0},错误堆栈:{1}", ex.Message, ex.StackTrace);
                }

                result.DataChanged = true;
                result.CloseWindow = false;
                result.ProcessLog = logger.ToString();
            }
        }
        /// <summary>
        /// 上传矩阵的内容(行)
        /// </summary>
        /// <param name="file"></param>
        /// <param name="result"></param>
        protected void uploadProgress_DoUploadProgress(HttpPostedFile file, UploadProgressResult result)
        {
            CheckEditMode();

            var fileType = Path.GetExtension(file.FileName).ToLower();

            if (fileType != ".xml" && fileType != ".xlsx")
                throw new SystemSupportException("'{0}' 必须是 xml 或 xlsx 文件。");

            UploadProgressStatus status = new UploadProgressStatus();
            status.CurrentStep = 1;
            status.MinStep = 0;
            status.MaxStep = 20;

            Action notifier = () =>
            {
                if (status.CurrentStep + 1 < status.MaxStep)
                {
                    status.CurrentStep++;
                }
                status.Response();
            };

            if (fileType == ".xml")
            {
                ImportFromXml(file.InputStream);
            }
            else if (fileType == ".xlsx")
            {
                ImportFromExcel2007(file.InputStream, notifier);
            }

            result.DataChanged = true;
            result.CloseWindow = true;
        }
		protected void uploadProgress_DoUploadProgress(HttpPostedFile file, UploadProgressResult result)
		{
			ExceptionHelper.FalseThrow(Path.GetExtension(file.FileName).ToLower() == ".xml",
				"'{0}' must be a xml file.", file.FileName);

			WorkbookNode workbook = new WorkbookNode();

			workbook.Load(file.InputStream);

			ExceptionHelper.FalseThrow(workbook.Worksheets.Contains("Matrix"),
				"The workbook must contains a 'Matrix' worksheet.");

			NamedLocationCollection fieldLocations = workbook.Names.ToLocations();

			TableNode table = workbook.Worksheets["Matrix"].Table;

			StringBuilder strB = new StringBuilder();

			int baseRowIndex = GetStartRow(fieldLocations);

			RowNode titleRow = table.GetRowByIndex(baseRowIndex);

			int currentRowIndex = table.Rows.IndexOf(titleRow) + 1;

			if (table.Rows.Count > currentRowIndex)
			{
				UploadProgressStatus status = new UploadProgressStatus();

				status.CurrentStep = 1;
				status.MinStep = 0;
				status.MaxStep = table.Rows.Count - currentRowIndex;

				int currentVirtualRow = baseRowIndex;

				for (int i = status.MinStep; i < status.MaxStep; i++)
				{
					RowNode row = table.Rows[currentRowIndex];

					if (row.Index > 0)
						currentVirtualRow = row.Index;
					else
						currentVirtualRow++;

					if (strB.Length > 0)
						strB.Append("\n");

					strB.AppendFormat("Processed={0}, Row={1}:", (i + 1), currentVirtualRow);

					foreach (CellLocation location in fieldLocations)
					{
						CellNode cell = row.GetCellByIndex(location.Column);

						strB.AppendFormat(";Name={0}, Value={1}", location.Name, cell != null ? cell.Data.Value : string.Empty);
					}

					status.CurrentStep = i;
					status.Response();

					currentRowIndex++;
				}

				status.CurrentStep = status.MaxStep;
				status.Response();
			}

			result.DataChanged = true;
			result.CloseWindow = false;
			result.ProcessLog = strB.ToString();
		}
        protected void uploadProgress_DoUploadProgress(HttpPostedFile file, UploadProgressResult result)
        {
            var fileType = Path.GetExtension(file.FileName).ToLower();
            if (fileType != ".xml" && fileType != ".xlsx")
            {
                throw new Exception("'{0}' must be a xml or xlsx file.");
            }

            UploadProgressStatus status = new UploadProgressStatus();
            status.CurrentStep = 1;
            status.MinStep = 0;
            status.MaxStep = 20;
            Action notifier = () =>
            {
                if (status.CurrentStep + 1 < status.MaxStep)
                {
                    status.CurrentStep++;
                }
                status.Response();
            };

            if (fileType == ".xml")
            {
                WfMatrix.ImportExistMatrixFromExcelXml(file.InputStream, notifier, ProcessKey);
            }
            else if (fileType == ".xlsx")
            {
                WfMatrix.ImportExistMatrixFromExcel2007(file.InputStream, notifier, ProcessKey);
            }

            result.DataChanged = true;
            result.CloseWindow = true;
        }
        /// <summary>
        /// 解析上传的zip文件,返回解析日志
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private StringBuilder ParseZipFile(HttpPostedFile file)
        {
            StringBuilder logger = new StringBuilder();
            try
            {
                UploadProgressStatus status = new UploadProgressStatus();
                status.CurrentStep = 1;
                status.MinStep = 0;
                status.MaxStep = WfImportTemplateExecutor.MaxStep;

                WfImportTemplateExecutor executor = new WfImportTemplateExecutor(file.InputStream, info =>
                {
                    logger.Append(info);
                    status.CurrentStep++;
                    status.Response();
                });

                executor.Execute();
            }
            catch (Exception ex)
            {
                logger.AppendFormat("导入错误,{0},错误堆栈:{1}", ex.Message, ex.StackTrace);
            }

            return logger;
        }
        /// <summary>
        /// 解析上传的xml文件,返回解析日志
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private StringBuilder ParseXmlFile(HttpPostedFile file)
        {
            StringBuilder logger = new StringBuilder();
            try
            {
                var xmlDoc = XDocument.Load(file.InputStream);
                var wfProcesses = xmlDoc.Descendants("Root");
                XElementFormatter formatter = new XElementFormatter();
                UploadProgressStatus status = new UploadProgressStatus();

                status.CurrentStep = 1;
                status.MinStep = 1;
                status.MaxStep = wfProcesses.Count() + 1;
                logger.AppendFormat("开始导入,共发现{1}个流程模板...\n", file.FileName, status.MaxStep);

                foreach (var wfProcess in wfProcesses)
                {
                    IWfProcessDescriptor wfProcessDesc = (IWfProcessDescriptor)formatter.Deserialize(wfProcess);

                    using (TransactionScope tran = TransactionScopeFactory.Create())
                    {
                        WfProcessDescHelper.SaveWfProcess(wfProcessDesc);
                        tran.Complete();
                    }

                    logger.AppendFormat("	{0}保存成功...\n", wfProcessDesc.Key);

                    status.CurrentStep++;
                    status.Response();
                }
                logger.AppendFormat("导入完成!", file.FileName);
            }
            catch (Exception ex)
            {
                logger.AppendFormat("导入错误,{0},错误堆栈:{1}", ex.Message, ex.StackTrace);
            }

            return logger;
        }