コード例 #1
0
        private static Cache InitializeCacheInternal(string cacheId, CacheInitParams initParams,
                                                     bool isRemoveCache = true)
        {
            if (cacheId == null)
            {
                throw new ArgumentNullException("cacheId");
            }
            if (cacheId == string.Empty)
            {
                throw new ArgumentException("cacheId cannot be an empty string");
            }

            CacheMode mode = initParams.Mode;


            int maxTries = 2;

            try
            {
                CacheServerConfig config = null;

                if (mode != CacheMode.OutProc)
                {
                    do
                    {
                        try
                        {
                            config = DirectoryUtil.GetCacheDom(cacheId, mode == CacheMode.InProc);
                        }


                        catch (Exception ex)
                        {
                            if (mode == CacheMode.Default)
                            {
                                mode = CacheMode.OutProc;
                            }
                            else
                            {
                                throw ex;
                            }
                        }

                        if (config != null)
                        {
                            if (config.CacheType.ToLower().Equals("clustered-cache"))
                            {
                                throw new Exception("Cluster cache cannot be initialized in In-Proc mode.");
                            }

                            switch (mode)
                            {
                            case CacheMode.InProc:
                                config.InProc = true;
                                break;

                            case CacheMode.OutProc:
                                config.InProc = false;
                                break;
                            }
                        }

                        break;
                    } while (maxTries > 0);
                }

                lock (typeof(NCache))
                {
                    Cache primaryCache = null;

                    lock (s_webCaches)
                    {
                        if (!s_webCaches.Contains(cacheId))
                        {
                            CacheImplBase cacheImpl = null;

                            if (config != null && config.InProc)
                            {
                                Alachisoft.NCache.Caching.Cache ncache = null;
                                Cache cache = null;
                                maxTries = 2;

                                do
                                {
                                    CacheConfig cacheConfig = CacheConfig.FromDom(config);

                                    if (Caching.APILogging.DebugAPIConfiguraions.LoggingEnabled)
                                    {
                                        cache = new WrapperCache(new Cache(null, cacheConfig));
                                    }
                                    else
                                    {
                                        cache = new Cache(null, cacheConfig);
                                    }


                                    ncache = CacheFactory.CreateFromPropertyString(cacheConfig.PropertyString, config,
                                                                                   false, false);


                                    cacheImpl       = new InprocCache(ncache, cacheConfig, cache);
                                    cache.CacheImpl = cacheImpl;

                                    if (primaryCache == null)
                                    {
                                        primaryCache = cache;
                                    }

                                    else
                                    {
                                        primaryCache.AddSecondaryInprocInstance(cache);
                                    }

                                    break;
                                } while (maxTries > 0);
                            }
                            else
                            {
                                maxTries = 2;
                                do
                                {
                                    try
                                    {
                                        PerfStatsCollector2 perfStatsCollector =
                                            new PerfStatsCollector2(cacheId, false);

                                        if (Caching.APILogging.DebugAPIConfiguraions.LoggingEnabled)
                                        {
                                            primaryCache =
                                                new WrapperCache(new Cache(null, cacheId, perfStatsCollector));
                                        }
                                        else
                                        {
                                            primaryCache = new Cache(null, cacheId, perfStatsCollector);
                                        }
                                        cacheImpl = new RemoteCache(cacheId, primaryCache, initParams,
                                                                    perfStatsCollector);

                                        perfStatsCollector.InitializePerfCounters(false);

                                        primaryCache.CacheImpl = cacheImpl;

                                        break;
                                    }


                                    catch (OperationNotSupportedException ex)
                                    {
                                        throw ex;
                                    }
                                } while (maxTries > 0);
                            }

                            if (primaryCache != null)
                            {
                                s_webCaches.AddCache(cacheId, primaryCache);
                            }
                        }
                        else
                        {
                            lock (s_webCaches.GetCache(cacheId))
                            {
                                primaryCache = s_webCaches.GetCache(cacheId) as Cache;

                                primaryCache.AddRef();
                            }
                        }
                    }

                    lock (s_webCache)
                    {
                        if (s_webCache.CacheImpl == null)
                        {
                            primaryCache.ExceptionsEnabled = ExceptionsEnabled;
                            s_webCache = primaryCache;
                        }
                    }

                    return(primaryCache);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #2
0
        /// <summary>
        /// 根据配置导出SQL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGenerateSQL_Click(object sender, EventArgs e)
        {
            if (projectInfo != null)
            {
                if (string.IsNullOrEmpty(projectInfo.OutputPath))
                {
                    MessageDxUtil.ShowError("请在项目菜单中配置导出脚本路径");
                    return;
                }

                if (!DirectoryUtil.IsExistDirectory(projectInfo.OutputPath))
                {
                    MessageDxUtil.ShowError(string.Format("配置的路径{0}在系统中不存在,请在项目菜单中配置导出脚本路径", projectInfo.OutputPath));
                    return;
                }

                // 操控进度条
                //var progressBar = (this.MdiParent as MainForm).progressBar;
                //progressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                if (FileUtil.IsExistFile(projectInfo.OutputPath + "\\Dict.sql"))
                {
                    FileUtil.DeleteFile(projectInfo.OutputPath + "\\Dict.sql");
                }

                FileUtil.CreateFile(projectInfo.OutputPath + "\\Dict.sql");

                #region 处理每个Table脚本
                XmlHelper           xmldicthelper      = new XmlHelper(@"XML\dict.xml");
                XmlNodeList         xmlNodeLst2        = xmldicthelper.Read("datatype/dataitem");
                List <DictInfo>     dictTypeInfoList2  = new List <DictInfo>();
                List <DictDataInfo> dictDetailInfoList = new List <DictDataInfo>();
                foreach (XmlNode xn1 in xmlNodeLst2)
                {
                    DictInfo dictInfo = new DictInfo();
                    // 将节点转换为元素,便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;

                    // 得到DataTypeInfo节点的所有子节点
                    XmlNodeList xnl0 = xe.ChildNodes;
                    dictInfo.Id     = Convert.ToInt32(xnl0.Item(0).InnerText);
                    dictInfo.Pid    = Convert.ToInt32(xnl0.Item(1).InnerText);
                    dictInfo.Name   = xnl0.Item(2).InnerText;
                    dictInfo.Remark = xnl0.Item(3).InnerText;

                    if (!string.IsNullOrEmpty(xnl0.Item(4).InnerXml))
                    {
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //新建对象
                        doc.LoadXml("<tmp>" + xnl0.Item(4).InnerXml + "</tmp>");   //符合xml格式的字符串
                        var nodes = doc.DocumentElement.ChildNodes;
                        foreach (var node in nodes)
                        {
                            DictDataInfo dicdetailInfo = new DictDataInfo();
                            var          dNode         = ((XmlElement)node).ChildNodes;
                            dicdetailInfo.DicttypeValue = dNode.Item(0).InnerText.ToInt32();
                            dicdetailInfo.Name          = dNode.Item(1).InnerText;
                            dicdetailInfo.Seq           = dNode.Item(2).InnerText;
                            dicdetailInfo.Remark        = dNode.Item(3).InnerText;
                            dicdetailInfo.DicttypeId    = dictInfo.Id;

                            dictDetailInfoList.Add(dicdetailInfo);
                        }
                    }

                    dictTypeInfoList2.Add(dictInfo);
                }

                // T_Basic_DictType
                // T_Basic_DictData
                FileUtil.AppendText(projectInfo.OutputPath + "\\Dict.sql", JCodes.Framework.Common.Proj.SqlOperate.initDictTypeInfo(projectInfo.DbType, tableGroup["DictType"] + "DictType", "数据字典类型", dictTypeInfoList2), Encoding.Default);

                //progressBar.EditValue = 50;

                FileUtil.AppendText(projectInfo.OutputPath + "\\Dict.sql", JCodes.Framework.Common.Proj.SqlOperate.initDictDataInfo(projectInfo.DbType, tableGroup["DictData"] + "DictData", "数据字典明细", dictDetailInfoList), Encoding.Default);

                //progressBar.EditValue = 100;
                #endregion

                MessageDxUtil.ShowTips("生成脚本成功");
                //progressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }
        }
コード例 #3
0
        private void btnModField_Click(object sender, EventArgs e)
        {
            StdFieldInfo aftermodstdFieldInfo = new StdFieldInfo();

            aftermodstdFieldInfo.Gid         = _beforemodstdFieldInfo.Gid;
            aftermodstdFieldInfo.Name        = txtName.Text.Trim();
            aftermodstdFieldInfo.ChineseName = txtChineseName.Text.Trim();
            aftermodstdFieldInfo.DataType    = lueFieldType.EditValue.ToString();

            StringBuilder content = new StringBuilder();

            #region 检查一下字段是否存在
            foreach (StdFieldInfo dataTypeInfo in _lstDataTypeInfo)
            {
                if (string.IsNullOrEmpty(dataTypeInfo.Gid))
                {
                    continue;
                }

                // 与别的字段重名,不允许修改
                if (string.Equals(aftermodstdFieldInfo.Name, dataTypeInfo.Name) && !string.Equals(_beforemodstdFieldInfo.Name, dataTypeInfo.Name))
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_ERR, "该标准字段已存在,不允许修改", typeof(FrmModField));
                    MessageDxUtil.ShowWarning("该标准字段已存在,不允许修改");
                    return;
                }
            }
            #endregion

            #region 取project.xml 判断当前数据库
            XmlHelper   xmlprojectthelper = new XmlHelper(@"XML\project.xml");
            XmlNodeList xmlprejectNodeLst = xmlprojectthelper.Read("datatype");

            if (xmlprejectNodeLst.Count == 0)
            {
                return;
            }

            XmlNode xn1project = xmlprejectNodeLst[0];

            // 将节点转换为元素,便于得到节点的属性值
            XmlElement xeproject = (XmlElement)xn1project;

            // 得到DataTypeInfo节点的所有子节点
            XmlNodeList xnl0project = xeproject.ChildNodes;

            string dbType = xnl0project.Item(4).InnerText;
            #endregion

            #region 生成SQL文件
            if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name) || !string.Equals(_beforemodstdFieldInfo.DataType, aftermodstdFieldInfo.DataType))
            {
                // SQLServer 修改字段   exec sp_rename '表名.列名','新列名' -- 注意,单引号不可省略。
                // SQLServer 修改字段类型 alter table 表名 alter column 字段名 type not null
                // MySql 修改字段 ALTER TABLE  表名 CHANGE  旧字段名 新字段名 字段类型
                // MySql 修改字段类型 ALTER TABLE  表名 CHANGE  字段名 字段名 新字段类型
                string saveFile = FileDialogHelper.SaveText("更新字段.sql", "C:\\myares\\");
                if (!string.IsNullOrEmpty(saveFile))
                {
                    String[] sqltablefileNames = DirectoryUtil.GetFileNames(@"XML\", "*.table", true);
                    foreach (string tablefileName in sqltablefileNames)
                    {
                        LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("开始变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                        XmlHelper xmltablehelper = new XmlHelper(tablefileName);
                        try
                        {
                            XmlNodeList xmlNodeLst = xmltablehelper.Read("datatype/fieldsinfo");
                            for (Int32 i = 0; i < xmlNodeLst.Count; i++)
                            {
                                // 字段变更
                                if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name) && !string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                                {
                                    #region 读取Table.xml 配置信息

                                    XmlHelper   xmltableshelper            = new XmlHelper(@"XML\tables.xml");
                                    XmlNodeList xmlNodeLst22               = xmltableshelper.Read("datatype/tabletype");
                                    Dictionary <string, string> guidGroup  = new Dictionary <string, string>();
                                    Dictionary <string, string> tableGroup = new Dictionary <string, string>();
                                    guidGroup.Clear();
                                    tableGroup.Clear();
                                    foreach (XmlNode xn1 in xmlNodeLst22)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;

                                        // 获取字符串中的英文字母 [a-zA-Z]+
                                        string GroupEnglishName = CRegex.GetText(xe.GetAttribute("name").ToString(), "[a-zA-Z]+", 0);

                                        guidGroup.Add(xe.GetAttribute("gid").ToString(), string.Format("{0}{1}_", Const.TablePre, GroupEnglishName));
                                    }

                                    XmlNodeList xmlNodeLst2 = xmltableshelper.Read("datatype/dataitem");
                                    foreach (XmlNode xn1 in xmlNodeLst2)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;
                                        // 得到Type和ISBN两个属性的属性值

                                        // 得到ConstantInfo节点的所有子节点
                                        XmlNodeList xnl0 = xe.ChildNodes;

                                        tableGroup.Add(xnl0.Item(0).InnerText, guidGroup[xnl0.Item(3).InnerText]);
                                    }
                                    #endregion

                                    string tableName = xmltablehelper.Read("datatype/basicinfo/item/name").Item(0).InnerText;
                                    content.Append(string.Format("exec sp_rename '{0}.{1}','{2}';\r\nGO\r\n\r\n", tableGroup[tableName] + tableName, _beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name));
                                }

                                if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name) && !string.Equals(_beforemodstdFieldInfo.DataType, aftermodstdFieldInfo.DataType))
                                {
                                    #region 先读取datatype.xml 在读取defaulttype.xml 然后Linq 查询保存到数据字典dic中
                                    XmlHelper           xmldatatypehelper  = new XmlHelper(@"XML\datatype.xml");
                                    XmlNodeList         xmldatatypeNodeLst = xmldatatypehelper.Read("datatype");
                                    List <DataTypeInfo> dataTypeInfoList   = new List <DataTypeInfo>();
                                    foreach (XmlNode xn1 in xmldatatypeNodeLst)
                                    {
                                        DataTypeInfo dataTypeInfo = new DataTypeInfo();
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;
                                        // 得到Type和ISBN两个属性的属性值
                                        dataTypeInfo.Gid = xe.GetAttribute("gid").ToString();

                                        // 得到DataTypeInfo节点的所有子节点
                                        XmlNodeList xnl0 = xe.ChildNodes;
                                        dataTypeInfo.Name      = xnl0.Item(0).InnerText;
                                        dataTypeInfo.StdType   = xnl0.Item(2).InnerText;
                                        dataTypeInfo.Length    = xnl0.Item(3).InnerText;
                                        dataTypeInfo.Precision = xnl0.Item(4).InnerText;

                                        dataTypeInfoList.Add(dataTypeInfo);
                                    }

                                    XmlHelper   defaulttypexmlHelper  = new XmlHelper(@"XML\defaulttype.xml");
                                    XmlNodeList defaulttypexmlNodeLst = defaulttypexmlHelper.Read("datatype");
                                    Dictionary <string, string> dict  = new Dictionary <string, string>();
                                    foreach (var dataTypeInfo in dataTypeInfoList)
                                    {
                                        foreach (XmlNode xn1 in defaulttypexmlNodeLst)
                                        {
                                            // 将节点转换为元素,便于得到节点的属性值
                                            XmlElement xe = (XmlElement)xn1;
                                            // 得到DataTypeInfo节点的所有子节点
                                            XmlNodeList xnl0  = xe.ChildNodes;
                                            string      value = string.Empty;
                                            if (dbType == "Oracle")
                                            {
                                                value = xnl0.Item(2).InnerText;
                                            }
                                            else if (dbType == "Mysql")
                                            {
                                                value = xnl0.Item(3).InnerText;
                                            }
                                            else if (dbType == "DB2")
                                            {
                                                value = xnl0.Item(4).InnerText;
                                            }
                                            else if (dbType == "SqlServer")
                                            {
                                                value = xnl0.Item(5).InnerText;
                                            }
                                            else if (dbType == "Sqlite")
                                            {
                                                value = xnl0.Item(6).InnerText;
                                            }
                                            else if (dbType == "Access")
                                            {
                                                value = xnl0.Item(7).InnerText;
                                            }

                                            // 找到匹配记录
                                            if (dataTypeInfo.StdType == xnl0.Item(0).InnerText)
                                            {
                                                if (value.Contains("$L"))
                                                {
                                                    if (String.Empty == dataTypeInfo.Length)
                                                    {
                                                        value = value.Replace("$L", "0");
                                                    }
                                                    else
                                                    {
                                                        value = value.Replace("$L", dataTypeInfo.Length);
                                                    }
                                                }
                                                if (value.Contains("$P"))
                                                {
                                                    if (String.Empty == dataTypeInfo.Precision)
                                                    {
                                                        value = value.Replace("$P", "0");
                                                    }
                                                    else
                                                    {
                                                        value = value.Replace("$P", dataTypeInfo.Precision);
                                                    }
                                                }
                                                dict.Add(dataTypeInfo.Name, value);
                                            }
                                        }
                                    }
                                    #endregion

                                    #region 读取Table.xml 配置信息

                                    XmlHelper   xmltableshelper            = new XmlHelper(@"XML\tables.xml");
                                    XmlNodeList xmlNodeLst22               = xmltableshelper.Read("datatype/tabletype");
                                    Dictionary <string, string> guidGroup  = new Dictionary <string, string>();
                                    Dictionary <string, string> tableGroup = new Dictionary <string, string>();
                                    guidGroup.Clear();
                                    tableGroup.Clear();
                                    foreach (XmlNode xn1 in xmlNodeLst22)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;

                                        // 获取字符串中的英文字母 [a-zA-Z]+
                                        string GroupEnglishName = CRegex.GetText(xe.GetAttribute("name").ToString(), "[a-zA-Z]+", 0);

                                        guidGroup.Add(xe.GetAttribute("gid").ToString(), string.Format("{0}{1}_", Const.TablePre, GroupEnglishName));
                                    }

                                    XmlNodeList xmlNodeLst2 = xmltableshelper.Read("datatype/dataitem");
                                    foreach (XmlNode xn1 in xmlNodeLst2)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;
                                        // 得到Type和ISBN两个属性的属性值

                                        // 得到ConstantInfo节点的所有子节点
                                        XmlNodeList xnl0 = xe.ChildNodes;

                                        tableGroup.Add(xnl0.Item(0).InnerText, guidGroup[xnl0.Item(3).InnerText]);
                                    }
                                    #endregion

                                    string tableName = xmltablehelper.Read("datatype/basicinfo/item/name").Item(0).InnerText;
                                    content.Append(string.Format("alter table {0} alter column {1} {2};\r\nGO\r\n\r\n", tableGroup[tableName] + tableName, aftermodstdFieldInfo.Name, dict[aftermodstdFieldInfo.DataType]));
                                }
                            }
                            xmltablehelper.Save(false);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                            MessageDxUtil.ShowError(ex.Message);
                        }
                        LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("结束变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                    }

                    FileUtil.WriteText(saveFile, content.ToString(), Encoding.UTF8);

                    if (MessageDxUtil.ShowYesNoAndTips("保存成功,是否打开文件?") == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveFile);
                    }
                }
            }
            #endregion

            #region 修改*.table 字段
            String[] tablefileNames = DirectoryUtil.GetFileNames(@"XML\", "*.table", true);
            foreach (string tablefileName in tablefileNames)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("开始变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                XmlHelper xmltablehelper = new XmlHelper(tablefileName);
                try
                {
                    #region 更新数据
                    if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                    {
                        XmlNodeList xmlNodeLst = xmltablehelper.Read("datatype/fieldsinfo");
                        for (Int32 i = 0; i < xmlNodeLst.Count; i++)
                        {
                            if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name))
                            {
                                xmlNodeLst[i].ChildNodes.Item(0).InnerText = aftermodstdFieldInfo.Name;
                            }
                        }
                    }
                    xmltablehelper.Save(false);
                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                    MessageDxUtil.ShowError(ex.Message);
                }
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("结束变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
            }
            #endregion

            #region 修改*.entity 字段
            String[] entityfileNames = DirectoryUtil.GetFileNames(@"XML\", "*.entity", true);
            foreach (string entityfileName in entityfileNames)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("开始变更{0}文件中变更前字段为{1}", entityfileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                XmlHelper xmlentityhelper = new XmlHelper(entityfileName);
                try
                {
                    #region 更新数据
                    if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                    {
                        XmlNodeList xmlNodeLst = xmlentityhelper.Read("datatype/fieldsinfo");
                        for (Int32 i = 0; i < xmlNodeLst.Count; i++)
                        {
                            if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name))
                            {
                                xmlNodeLst[i].ChildNodes.Item(0).InnerText = aftermodstdFieldInfo.Name;
                            }
                        }
                    }
                    xmlentityhelper.Save(false);
                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                    MessageDxUtil.ShowError(ex.Message);
                }
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("结束变更{0}文件中变更前字段为{1}", entityfileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
            }
            #endregion

            #region 修改stdfield.xml文件
            XmlHelper xmlstdfieldhelper = new XmlHelper(@"XML\stdfield.xml");
            try
            {
                #region 更新数据
                if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                {
                    xmlstdfieldhelper.Replace(string.Format("datatype/dataitem/item[@gid=\"{0}\"]/name", aftermodstdFieldInfo.Gid), aftermodstdFieldInfo.Name);
                }
                if (!string.Equals(_beforemodstdFieldInfo.ChineseName, aftermodstdFieldInfo.ChineseName))
                {
                    xmlstdfieldhelper.Replace(string.Format("datatype/dataitem/item[@gid=\"{0}\"]/chineseName", aftermodstdFieldInfo.Gid), aftermodstdFieldInfo.ChineseName);
                }
                if (!string.Equals(_beforemodstdFieldInfo.DataType, aftermodstdFieldInfo.DataType))
                {
                    xmlstdfieldhelper.Replace(string.Format("datatype/dataitem/item[@gid=\"{0}\"]/datatype", aftermodstdFieldInfo.Gid), aftermodstdFieldInfo.DataType);
                }
                xmlstdfieldhelper.Save(false);
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                MessageDxUtil.ShowError(ex.Message);
            }
            #endregion



            this.Close();
        }
コード例 #4
0
ファイル: AssetBundleUtil.cs プロジェクト: 404Lcc/Lcc
        public static void BuildAssetBundle(AssetBundleSetting assetBundleSetting)
        {
            Dictionary <string, AssetBundleData>     assetBundleDataDict     = new Dictionary <string, AssetBundleData>();
            Dictionary <string, AssetBundleRuleType> assetBundleRuleTypeDict = new Dictionary <string, AssetBundleRuleType>();
            string path = PathUtil.GetPath(PathType.DataPath, assetBundleSetting.outputPath, GetPlatformForAssetBundle(EditorUserBuildSettings.activeBuildTarget));

            foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List <DirectoryInfo>()))
            {
                item.Delete();
            }
            foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List <FileInfo>()))
            {
                item.Delete();
            }
            List <AssetBundleBuild> assetBundleBuildList = new List <AssetBundleBuild>();

            foreach (AssetBundleRule item in assetBundleSetting.assetBundleRuleList)
            {
                if (item.assetBundleRuleType == AssetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List <FileInfo>());
                    if (fileInfos.Length == 0)
                    {
                        continue;
                    }
                    List <FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        assetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("Assets")).Replace("\\", "/"), AssetBundleRuleType.File);
                    }
                }
                if (item.assetBundleRuleType == AssetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List <DirectoryInfo>());
                    if (directoryInfos.Length == 0)
                    {
                        continue;
                    }
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        if (fileInfos.Length == 0)
                        {
                            continue;
                        }
                        List <FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                        foreach (FileInfo fileInfo in fileInfoList)
                        {
                            assetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("Assets")).Replace("\\", "/"), AssetBundleRuleType.Directory);
                        }
                    }
                }
            }
            foreach (AssetBundleData item in assetBundleSetting.assetBundleDataList)
            {
                assetBundleBuildList.Add(new AssetBundleBuild()
                {
                    assetBundleName = item.assetBundleName,
                    assetNames      = item.assetNames,
                });
            }
            AssetBundleManifest assetBundleManifest = BuildPipeline.BuildAssetBundles(path, assetBundleBuildList.ToArray(), BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);

            foreach (AssetBundleData item in assetBundleSetting.assetBundleDataList)
            {
                item.assetBundleHash = assetBundleManifest.GetAssetBundleHash(item.assetBundleName).ToString();
                BuildPipeline.GetCRCForAssetBundle($"{path}/{item.assetBundleName}", out item.assetBundleCRC);
                item.fileSize = FileUtil.GetFileSize($"{path}/{item.assetBundleName}");
                assetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.assetBundleName), item);
            }
            AssetBundleConfig assetBundleConfig = new AssetBundleConfig(assetBundleSetting.buildId, assetBundleDataDict, assetBundleRuleTypeDict);

            FileUtil.SaveAsset(path, "AssetBundleConfig.json", JsonUtil.ToJson(assetBundleConfig));
            if (assetBundleSetting.isCopyStreamingAssets)
            {
                string copyPath = PathUtil.GetPath(PathType.StreamingAssetsPath, "Res", GetPlatformForAssetBundle(EditorUserBuildSettings.activeBuildTarget));
                foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(copyPath), new List <DirectoryInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(copyPath), new List <FileInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List <FileInfo>()))
                {
                    if (Path.GetExtension(item.Name) == ".meta")
                    {
                        continue;
                    }
                    File.Copy(item.FullName, $"{PathUtil.GetPath(PathType.StreamingAssetsPath, "Res", GetPlatformForAssetBundle(EditorUserBuildSettings.activeBuildTarget))}/{item.Name}");
                }
            }
            AssetDatabase.Refresh();
        }
コード例 #5
0
 public void TestInitialize()
 {
     DirectoryUtil.CreateDirectoryIfNotExists(this.resultPath);
     DirectoryUtil.ClearDirectory(this.resultPath);
 }
コード例 #6
0
ファイル: Log4net.cs プロジェクト: yongwuhou/NCache
        /// <summary>
        /// intitializes Known name based log files
        /// </summary>
        /// <param name="loggerName">Enum of Known loggerNames</param>
        /// <param name="cacheName">cacheName if Clientcache logging, if not ClientCache, use the other override</param>
        public static void Initialize(NCacheLog.LoggerNames loggerNameEnum, string cacheName)
        {
            lock (lockObj)
            {
                MemoryStream logStream = new MemoryStream(log4netXML);
                log4net.Config.XmlConfigurator.Configure(LogRepository, logStream);

                string logName = loggerNameEnum.ToString();

                string filename = logName;
                if (loggerNameEnum == NCacheLog.LoggerNames.ClientLogs && (cacheName != null && cacheName.Length > 0))
                {
                    filename = filename + "." + cacheName + "." + System.Diagnostics.Process.GetCurrentProcess().Id;

                    logName = cacheName + System.Diagnostics.Process.GetCurrentProcess().Id;
                }
                else
                {
                    if (cacheName != null && cacheName.Length > 0)
                    {
                        filename = cacheName;
                    }
                }

                //If Logger is already present, can either be a cache or Client
                if (LoggingInformation.GetLoggerName(logName) != null)
                {
                    if (loggerNameEnum == NCacheLog.LoggerNames.ClientLogs)
                    {
                        return; // clientLogs alread initiated
                    }
                    else
                    {
                        if (LoggingInformation.GetStaticLoggerName(logName) != null)
                        {
                            return; // Log already initiated
                        }
                        else
                        {
                            logName = logName + DateTime.Now;
                        }
                    }
                }
                else
                {
                    if (loggerNameEnum != NCacheLog.LoggerNames.ClientLogs)
                    {
                        if (LoggingInformation.GetStaticLoggerName(logName) != null)
                        {
                            return; // Log already initiated
                        }
                        else
                        {
                            logName = logName + DateTime.Now;
                        }
                    }
                }

                filename = filename + "." +
                           Environment.MachineName.ToLower() + "." +
                           DateTime.Now.ToString("dd-MM-yy HH-mm-ss") + @".logs.txt";

                string filepath = "";
                if (!DirectoryUtil.SearchGlobalDirectory("log-files", false, out filepath))
                {
                    try
                    {
                        DirectoryUtil.SearchLocalDirectory("log-files", true, out filepath);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Unable to initialize the log file", ex);
                    }
                }

                try
                {
                    filepath = Path.Combine(filepath, loggerNameEnum.ToString());
                    if (!Directory.Exists(filepath))
                    {
                        Directory.CreateDirectory(filepath);
                    }

                    filepath = Path.Combine(filepath, filename);

                    LoggingInformation.cacheLogger.Add(logName, logName);
                    if (loggerNameEnum != NCacheLog.LoggerNames.ClientLogs)
                    {
                        LoggingInformation.staticCacheLogger.Add(loggerNameEnum.ToString(), logName);
                    }

                    SetLevel(logName, NCacheLog.Level.OFF.ToString());
                    AddAppender(logName, CreateBufferAppender(logName, filepath));
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
コード例 #7
0
        public override bool WriteData(IEnumerable <DataTable> tables, bool deleteBefore = false)
        {
            this.ValidateAndThrow();

            string       lastFileName = "";
            string       fileName     = "";
            bool         isNewFile    = true;
            StreamWriter writer       = null;

            foreach (DataTable table in tables)
            {
                if (writer == null || lastFileName != this.FileName)
                {
                    fileName = this.FileName;

                    if (string.IsNullOrEmpty(fileName))
                    {
                        fileName = table.TableName;
                    }

                    if (string.IsNullOrEmpty(fileName))
                    {
                        return(false);
                    }

                    DirectoryUtil.CreateDirectoryIfNotExists(Path.GetDirectoryName(fileName));

                    if (deleteBefore)
                    {
                        FileUtil.DeleteFileIfExists(fileName);
                    }

                    isNewFile = this.IsNewFile(fileName);

                    if (writer != null)
                    {
                        writer.Flush();
                        writer.Close();
                        writer.Dispose();
                    }

                    if (!string.IsNullOrEmpty(fileName))
                    {
                        writer = new StreamWriter(fileName, !isNewFile, this.Encoding);
                    }
                    else if (this.DataStream != null)
                    {
                        writer = new StreamWriter(this.DataStream, this.Encoding);
                    }

                    lastFileName = fileName;
                }

                writer.NewLine = this.recordSeperator;

                var lines = this.WriteFormatter.Format(table) as IEnumerable <string>;

                int writtenRows = 0;
                int rowIdx      = 0;

                if (lines != null)
                {
                    foreach (var line in lines)
                    {
                        if (!isNewFile && rowIdx == 0)
                        {
                            // skip header when it is no new fileName
                            rowIdx++;
                            continue;
                        }

                        writer.WriteLine(line);

                        if (writtenRows % 100 == 0)
                        {
                            writer.Flush();
                        }

                        writtenRows++;
                        rowIdx++;
                    }

                    writer.Flush();
                }

                isNewFile = this.IsNewFile(fileName);
            }

            if (writer != null)
            {
                writer.Close();
                writer.Dispose();
            }

            return(true);
        }
コード例 #8
0
 private void CleanPhysicalPath(DeployContext context)
 {
     context.Log.InfoFormat("Cleaning folder {0}", context.PhysicalPath);
     DirectoryUtil.Clean(context.PhysicalPath);
 }
コード例 #9
0
 private void CopyNewFiles(DeployContext context)
 {
     context.Log.InfoFormat("Copying new files");
     DirectoryUtil.CopyDirectory(context.TempFolderWithNewVersionFiles, context.PhysicalPath);
 }
コード例 #10
0
        /// <summary>
        /// 监听文件是否来了
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnListen_Click(object sender, System.EventArgs e)
        {
            string revPath = txtListen.Text.Replace("yyyyMMdd", txtTDay.Text.Trim()).Trim();

            if (string.IsNullOrEmpty(revPath))
            {
                txtListen.Focus();
                MessageDxUtil.ShowError("监听路径 未配置");
                return;
            }

            if (string.IsNullOrEmpty(txtListenTipMsg.Text.Trim()))
            {
                txtListenTipMsg.Focus();
                MessageDxUtil.ShowError("监听完成提示内容 未配置");
                return;
            }

            if (!DirectoryUtil.IsExistDirectory(revPath))
            {
                txtListen.Focus();
                MessageDxUtil.ShowError(string.Format("配置监听路径不存在 ListenPath: {0}", revPath));
                return;
            }

            Task task1 = new Task(() => {
                // 获取初始化数据
                list = InitRevData(revPath);
                if (list.Count == 0)
                {
                    MessageDxUtil.ShowError("启用代销数据项为0, 请在代销配置中配置启用的代销数据项");
                    return;
                }

                // 检查是否已经全部到齐
                Boolean isRev = true;
                foreach (ConsignmentInfo consignmentInfo in list)
                {
                    if (string.Equals("0", consignmentInfo.Data1))
                    {
                        isRev = false;
                    }
                }

                if (isRev)
                {
                    MessageDxUtil.ShowTips(txtListenTipMsg.Text.Trim());
                }
                else
                {
                    UpdateSpeekText("停止播放");

                    //btnCancelSpeek.Text = "停止播放";
                    isAllArr = 1;

                    mfsw                     = new MyFileSystemWatcher(revPath);
                    mfsw.Filter              = "*";
                    mfsw.Created            += new FileSystemEventHandler(mfsw_Created);
                    mfsw.EnableRaisingEvents = true;
                    mfsw.NotifyFilter        = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess
                                               | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
                    mfsw.IncludeSubdirectories = true;
                }
            });

            task1.Start();
        }
コード例 #11
0
        private void btnBuildOk_Click(object sender, EventArgs e)
        {
            Task task1 = new Task(() => {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, "START [开始生成OK标志]", typeof(FrmDealConsignment));

                AddLog(LogLevel.LOG_LEVEL_INFO, "START [开始生成OK标志]");

                string buildPath      = txtBuildOk.Text.Replace("yyyyMMdd", txtTDay.Text.Trim()).Trim();
                string build004Path   = txtBuild004Ok.Text.Replace("yyyyMMdd", txtTDay.Text.Trim()).Trim();
                string build012Path   = txtBuild012Ok.Text.Replace("yyyyMMdd", txtTDay.Text.Trim()).Trim();
                string TDay           = txtTDay.Text.Trim();
                string T1Day          = txtT1Day.Text.Trim();
                string[] ExcludeItems = txtExcludeItems.Text.Trim().Split(',');

                if (string.IsNullOrEmpty(buildPath))
                {
                    txtcheckPath.Focus();
                    MessageDxUtil.ShowError("生成路径 未配置");
                    return;
                }

                if (!DirectoryUtil.IsExistDirectory(buildPath))
                {
                    txtcheckPath.Focus();
                    MessageDxUtil.ShowError(string.Format("配置生成路径不存在 BuildPath: {0}", buildPath));
                    return;
                }

                if (string.IsNullOrEmpty(build004Path))
                {
                    txtcheckPath.Focus();
                    MessageDxUtil.ShowError("3T_004_hq 未配置");
                    return;
                }

                if (!DirectoryUtil.IsExistDirectory(build004Path))
                {
                    txtcheckPath.Focus();
                    MessageDxUtil.ShowError(string.Format("配置 3T_004_hq 不存在 Build004Path: {0}", build004Path));
                    return;
                }

                if (string.IsNullOrEmpty(build012Path))
                {
                    txtcheckPath.Focus();
                    MessageDxUtil.ShowError("3T_012_HQ 未配置");
                    return;
                }

                if (!DirectoryUtil.IsExistDirectory(build012Path))
                {
                    txtcheckPath.Focus();
                    MessageDxUtil.ShowError(string.Format("配置 3T_012_HQ 不存在 Build012Path: {0}", build012Path));
                    return;
                }

                // 遍历全部的文件夹并删除已经存在的OK标志
                String[] files = DirectoryUtil.GetFileNames(buildPath, "*.ok", true);
                foreach (String file in files)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("删除文件OK文件 {0}", file), typeof(FrmDealConsignment));
                    FileUtil.DeleteFile(file);
                }

                Int32 buildOkCount    = 0;
                Int32 build004OkCount = 0;
                Int32 build012OkCount = 0;
                // 遍历全部的文件夹并生成OK标志
                files = DirectoryUtil.GetFileNames(buildPath, "*.*", true);
                foreach (String file in files)
                {
                    // 对于排除的项目不生成ok标志
                    bool isSkip = false;

                    foreach (string item in ExcludeItems)
                    {
                        if (file.Contains(item))
                        {
                            isSkip = true;
                            continue;
                        }
                    }

                    if (isSkip)
                    {
                        continue;
                    }

                    string fileOk = string.Format("{0}.ok", file);
                    AddLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("生成文件OK文件 {0}", fileOk));
                    FileUtil.CreateFile(fileOk);

                    buildOkCount++;
                }

                // 遍历 3T_004_hq 下 T+1对应的文件生成OK标志
                files = DirectoryUtil.GetFileNames(build004Path, string.Format("*{0}*.ok", T1Day), true);
                foreach (String file in files)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("删除004文件OK文件 {0}", file), typeof(FrmDealConsignment));
                    FileUtil.DeleteFile(file);
                }

                // 遍历全部的文件夹并生成OK标志
                files = DirectoryUtil.GetFileNames(build004Path, string.Format("*{0}*.*", T1Day), true);
                foreach (String file in files)
                {
                    string fileOk = string.Format("{0}.ok", file);
                    AddLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("生成004文件OK文件 {0}", fileOk));
                    //LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("生成004文件OK文件 {0}", fileOk), typeof(FrmDealConsignment));
                    FileUtil.CreateFile(fileOk);
                    build004OkCount++;
                }

                // 遍历 3T_012_HQ 下 T+1对应的文件生成OK标志
                files = DirectoryUtil.GetFileNames(build012Path, string.Format("*{0}*.ok", T1Day), true);
                foreach (String file in files)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("删除012文件OK文件 {0}", file), typeof(FrmDealConsignment));
                    FileUtil.DeleteFile(file);
                }

                // 遍历全部的文件夹并生成OK标志
                files = DirectoryUtil.GetFileNames(build012Path, string.Format("*{0}*.*", T1Day), true);
                foreach (String file in files)
                {
                    string fileOk = string.Format("{0}.ok", file);
                    AddLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("生成012文件OK文件 {0}", fileOk));
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("生成012文件OK文件 {0}", fileOk), typeof(FrmDealConsignment));
                    FileUtil.CreateFile(fileOk);
                    build012OkCount++;
                }
                string str = string.Format("代销处理完成! 生成路径生成OK共计{0}条记录 3T_004_hq生成OK共计{1}条记录 3T_012_HQ生成OK共计{2}条记录", buildOkCount, build004OkCount, build012OkCount);
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, "END [" + str + "]", typeof(FrmDealConsignment));

                AddLog(LogLevel.LOG_LEVEL_INFO, "END [" + str + "]");

                MessageDxUtil.ShowTips(str);
            });

            task1.Start();
        }
コード例 #12
0
ファイル: TouHangDiGaoFrm.cs プロジェクト: 15831944/winform-1
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            string path = FileDialogHelper.OpenDir();

            string recordFileName = "\\" + "缺少文件.txt";

            if (FileUtil.FileIsExist(path + recordFileName))
            {
                FileUtil.DeleteFile(path + recordFileName);
            }
            FileUtil.CreateFile(path + recordFileName);


            if (!string.IsNullOrEmpty(path))
            {
                string[] dirs = DirectoryUtil.GetDirectories(path);

                Dictionary <string, bool> a = new Dictionary <string, bool>();
                // 判断是否是子目录
                foreach (var d in dirs)
                {
                    string[] subdirs = DirectoryUtil.GetDirectories(d, "*", true);

                    string[] tmpdsname = d.Split('\\');
                    string   dsname    = tmpdsname[tmpdsname.Length - 1].Split('$')[0];

                    foreach (var dir in subdirs)
                    {
                        string[] tmpdirsname = dir.Split('\\');
                        string   dirname     = tmpdirsname[tmpdirsname.Length - 1].Split('$')[0];

                        a[dsname + dirname] = false;

                        if (dirname.Substring(0, 1) == "第" && dirname.Substring(dirname.Length - 1, 1) == "章")
                        {
                            continue;
                        }

                        Int32 readCount = 0;
                        foreach (var dir2 in subdirs)
                        {
                            string[] tmpdir2sname = dir2.Split('\\');
                            string   dir2name     = tmpdir2sname[tmpdir2sname.Length - 1].Split('$')[0];

                            if (dir2name != dirname && dirname.Contains(dir2name) && dirname.IndexOf(dir2name) == 0)
                            {
                                a[dsname + dirname] = true;
                                break;
                            }

                            if (dir2name != dirname && dir2name.Contains(dirname) && dir2name.IndexOf(dirname) == 0)
                            {
                                a[dsname + dirname] = false;
                                break;
                            }

                            // 已经遍历玩了,则还没有找到就是没有子目录
                            readCount++;
                            if (subdirs.Length == readCount)
                            {
                                a[dsname + dirname] = true;
                                break;
                            }
                        }
                    }
                }

                foreach (var d in dirs)
                {
                    string[] subdirs = DirectoryUtil.GetDirectories(d, "*", true);

                    string[] tmpdsname = d.Split('\\');
                    string   dsname    = tmpdsname[tmpdsname.Length - 1].Split('$')[0];

                    foreach (var dir in subdirs)
                    {
                        string[] tmpdirsname = dir.Split('\\');
                        string   dirname     = tmpdirsname[tmpdirsname.Length - 1].Split('$')[0];

                        if (dirname.Substring(0, 1) == "第" && dirname.Substring(dirname.Length - 1, 1) == "章")
                        {
                            continue;
                        }
                        // 是子目录
                        if (a[dsname + dirname])
                        {
                            if (dir.Length > 250)
                            {
                                MessageDxUtil.ShowTips("目录超过限制长度[" + dir + "]");
                                continue;
                            }

                            if (DirectoryUtil.IsEmptyDirectory(dir))
                            {
                                FileUtil.AppendText(path + recordFileName, string.Format("{0}\r\n", dir), Encoding.UTF8);
                            }
                        }
                    }
                }

                MessageDxUtil.ShowTips("操作完成");
            }
        }
コード例 #13
0
ファイル: TouHangDiGaoFrm.cs プロジェクト: 15831944/winform-1
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            string copyToPath = txtCopytoPath.Text.Trim();
            string sourcePath = txtSourcePath.Text.Trim();

            if (string.IsNullOrEmpty(copyToPath))
            {
                MessageDxUtil.ShowError("复制到对应文件夹未配置");
                return;
            }

            if (string.IsNullOrEmpty(sourcePath))
            {
                MessageDxUtil.ShowError("拷贝源文件夹未配置");
                return;
            }

            // 读取文件夹保存到字典 字段值为 第几部分_索引名字,拷贝全路径
            Dictionary <string, string> dic = new Dictionary <string, string>();

            string[] allDirs = DirectoryUtil.GetDirectories(copyToPath, "*", true);
            foreach (var dir in allDirs)
            {
                // 如果路径超长了 就不往下走了
                if (dir.Length > 245)
                {
                    continue;
                }

                DirectoryInfo dirinfo = new DirectoryInfo(dir);

                // 没找到
                if (dirinfo.Name.Split('$').Length <= 1)
                {
                    continue;
                }

                // 合法路径
                if (dirinfo.Parent.Name.Split('$')[0].Contains("部分") && dirinfo.Parent.Name.Split('$')[0].Substring(0, 1) == "第")
                {
                    dic[dirinfo.Parent.Name.Split('$')[0] + "_" + dirinfo.Name.Split('$')[1]] = dir;
                }
            }

            Int32 copyCount = 0;

            string[] allFiles = DirectoryUtil.GetAllFileNames(sourcePath);
            foreach (var file in allFiles)
            {
                FileInfo fileInfo = new FileInfo(file);

                // 没找到
                if (fileInfo.Name.Split(' ').Length <= 1)
                {
                    continue;
                }

                string indexStr = fileInfo.Name.Split(' ')[1];
                string pattern  = @"第\w+部分";
                Regex  regex    = new Regex(pattern);
                if (regex.IsMatch(fileInfo.DirectoryName))
                {
                    if (dic.ContainsKey(regex.Match(fileInfo.DirectoryName).Value + "_" + fileInfo.Name.Split(' ')[1].Replace(fileInfo.Extension, "")))
                    {
                        copyCount++;
                        File.Move(fileInfo.FullName, dic[regex.Match(fileInfo.DirectoryName).Value + "_" + fileInfo.Name.Split(' ')[1].Replace(fileInfo.Extension, "")] + "\\" + fileInfo.Name);
                    }
                }
                else
                {
                    continue;
                }
            }

            MessageDxUtil.ShowTips(string.Format("操作成功, 目录下一共{0}个文件,成功拷贝{1}个文件", allFiles.Length, copyCount));
        }
コード例 #14
0
ファイル: TouHangDiGaoFrm.cs プロジェクト: 15831944/winform-1
        private void simpleButton1_Click(object sender, System.EventArgs e)
        {
            string path = FileDialogHelper.OpenDir();

            if (!string.IsNullOrEmpty(path))
            {
                string[] dirs = DirectoryUtil.GetDirectories(path);

                Dictionary <string, bool> a = new Dictionary <string, bool>();
                // 判断是否是子目录
                foreach (var d in dirs)
                {
                    string[] subdirs = DirectoryUtil.GetDirectories(d, "*", true);

                    string[] tmpdsname = d.Split('\\');
                    string   dsname    = tmpdsname[tmpdsname.Length - 1].Split('$')[0];

                    foreach (var dir in subdirs)
                    {
                        string[] tmpdirsname = dir.Split('\\');
                        string   dirname     = tmpdirsname[tmpdirsname.Length - 1].Split('$')[0];

                        a[dsname + dirname] = false;

                        if (dirname.Substring(0, 1) == "第" && dirname.Substring(dirname.Length - 1, 1) == "章")
                        {
                            continue;
                        }

                        Int32 readCount = 0;
                        foreach (var dir2 in subdirs)
                        {
                            string[] tmpdir2sname = dir2.Split('\\');
                            string   dir2name     = tmpdir2sname[tmpdir2sname.Length - 1].Split('$')[0];

                            if (dir2name != dirname && dirname.Contains(dir2name) && dirname.IndexOf(dir2name) == 0)
                            {
                                a[dsname + dirname] = true;
                                break;
                            }

                            if (dir2name != dirname && dir2name.Contains(dirname) && dir2name.IndexOf(dirname) == 0)
                            {
                                a[dsname + dirname] = false;
                                break;
                            }
                            // 已经遍历玩了,则还没有找到就是没有子目录
                            readCount++;
                            if (subdirs.Length == readCount)
                            {
                                a[dsname + dirname] = true;
                                break;
                            }
                        }
                    }
                }

                foreach (var d in dirs)
                {
                    string[] subdirs = DirectoryUtil.GetDirectories(d, "*", true);

                    string[] tmpdsname = d.Split('\\');
                    string   dsname    = tmpdsname[tmpdsname.Length - 1].Split('$')[0];

                    foreach (var dir in subdirs)
                    {
                        string[] tmpdirsname = dir.Split('\\');
                        string   dirname     = tmpdirsname[tmpdirsname.Length - 1].Split('$')[0];

                        if (dirname.Substring(0, 1) == "第" && dirname.Substring(dirname.Length - 1, 1) == "章")
                        {
                            continue;
                        }
                        // 是子目录
                        if (a[dsname + dirname])
                        {
                            if (dir.Length > 250)
                            {
                                MessageDxUtil.ShowTips("目录超过限制长度[" + dir + "]");
                                continue;
                            }

                            if ((dir + "\\" + tmpdirsname[tmpdirsname.Length - 1].Split('$')[1] + ".txt").Length > 250)
                            {
                                FileUtil.WriteText(dir + "\\1.txt", tmpdirsname[tmpdirsname.Length - 1].Split('$')[1], Encoding.UTF8);
                            }
                            else
                            {
                                FileUtil.WriteText(dir + "\\" + tmpdirsname[tmpdirsname.Length - 1].Split('$')[1] + ".txt", tmpdirsname[tmpdirsname.Length - 1].Split('$')[1], Encoding.UTF8);
                            }
                        }
                    }
                }

                MessageDxUtil.ShowTips("操作完成");
            }
        }
コード例 #15
0
        public void LoadConfiguration()
        {
            FileStream  fs = null;
            string      c_configFileName = null;
            XmlDocument configuration    = new XmlDocument();

            try
            {
                if (_cacheId == null)
                {
                    return;
                }
                c_configFileName = DirectoryUtil.GetBaseFilePath("client.ncconf", _search, out _result);
                if (c_configFileName == null)
                {
                    return;
                }
                FileInfo fileInfo = new FileInfo(c_configFileName);
                fs = fileInfo.OpenRead();
                configuration.Load(fs);
                fileInfo = null;

                bool serverPortFound = false;

                XmlNodeList serverPortList = configuration.GetElementsByTagName("ncache-server");
                if (serverPortList != null && serverPortList.Count > 0)
                {
                    XmlNode portNode = serverPortList.Item(0);
                    if (portNode != null)
                    {
                        XmlAttributeCollection attributes = portNode.Attributes;
                        if (attributes != null)
                        {
                            string currentAttrib = string.Empty;

                            if (initParam.ServerList != null && initParam.ServerList.Length > 0)
                            {
                                if (initParam.ServerList[0].Port > 0)
                                {
                                    _serverPort = initParam.ServerList[0].Port;
                                }
                            }
                            else
                            {
                                if (attributes["port"] != null)
                                {
                                    currentAttrib = attributes["port"].Value;
                                    if (currentAttrib != null)
                                    {
                                        _serverPort = Convert.ToInt32(currentAttrib);
                                    }
                                }
                            }
                        }
                        serverPortFound = true;
                    }
                }

                if (!serverPortFound)
                {
                    throw new Runtime.Exceptions.ConfigurationException("ncache-server missing in client confiugration");
                }

                XmlNodeList cacheList   = configuration.GetElementsByTagName("cache");
                XmlNodeList cacheConfig = null;

                for (int i = 0; i < cacheList.Count; i++)
                {
                    XmlNode cache = cacheList.Item(i);
                    if (cache.Attributes.GetNamedItem("id").Value.ToLower().Equals(_cacheId.ToLower()))
                    {
                        if (cache.Attributes["load-balance"] != null)
                        {
                            this._balanceNodes = Convert.ToBoolean(cache.Attributes["load-balance"].Value);
                        }
                        if (initParam != null && initParam.IsSet(LOADBALANCE))
                        {
                            this._balanceNodes = initParam.LoadBalance;
                        }



                        try
                        {
                            if (cache.Attributes["enable-client-logs"] != null)
                            {
                                this._enableClientLogs = Convert.ToBoolean(cache.Attributes["enable-client-logs"].Value.ToString());
                            }
                        }
                        catch (Exception)
                        { }

                        if (cache.Attributes["log-level"] != null)
                        {
                            this._enableDetailedClientLogs = cache.Attributes["log-level"].Value.ToString().ToLower() == "info" ? true : false;
                        }

                        this.serverRuntimeContext = RtContextValue.NCACHE;
                        _importHashmap            = true;

                        cacheConfig = cache.ChildNodes;
                        break;
                    }
                }

                if (cacheConfig == null)
                {
                    if (!String.IsNullOrEmpty(_cacheId))
                    {
                        if (_result != Search.GlobalSearch)
                        {
                            _search = _result + 1;
                            LoadConfiguration();
                        }
                    }
                    return;
                }
                _search = _result;
                LoadRemoteServerMappingConfig(cacheConfig);

                LoadRemoteServerConfig(cacheConfig);
            }
            catch (Runtime.Exceptions.ConfigurationException)
            {
                throw;
            }
            catch (System.IO.IOException) { throw; }
            catch (Exception e)
            {
                throw new Runtime.Exceptions.ConfigurationException("An error occurred while reading client.ncconf. " + e.Message);
            }

            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
コード例 #16
0
        public static void InstantiateCartridge(Manifest cartridge, string target, bool failureRemove = true)
        {
            Directory.CreateDirectory(target);
            try
            {
                bool downloadable = cartridge.ManifestPath == "url";

                if (downloadable)
                {
                    Uri    uri       = new Uri(cartridge.SourceUrl);
                    string temporary = Path.Combine(target, Path.GetFileName(uri.LocalPath));

                    if (uri.Scheme == "git" || cartridge.SourceUrl.EndsWith(".git"))
                    {
                        // use intermediate temp directory to reset cygwin directories ACLs
                        string tempRepo    = cartridge.Name + ".temp";
                        string tempRepoDir = Path.Combine(new DirectoryInfo(target).Parent.FullName, tempRepo);
                        try
                        {
                            string template = @"{0} clone {1} {2}
set GIT_DIR=./{2}/.git
{0} repack";
                            string file     = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + "cmd.bat");
                            File.WriteAllText(file, string.Format(template, Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], @"bin\git.exe"), cartridge.SourceUrl, tempRepo));
                            ProcessResult result = ProcessExtensions.RunCommandAndGetOutput("cmd.exe", string.Format("/c {0}", file), new DirectoryInfo(target).Parent.FullName);
                            if (result.ExitCode != 0)
                            {
                                throw new Exception(string.Format("Unable to clone cartridge from {0} stdout: {1} stderr {2}", cartridge.SourceUrl, result.StdOut, result.StdErr));
                            }

                            DirectoryUtil.DirectoryCopy(tempRepoDir, target, true);
                        }
                        finally
                        {
                            if (Directory.Exists(tempRepoDir))
                            {
                                Directory.Delete(tempRepoDir, true);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.zip"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("zip", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"(\.tar\.gz|\.tgz)$"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("tgz", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.tar$"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("tar", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (uri.Scheme == "file")
                    {
                        DirectoryUtil.DirectoryCopy(uri.LocalPath, target, true);
                    }
                    else
                    {
                        throw new ArgumentException(string.Format("CLIENT_ERROR: Unsupported URL({0}) for downloading a private cartridge", cartridge.SourceUrl));
                    }
                }
                else
                {
                    // TODO exclude usr folder and use link
                    DirectoryUtil.DirectoryCopy(cartridge.RepositoryPath, target, true);
                }

                ValidateCartridgeHome(cartridge, target);

                if (downloadable)
                {
                    string manifestOnDisk = Path.Combine(target, "metadata", "manifest.yml");
                    using (StreamWriter sw = new StreamWriter(manifestOnDisk))
                    {
                        Serializer ser = new Serializer(SerializationOptions.None);
                        ser.Serialize(sw, cartridge.ManifestSpec);
                    }
                }
            }
            catch (Exception e)
            {
                if (failureRemove)
                {
                    if (Directory.Exists(target))
                    {
                        Directory.Delete(target);
                    }
                }
                throw e;
            }
        }
コード例 #17
0
        /// <summary>
        /// 根据查询条件导出列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult Export()
        {
            #region 根据参数获取List列表
            string where = GetPagerCondition();
            string             CustomedCondition = Request["CustomedCondition"] ?? "";
            List <ContactInfo> list = new List <ContactInfo>();

            if (!string.IsNullOrWhiteSpace(CustomedCondition))
            {
                Dictionary <string, string> dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(CustomedCondition);
                if (dict != null)
                {
                    string id        = dict["id"];
                    string groupname = dict["groupname"];
                    string userid    = dict["userid"];

                    if (string.IsNullOrEmpty(id))
                    {
                        if (groupname == "所有联系人")
                        {
                            where = "";//直接使用空条件
                            list  = baseBLL.Find(where);
                        }
                        else if (groupname == "未分组联系人")
                        {
                            list = BLLFactory <Contact> .Instance.FindByGroupName(userid, null);
                        }
                    }
                    else
                    {
                        list = BLLFactory <Contact> .Instance.FindByGroupName(userid, groupname);
                    }
                }
            }
            else
            {
                list = baseBLL.Find(where);
            }
            #endregion

            #region 把列表转换为DataTable
            DataTable datatable = DataTableHelper.CreateTable("序号|int," + columnString);
            DataRow   dr;
            int       j = 1;
            for (int i = 0; i < list.Count; i++)
            {
                dr         = datatable.NewRow();
                dr["序号"]   = j++;
                dr["客户名称"] = BLLFactory <Customer> .Instance.GetCustomerName(list[i].Customer_ID);//转义为客户名称

                dr["编号"]    = list[i].HandNo;
                dr["姓名"]    = list[i].Name;
                dr["身份证号码"] = list[i].IDCarNo;
                dr["出生日期"]  = list[i].Birthday;
                dr["性别"]    = list[i].Sex;
                dr["办公电话"]  = list[i].OfficePhone;
                dr["家庭电话"]  = list[i].HomePhone;
                dr["传真"]    = list[i].Fax;
                dr["联系人手机"] = list[i].Mobile;
                dr["联系人地址"] = list[i].Address;
                dr["邮政编码"]  = list[i].ZipCode;
                dr["电子邮件"]  = list[i].Email;
                dr["QQ号码"]  = list[i].Qq;
                dr["备注"]    = list[i].Note;
                dr["排序序号"]  = list[i].Seq;
                dr["所在省份"]  = list[i].Province;
                dr["城市"]    = list[i].City;
                dr["所在行政区"] = list[i].District;
                dr["籍贯"]    = list[i].Hometown;
                dr["家庭住址"]  = list[i].HomeAddress;
                dr["民族"]    = list[i].Nationality;
                dr["教育程度"]  = list[i].Eduction;
                dr["毕业学校"]  = list[i].GraduateSchool;
                dr["政治面貌"]  = list[i].Political;
                dr["职业类型"]  = list[i].JobType;
                dr["职称"]    = list[i].Titles;
                dr["职务"]    = list[i].Rank;
                dr["所在部门"]  = list[i].Department;
                dr["爱好"]    = list[i].Hobby;
                dr["属相"]    = list[i].Animal;
                dr["星座"]    = list[i].Constellation;
                dr["婚姻状态"]  = list[i].MarriageStatus;
                dr["健康状况"]  = list[i].HealthCondition;
                dr["重要级别"]  = list[i].Importance;
                dr["认可程度"]  = list[i].Recognition;
                dr["关系"]    = list[i].RelationShip;
                dr["负责需求"]  = list[i].ResponseDemand;
                dr["关心重点"]  = list[i].CareFocus;
                dr["利益诉求"]  = list[i].InterestDemand;
                dr["体型"]    = list[i].BodyType;
                dr["吸烟"]    = list[i].Smoking;
                dr["喝酒"]    = list[i].Drink;
                dr["身高"]    = list[i].Height;
                dr["体重"]    = list[i].Weight;
                dr["视力"]    = list[i].Vision;
                dr["个人简述"]  = list[i].Introduce;

                datatable.Rows.Add(dr);
            }
            #endregion

            #region 把DataTable转换为Excel并输出
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            //为单元格添加样式
            Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
            //设置居中
            style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            //设置背景颜色
            style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0);
            style.Pattern         = BackgroundType.Solid;
            style.Font.IsBold     = true;

            int rowIndex = 0;
            for (int i = 0; i < datatable.Columns.Count; i++)
            {
                DataColumn col        = datatable.Columns[i];
                string     columnName = col.Caption ?? col.ColumnName;
                workbook.Worksheets[0].Cells[rowIndex, i].PutValue(columnName);
                workbook.Worksheets[0].Cells[rowIndex, i].SetStyle(style);
            }
            rowIndex++;

            foreach (DataRow row in datatable.Rows)
            {
                for (int i = 0; i < datatable.Columns.Count; i++)
                {
                    workbook.Worksheets[0].Cells[rowIndex, i].PutValue(row[i].ToString());
                }
                rowIndex++;
            }

            for (int k = 0; k < datatable.Columns.Count; k++)
            {
                workbook.Worksheets[0].AutoFitColumn(k, 0, 150);
            }
            workbook.Worksheets[0].FreezePanes(1, 0, 1, datatable.Columns.Count);

            //根据用户创建目录,确保生成的文件不会产生冲突
            string filePath   = string.Format("/GenerateFiles/{0}/Contact.xls", CurrentUser.Name);
            string realPath   = Server.MapPath(filePath);
            string parentPath = Directory.GetParent(realPath).FullName;
            DirectoryUtil.AssertDirExist(parentPath);

            workbook.Save(realPath, Aspose.Cells.SaveFormat.Excel97To2003);

            #endregion

            //返回生成后的文件路径,让客户端根据地址下载
            return(Content(filePath));
        }
コード例 #18
0
ファイル: FileUpload.cs プロジェクト: goodyu372/M12MiniMes
        /// <summary>
        /// 对附件组包含的文件进行归档处理,归档文件重新移动到指定的归档目录中
        /// </summary>
        /// <param name="attachmentGUID">附件组GUID</param>
        /// <param name="basePath">基础路径</param>
        /// <param name="archiveCategory">归档目录</param>
        /// <returns></returns>
        public CommonResult ArchiveFile(string attachmentGUID, string basePath, string archiveCategory)
        {
            var result = new CommonResult();

            if (string.IsNullOrEmpty(basePath))
            {
                result.ErrorMessage = "基础路径basePath没有指定,无法归档";
                return(result);
            }

            var fileList = BLLFactory <FileUpload> .Instance.GetByAttachGUID(attachmentGUID);

            foreach (var info in fileList)
            {
                if (info != null && !string.IsNullOrEmpty(info.SavePath))
                {
                    if (!string.IsNullOrEmpty(info.BasePath))
                    {
                        var url = info.BasePath.UriCombine(info.SavePath);
                        if (info.BasePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                        {
                            result.ErrorMessage = "HTTP路径文件无法归档";
                        }
                        else if (info.BasePath.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
                        {
                            result.ErrorMessage = "FTP路径文件无法归档";
                        }
                        else
                        {
                            //相对目录或者本地目录可以归档

                            //归档实际路径
                            string realArchiveBaseDir = basePath;
                            if (!IsPhysicalPath(realArchiveBaseDir))
                            {
                                //如果没指定基础路径,则以配置为主,如果没有配置项AttachmentBasePath,默认一个相对目录
                                string AttachmentBasePath = config.AppConfigGet("AttachmentBasePath");//配置的基础路径
                                if (string.IsNullOrEmpty(AttachmentBasePath))
                                {
                                    //默认以根目录下的UploadFiles目录为上传目录, 例如"C:\SPDTPatientMisService\UploadFiles";
                                    AttachmentBasePath = AppDomain.CurrentDomain.BaseDirectory.PathCombine("UploadFiles");
                                }
                                //和附件上传目录,组合为一个正确路径
                                realArchiveBaseDir = AttachmentBasePath.PathCombine(realArchiveBaseDir);
                            }
                            //包含分类目录的路径
                            string realArchivePath = realArchiveBaseDir.PathCombine(archiveCategory);

                            //实际文件路径
                            string serverRealPath = PathCombine(info.BasePath, info.SavePath.Replace('\\', '/'));
                            if (!IsPhysicalPath(serverRealPath))
                            {
                                //如果是相对目录,加上当前程序的目录才能定位文件地址
                                serverRealPath = AppDomain.CurrentDomain.BaseDirectory.PathCombine(serverRealPath);
                            }

                            try
                            {
                                //确保移动的目录存在,不存在则创建
                                DirectoryUtil.AssertDirExist(realArchivePath);
                                //移动后的路径
                                var movedFilePath = realArchivePath.PathCombine(info.FileName);

                                if (File.Exists(serverRealPath) && !File.Exists(movedFilePath))
                                {
                                    //移动文件
                                    File.Move(serverRealPath, movedFilePath);

                                    //修改数据库的文件路径并更新
                                    string    filePath = movedFilePath.Replace(realArchiveBaseDir, "");
                                    Hashtable ht       = new Hashtable();
                                    ht.Add("BasePath", realArchiveBaseDir);
                                    ht.Add("SavePath", filePath);
                                    baseDal.UpdateFields(ht, info.ID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var tips = "文件归档出现错误:" + ex.Message;
                                LogTextHelper.Error(tips);
                                result.ErrorMessage = tips;
                            }
                        }
                    }
                }
            }
            result.Success = true;

            return(result);
        }
コード例 #19
0
        public void MirrorRepositories(
            MirroringConfiguration configuration,
            MirroringSettings settings,
            CancellationToken cancellationToken)
        {
            var descriptor       = GetMirroringDescriptor(configuration);
            var loggedDescriptor = descriptor + " (#" + configuration.Id.ToString() + ")";

            Debug.WriteLine("Starting mirroring: " + loggedDescriptor);
            _eventLog.WriteEntry("Starting mirroring: " + loggedDescriptor);

            var repositoryDirectoryName = GetCloneDirectoryName(configuration);
            // A subfolder per clone dir start letter:
            var cloneDirectoryParentPath = Path.Combine(settings.RepositoriesDirectoryPath, repositoryDirectoryName[0].ToString());
            var cloneDirectoryPath       = Path.Combine(cloneDirectoryParentPath, repositoryDirectoryName);
            var repositoryLockFilePath   = GetRepositoryLockFilePath(cloneDirectoryPath);

            try
            {
                if (File.Exists(repositoryLockFilePath))
                {
                    var logEntryStart =
                        "An existing lock was found for the mirroring configuration " + loggedDescriptor + ". ";
                    var lastUpdatedTimeUtc = RepositoryInfoFileHelper.GetLastUpdatedDateTimeUtc(cloneDirectoryPath);

                    if (lastUpdatedTimeUtc >= DateTime.UtcNow.AddSeconds(-settings.MirroringTimoutSeconds))
                    {
                        _eventLog.WriteEntry(
                            logEntryStart +
                            "This can mean that the number of configurations was reduced and thus while a mirroring was running a new process for the same repositories was started. We'll let the initial process finish.");

                        return;
                    }
                    else
                    {
                        _eventLog.WriteEntry(
                            logEntryStart +
                            "Additionally the directory was last touched at " + lastUpdatedTimeUtc.ToString() +
                            " UTC which is older than the allowed mirroring timeout (" + settings.MirroringTimoutSeconds +
                            "s). Thus the lock is considered abandoned and mirroring will continue.",
                            EventLogEntryType.Warning);
                    }
                }

                if (configuration.HgCloneUri.Scheme.Equals("ssh", StringComparison.InvariantCultureIgnoreCase) ||
                    configuration.GitCloneUri.Scheme.Equals("ssh", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new MirroringException("SSH protocol is not supported, only HTTPS.");
                }

                if (!Directory.Exists(cloneDirectoryParentPath))
                {
                    Directory.CreateDirectory(cloneDirectoryParentPath);
                }

                File.Create(repositoryLockFilePath).Dispose();

                // Changing directory to other drive if necessary.
                RunCommandAndLogOutput(Path.GetPathRoot(cloneDirectoryPath).Replace("\\", string.Empty));

                var quotedHgCloneUrl         = configuration.HgCloneUri.ToString().EncloseInQuotes();
                var quotedGitCloneUrl        = configuration.GitCloneUri.ToString().EncloseInQuotes();
                var quotedCloneDirectoryPath = cloneDirectoryPath.EncloseInQuotes();
                var isCloned = IsCloned(configuration, settings);

                if (!isCloned)
                {
                    DeleteDirectoryIfExists(cloneDirectoryPath);
                    Directory.CreateDirectory(cloneDirectoryPath);
                }

                RepositoryInfoFileHelper.CreateOrUpdateFile(cloneDirectoryPath, descriptor);

                // Mirroring between two git repos is supported, but in a hacked-in way at the moment. This needs a
                // clean-up. Also, do note that only GitToHg and TwoWay is implemented. It would make the whole thing
                // even more messy to duplicate the logic in HgToGit.
                var hgUrlIsGitUrl = configuration.HgCloneUri.Scheme == "git+https";

                cancellationToken.ThrowIfCancellationRequested();

                switch (configuration.Direction)
                {
                case MirroringDirection.GitToHg:
                    if (hgUrlIsGitUrl)
                    {
                        RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                      .FetchOrCloneFromGit(configuration.GitCloneUri, cloneDirectoryPath, true, cancellationToken));
                        _gitCommandExecutor.PushToGit(configuration.HgCloneUri, cloneDirectoryPath, cancellationToken);
                    }
                    else
                    {
                        if (isCloned)
                        {
                            if (configuration.GitUrlIsHgUrl)
                            {
                                _hgCommandExecutor
                                .PullHg(quotedGitCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                            }
                            else
                            {
                                RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                              .FetchOrCloneFromGit(configuration.GitCloneUri, cloneDirectoryPath, true, cancellationToken));
                                _hgCommandExecutor.ImportHistoryFromGit(quotedCloneDirectoryPath, settings, cancellationToken);
                            }
                        }
                        else
                        {
                            if (configuration.GitUrlIsHgUrl)
                            {
                                _hgCommandExecutor
                                .CloneHg(quotedGitCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                            }
                            else
                            {
                                _hgCommandExecutor
                                .CloneGit(configuration.GitCloneUri, quotedCloneDirectoryPath, settings, cancellationToken);
                            }
                        }

                        _hgCommandExecutor
                        .PushWithBookmarks(quotedHgCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                    }

                    break;

                case MirroringDirection.HgToGit:
                    if (isCloned)
                    {
                        _hgCommandExecutor.PullHg(quotedHgCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                    }
                    else
                    {
                        _hgCommandExecutor.CloneHg(quotedHgCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                    }

                    if (configuration.GitUrlIsHgUrl)
                    {
                        _hgCommandExecutor
                        .PushWithBookmarks(quotedGitCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                    }
                    else
                    {
                        _hgCommandExecutor.CreateOrUpdateBookmarksForBranches(quotedCloneDirectoryPath, settings, cancellationToken);
                        _hgCommandExecutor.ExportHistoryToGit(quotedCloneDirectoryPath, settings, cancellationToken);
                        RunGitCommandAndMarkException(() =>
                                                      _gitCommandExecutor.PushToGit(configuration.GitCloneUri, cloneDirectoryPath, cancellationToken));
                    }

                    break;

                case MirroringDirection.TwoWay:
                    Action syncHgAndGitHistories = () =>
                    {
                        _hgCommandExecutor
                        .CreateOrUpdateBookmarksForBranches(quotedCloneDirectoryPath, settings, cancellationToken);
                        _hgCommandExecutor.ExportHistoryToGit(quotedCloneDirectoryPath, settings, cancellationToken);

                        // This will clear all commits int he git repo that aren't in the git remote repo but
                        // add changes that were added to the git repo.
                        RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                      .FetchOrCloneFromGit(configuration.GitCloneUri, cloneDirectoryPath, false, cancellationToken));
                        _hgCommandExecutor.ImportHistoryFromGit(quotedCloneDirectoryPath, settings, cancellationToken);

                        // Updating bookmarks which may have shifted after importing from git. This way the
                        // export to git will create a git repo with history identical to the hg repo.
                        _hgCommandExecutor.CreateOrUpdateBookmarksForBranches(quotedCloneDirectoryPath, settings, cancellationToken);
                        _hgCommandExecutor.ExportHistoryToGit(quotedCloneDirectoryPath, settings, cancellationToken);

                        RunGitCommandAndMarkException(() =>
                                                      _gitCommandExecutor.PushToGit(configuration.GitCloneUri, cloneDirectoryPath, cancellationToken));
                    };

                    if (hgUrlIsGitUrl)
                    {
                        // The easiest solution to do two-way git mirroring is to sync separately, with two clones.
                        // Otherwise when e.g. repository A adds a new commit, then repository B is pulled in, the
                        // head of the branch will be at the point where it is in B. Thus pushing to A will fail
                        // with "Cannot push non-fastforwardable reference". There are other similar errors that
                        // can arise but can't easily be fixed automatically in a safe way. So first pulling both
                        // repos then pushing them won't work.

                        var gitDirectoryPath = GitCommandExecutor.GetGitDirectoryPath(cloneDirectoryPath);

                        var    secondToFirstClonePath = Path.Combine(gitDirectoryPath, "secondToFirst");
                        Action pullSecondPushToFirst  = () =>
                        {
                            RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                          .FetchOrCloneFromGit(configuration.HgCloneUri, secondToFirstClonePath, true, cancellationToken));
                            RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                          .PushToGit(configuration.GitCloneUri, secondToFirstClonePath, cancellationToken));
                        };

                        var firstToSecondClonePath = Path.Combine(gitDirectoryPath, "firstToSecond");
                        RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                      .FetchOrCloneFromGit(configuration.GitCloneUri, firstToSecondClonePath, true, cancellationToken));
                        try
                        {
                            RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                          .PushToGit(configuration.HgCloneUri, firstToSecondClonePath, cancellationToken));

                            pullSecondPushToFirst();
                        }
                        catch (LibGit2SharpException ex) when(ex.Message.Contains("Cannot push because a reference that you are trying to update on the remote contains commits that are not present locally."))
                        {
                            pullSecondPushToFirst();

                            // This exception can happen when the second repo contains changes not present in the
                            // first one. Then we need to update the first repo with the second's changes and pull-
                            // push again.
                            RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                          .FetchOrCloneFromGit(configuration.GitCloneUri, firstToSecondClonePath, true, cancellationToken));
                            RunGitCommandAndMarkException(() => _gitCommandExecutor
                                                          .PushToGit(configuration.HgCloneUri, firstToSecondClonePath, cancellationToken));
                        }
                    }
                    else
                    {
                        if (isCloned)
                        {
                            _hgCommandExecutor.PullHg(quotedHgCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);

                            if (configuration.GitUrlIsHgUrl)
                            {
                                _hgCommandExecutor
                                .PullHg(quotedGitCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                            }
                            else
                            {
                                syncHgAndGitHistories();
                            }
                        }
                        else
                        {
                            if (configuration.GitUrlIsHgUrl)
                            {
                                _hgCommandExecutor
                                .CloneHg(quotedGitCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                                _hgCommandExecutor
                                .PullHg(quotedHgCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                            }
                            else
                            {
                                // We need to start with cloning the hg repo. Otherwise cloning the git repo, then
                                // pulling from the hg repo would yield a "repository unrelated" error, even if the git
                                // repo was created from the hg repo. For an explanation see:
                                // http://stackoverflow.com/questions/17240852/hg-git-clone-from-github-gives-abort-repository-is-unrelated
                                _hgCommandExecutor
                                .CloneHg(quotedHgCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);

                                syncHgAndGitHistories();
                            }
                        }


                        _hgCommandExecutor
                        .PushWithBookmarks(quotedHgCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);

                        if (configuration.GitUrlIsHgUrl)
                        {
                            _hgCommandExecutor
                            .PushWithBookmarks(quotedGitCloneUrl, quotedCloneDirectoryPath, settings, cancellationToken);
                        }
                    }

                    break;
                }

                Debug.WriteLine("Finished mirroring: " + loggedDescriptor);
                _eventLog.WriteEntry("Finished mirroring: " + loggedDescriptor);
            }
            catch (Exception ex) when(!ex.IsFatalOrCancellation())
            {
                // We should dispose the command runners so the folder is not locked by the command line.
                Dispose();
                // Waiting a bit for any file locks or leases to be disposed even though CommandRunners and processes
                // were killed.
                Thread.Sleep(10000);

                var exceptionMessage = string.Format(
                    "An error occured while running commands when mirroring the repositories {0} and {1} in direction {2}. Mirroring will be re-started next time.",
                    configuration.HgCloneUri,
                    configuration.GitCloneUri,
                    configuration.Direction);

                try
                {
                    // Re-cloning a repo is costly. During local debugging you can flip this variable from the
                    // Immediate Window to prevent it if necessary too.
                    var continueWithRepoFolderDelete = true;

                    // These git exceptions are caused by hg errors in a way, so despite them coming from git the whole
                    // repo folder should be removed.
                    var isHgOriginatedGitException =
                        ex.Message.Contains("does not match any existing object") ||
                        ex.Message.Contains("Object not found - failed to find pack entry");
                    if (ex.Data.Contains("IsGitException") && !isHgOriginatedGitException)
                    {
                        exceptionMessage += " The error was a git error.";

                        try
                        {
                            DeleteDirectoryIfExists(GitCommandExecutor.GetGitDirectoryPath(cloneDirectoryPath));

                            exceptionMessage            += " Thus just the git folder was removed.";
                            continueWithRepoFolderDelete = false;
                        }
                        catch (Exception gitDirectoryDeleteException) when(!gitDirectoryDeleteException.IsFatalOrCancellation())
                        {
                            exceptionMessage +=
                                " While the removal of just the git folder was attempted it failed with the following exception, thus the deletion of the whole repository folder will be attempted: " +
                                gitDirectoryDeleteException;

                            // We'll continue with the repo folder removal below.
                        }
                    }

                    if (continueWithRepoFolderDelete)
                    {
                        DeleteDirectoryIfExists(cloneDirectoryPath);
                        RepositoryInfoFileHelper.DeleteFileIfExists(cloneDirectoryPath);
                    }
                }
                catch (Exception directoryDeleteException) when(!directoryDeleteException.IsFatalOrCancellation())
                {
                    try
                    {
                        // This most possibly means that for some reason some process is still locking the folder although
                        // it shouldn't (mostly, but not definitely the cause of IOException) or there are read-only files
                        // (git pack files commonly are) which can be (but not always) behind UnauthorizedAccessException.
                        if (directoryDeleteException is IOException || directoryDeleteException is UnauthorizedAccessException)
                        {
                            var killResult = DirectoryUtil.KillProcessesLockingFiles(cloneDirectoryPath);

                            DeleteDirectoryIfExists(cloneDirectoryPath);
                            RepositoryInfoFileHelper.DeleteFileIfExists(cloneDirectoryPath);

                            exceptionMessage +=
                                " While deleting the folder of the mirror initially failed, after trying to kill processes that were locking files in it and setting all files not to be read-only the folder could be successfully deleted. " +
                                "Processes killed: " + (killResult.KilledProcesseFileNames.Any() ? string.Join(", ", killResult.KilledProcesseFileNames) : "no processes") +
                                " Read-only files: " + (killResult.ReadOnlyFilePaths.Any() ? string.Join(", ", killResult.ReadOnlyFilePaths) : "no files");

                            throw new MirroringException(exceptionMessage, ex, directoryDeleteException);
                        }
                    }
                    catch (Exception forcedCleanUpException)
                        when(!forcedCleanUpException.IsFatalOrCancellation() && !(forcedCleanUpException is MirroringException))
                        {
                            throw new MirroringException(
                                      exceptionMessage + " Subsequently clean-up after the error failed as well, also the attempt to kill processes that were locking the mirror's folder and clearing all read-only files.",
                                      ex,
                                      directoryDeleteException,
                                      forcedCleanUpException);
                        }

                    throw new MirroringException(
                              exceptionMessage + " Subsequently clean-up after the error failed as well.",
                              ex,
                              directoryDeleteException);
                }

                throw new MirroringException(exceptionMessage, ex);
            }
            finally
            {
                if (File.Exists(repositoryLockFilePath))
                {
                    File.Delete(repositoryLockFilePath);
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// 生成底单
        /// </summary>
        public void BuildImage()
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            UpdateControlText1 updateControl = updateControlText;

            try
            {
                if (_list == null || _list.Count == 0)
                {
                    return;
                }
                for (int i = 0; i < _list.Count; i++)
                {
                    if (string.IsNullOrEmpty(_list[i].BillCode))
                    {
                        continue;
                    }
                    _printFileName = !string.IsNullOrEmpty(_list[i].BillCode) ? _list[i].BillCode : DateTime.Now.Ticks.ToString();
                    _tempList.Add(_list[i]);
                    ++_tempIndex;
                    // http://blog.csdn.net/szstephenzhou/article/details/12838961
                    // 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
                    if (this.IsHandleCreated)
                    {
                        this.Invoke(updateControl, string.Format("{0}/{1}", _tempIndex, _list.Count));
                    }
                    //  2016-1-31下午 这一行代码一定要写,因为要导出模板的面单图片,所以一定要设置true,如果不想要就设置成false就行了,grid++的客服还是很不错的,qq:grid++ report  641243789
                    // _report.BackImagePrint = true;
                    // 直接调用ExportDirect方法执行导出任务,这里我只是导出图片哦
                    _report.ExportDirect(GRExportType.gretIMG, _printFileName, false, false);
                    _tempList.Clear();
                }
                if (_tempIndex > 0)
                {
                    if (ckAddSystemWaterMark.Checked)
                    {
                        string waterMarkFolder = BillPrintHelper.SaveFilePath + "\\水印底单";
                        if (!DirectoryUtil.IsExistDirectory(waterMarkFolder))
                        {
                            DirectoryUtil.CreateDirectory(waterMarkFolder);
                        }
                        var files = DirectoryUtil.GetFileNames(BillPrintHelper.SaveFilePath);
                        foreach (string file in files)
                        {
                            if (Utilities.FileUtil.FileIsExist(file))
                            {
                                // img对象一定要释放,不然内存上升,杨恒连,2016年7月24日15:25:35
                                using (var img = ImageHelper.WatermarkText(Image.FromFile(file), BaseSystemInfo.SoftFullName, ImageHelper.WatermarkPosition.BottomRight, new Font("Verdana", 10, FontStyle.Bold), new SolidBrush(Color.Blue)))
                                {
                                    string fileName = Utilities.FileUtil.GetFileNameNoExtension(file);
                                    img.Save(string.Format(waterMarkFolder + "\\" + fileName + ".png", fileName));
                                }
                            }
                        }
                    }
                    // alertBuildImageInfo.Show(this, "生成底单", string.Format("成功生成{0}张底单图片", _list.Count));
                    //   XtraMessageBox.Show(string.Format("成功生成{0}张底单图片,是否打开文件夹查看?", _list.Count), AppMessage.MSG0000, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    //if ( == DialogResult.Yes)
                    //{
                    //    Process.Start(BillPrintHelper.SaveFilePath);
                    //}
                }
            }
            catch (Exception exception)
            {
                //   XtraMessageBox.Show(exception.Message, AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Error);
                LogUtil.WriteException(exception);
            }
            finally
            {
                btnBuildImage.Enabled = true;
                _tempIndex            = 0;
                if (_list != null)
                {
                    stopWatch.Stop();
                    TimeSpan ts          = stopWatch.Elapsed;
                    string   elapsedTime = string.Format("{0}分{1}秒{2}毫秒", ts.Minutes, ts.Seconds, ts.Milliseconds);
                    // http://blog.csdn.net/szstephenzhou/article/details/12838961
                    // 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
                    if (this.IsHandleCreated)
                    {
                        this.Invoke(updateControl, string.Format("{0}/{1}", _tempIndex, _list.Count) + "  耗时:" + elapsedTime);
                    }
                }
            }
        }
コード例 #21
0
        private void CopyNewFilesToPhysicalPath(DeployContext context)
        {
            context.Log.Info("Copying files...");

            DirectoryUtil.CopyDirectory(context.TempFolderWithNewVersionFiles, context.PhysicalPath);
        }
コード例 #22
0
ファイル: Manager.cs プロジェクト: KIZI/EasyMiner-LM-Connect
        public string Update()
        {
            var tasks     = new List <Task>();
            var directory = string.Format("{0}\\LISp Miner {1}", this.TargetPath, this.ReleaseDate.ToString("yyyy.MM.dd"));
            var current   = string.Format("{0}\\LISp Miner", this.TargetPath);

            this.CurrentVersionPath = directory;

            ConsoleLine.Append("Updating LISp Miner to version {0} from {1}", this.Version, this.ReleaseDate.ToShortDateString());
            ConsoleLine.Append("\tto destination: {0}", Path.GetFullPath(this.TargetPath));

            ConsoleLine.Append();

            if (Directory.Exists(directory))
            {
                Directory.Delete(directory, true);
            }

            Directory.CreateDirectory(directory);

            foreach (var package in Packages)
            {
                string source;
                string name;
                string destination;

                GetPackageInfo(package, directory, out name, out source, out destination);

                var line = ConsoleLine.Append("Downloading {0} ...", name);

                this.Lines.Add(name, line);

                var task = this.DownloadPackageAsync(destination, name, source);

                tasks.Add(task);
            }

            if (!Directory.Exists(this.DataFolder))
            {
                Directory.CreateDirectory(this.DataFolder);
            }

            foreach (var package in DataPackages)
            {
                string source;
                string name;
                string destination;

                GetPackageInfo(package, this.DataFolder, out name, out source, out destination);

                var line = ConsoleLine.Append("Downloading {0} ...", name);

                this.Lines.Add(name, line);

                var task = this.DownloadPackageAsync(destination, name, source);

                tasks.Add(task);
            }

            Task.WaitAll(tasks.ToArray());

            if (Directory.Exists(current))
            {
                Directory.Delete(current, true);
            }

            #region Setting LISp Miner version {0} as current.

            ConsoleLine.Append("Setting LISp Miner version {0} as current.", this.Version);

            DirectoryUtil.Copy(directory, current);

            #endregion

            return(ConsoleLine.GetBuffer());
        }
コード例 #23
0
ファイル: FrmDealPassword.cs プロジェクト: 15831944/winform-1
 private void btnBuild_Click(object sender, EventArgs e)
 {
     string[] filesNames = DirectoryUtil.GetFileNames(txtFilePath.Text.Trim());
 }
コード例 #24
0
 public void WhenDirectoryIsNullThenShouldThrowException()
 {
     //Assert
     Assert.ThrowsException <ArgumentNullException>(() => DirectoryUtil.GetFilesByRegex(null, ".txt", SearchOption.AllDirectories).ToList());
 }
コード例 #25
0
 private void GearLevelTidyTmp(string gearTmpDir)
 {
     DirectoryUtil.EmptyDirectory(gearTmpDir);
 }
コード例 #26
0
 public void WhenPatternIsNullThenShouldThrowException()
 {
     //Assert
     Assert.ThrowsException <ArgumentNullException>(() => { DirectoryUtil.GetFilesByRegex("Dummy", null, SearchOption.AllDirectories).ToList(); });
 }
コード例 #27
0
        //public void FileCopy(string sourceFileName, string targetFileName)
        //{
        //    File.Copy(sourceFileName, targetFileName);
        //}

        public IEnumerable <string> GetFiles(string directoryName, string[] fileFilters)
        {
            return(DirectoryUtil.GetFiles(directoryName, fileFilters));
        }
コード例 #28
0
        public override bool WriteData(IEnumerable <DataTable> tables, bool deleteBefore = false)
        {
            this.ValidateAndThrow();

            var xmlDoc       = new XmlDocument();
            var namespaceMgr = new XmlNamespaceManager(xmlDoc.NameTable);

            if (!string.IsNullOrEmpty(this.FileName))
            {
                DirectoryUtil.CreateDirectoryIfNotExists(Path.GetDirectoryName(this.FileName));

                if (deleteBefore)
                {
                    FileUtil.DeleteFileIfExists(this.FileName);
                }

                if (this.IsNewFile(this.FileName))
                {
                    // add Declaration
                    XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    xmlDoc.AppendChild(docNode);

                    // create base Path
                    XPathUtil.CreateXPath(xmlDoc, this.XPath);
                }
                else
                {
                    xmlDoc.Load(this.FileName);
                }
            }

            foreach (DataTable table in tables)
            {
                var xmlLines = this.WriteFormatter.Format(table, null) as IEnumerable <string>;

                int writtenRows = 0;
                int rowIdx      = 0;

                if (xmlLines != null)
                {
                    foreach (var xmlLine in xmlLines)
                    {
                        var lastNode = xmlDoc.SelectSingleNode(this.XPath + "[last()]", namespaceMgr);

                        if (lastNode != null)
                        {
                            // Append xml to the last node
                            var xmlDocFragment = xmlDoc.CreateDocumentFragment();
                            xmlDocFragment.InnerXml = xmlLine;
                            lastNode.AppendChild(xmlDocFragment);

                            writtenRows++;
                        }

                        rowIdx++;
                    }
                }
            }

            var settings = new XmlWriterSettings {
                Indent = true
            };
            XmlWriter writer = null;

            if (!string.IsNullOrEmpty(this.FileName))
            {
                writer = XmlWriter.Create(this.FileName, settings);
            }
            else if (this.DataStream != null)
            {
                writer = XmlWriter.Create(this.DataStream, settings);
            }
            else
            {
                return(false);
            }

            xmlDoc.Save(writer);

            writer.Close();
            writer.Dispose();

            return(true);
        }
コード例 #29
0
 private void CopyFiles(DeployContext context)
 {
     context.Log.Info($"Copying files from {context.TempFolderWithNewVersionFiles} to {_unit.Installable.TargetPath}...");
     DirectoryUtil.CopyDirectory(context.TempFolderWithNewVersionFiles, _unit.Installable.TargetPath);
 }
コード例 #30
0
 static Screenshoter()
 {
     DirectoryUtil.CreateDirectory(ResourcesUtil.ScreenshotsFolder);
 }