Example #1
0
        /// <summary>
        /// Check and duplicate the single slide ppt
        /// Copy to the destination
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="target"></param>
        public void CheckCopySlides(string origin, string target)
        {
            POWERPOINT.ApplicationClass ppt = new POWERPOINT.ApplicationClass();
            POWERPOINT.Presentation pres = ppt.Presentations.Open(
                    origin,
                    Microsoft.Office.Core.MsoTriState.msoTrue,
                    Microsoft.Office.Core.MsoTriState.msoTrue,
                    Microsoft.Office.Core.MsoTriState.msoFalse);

            if (pres.Slides.Count == 1)
            {
                pres.SaveAs(
                    target,
                    POWERPOINT.PpSaveAsFileType.ppSaveAsDefault,
                    Microsoft.Office.Core.MsoTriState.msoCTrue);

                pres.Slides[1].Copy();
                pres.Slides.Paste(2);
                pres.Save();
            }
            else
            {
                System.IO.FileInfo file = new System.IO.FileInfo(origin);
                file.CopyTo(target, true);
            }

            pres.Close();
            ppt.Quit();
        }
Example #2
0
        public byte[] FileToByteArray(string _FileName)
        {
            byte[] _Buffer = null;

            try
            {

                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

                // read entire file into buffer
                _Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes));
                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }

            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            return _Buffer;
        }
        internal CSharpProjectScriptSource(string path)
        {
            this.projectFile = new System.IO.FileInfo(path);
            fileContent = System.IO.File.ReadAllLines(projectFile.FullName);
            current = 0;
            while (current < fileContent.Length)
            {
                if (IsScriptDefinition(Line))
                {
                    string relativePathToScript = GetBitInQuotes();

                    string absolutePathToScript = System.IO.Path.Combine(projectFile.DirectoryName, relativePathToScript);
                    string scriptType = null;
                    if (absolutePathToScript.IndexOf("\\" + ScriptSource.UpdateScriptDir  + "\\") > -1) {scriptType = ScriptType.UpdateScript ;}
                    if (absolutePathToScript.IndexOf("\\" + ScriptSource.CreateScriptDir  + "\\" + ScriptSource.ProcedureSubDir + "\\") > -1) { scriptType = ScriptType.StoredProcedure; }
                    if (absolutePathToScript.IndexOf("\\" + ScriptSource.CreateScriptDir  + "\\" + ScriptSource.FunctionSubDir + "\\") > -1) { scriptType = ScriptType.UserDefinedFunction; }
                    if (absolutePathToScript.IndexOf("\\" + ScriptSource.CreateScriptDir  + "\\" + ScriptSource.ViewSubDir + "\\") > -1) { scriptType = ScriptType.View; }
                    if (absolutePathToScript.IndexOf("\\" + ScriptSource.CreateScriptDir  + "\\" + ScriptSource.TriggerSubDir + "\\") > -1) { scriptType = ScriptType.Trigger; }
                    if (absolutePathToScript.IndexOf("\\" + ScriptSource.DataScriptDir    + "\\") > -1) { scriptType = ScriptType.TableData; }
					if (absolutePathToScript.IndexOf("\\" + ScriptSource.OnSyncScriptDir + "\\") > -1) { scriptType = ScriptType.OnSync; }
                  
                    AddScript(scriptType, absolutePathToScript);
                }
                MoveToNextLine();
            }
        }
 public void runGame()
 {
     //throw new Exception("LOGGING IS OFF!");
     base_dir = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).Directory.FullName;
     AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
     AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
     var os = System.Environment.OSVersion;
     if (os.Version.Major > 5)
     {
         AppDomain.CurrentDomain.FirstChanceException += new EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs>(CurrentDomain_FirstChanceException);
     }
     try
     {
         var ass = System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes("GnomoriaModded.dll"));
         var ep = ass.EntryPoint;
         //var inst = ass.GetType("Game.GnomanEmpire").GetProperty("Instance").GetGetMethod().Invoke(null, new object[] { });
         //var obj = ass.CreateInstance(ep.Name);
         ep.Invoke(null, new object[] { new String[] { "-noassemblyresolve", "-noassemblyloading" } });
         return;
     }
     catch (Exception err)
     {
         CustomErrorHandler(err);
     }
 }
        public void init(Outlook.Attachment attach)
        {
            attachment = attach;
                System.IO.FileInfo fi = new System.IO.FileInfo(attachment.FileName);
                lNom.Text = "Nom : " + fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);
                lType.Text = "Type : " + fi.Extension.ToString();
                lTaille.Text = "Taille : " + attachment.Size + " o";

                IDictionary<string, string> parameters = new Dictionary<string, string>();
                parameters[SessionParameter.BindingType] = BindingType.AtomPub;

                XmlNode rootNode = Config1.xmlRootNode();

                parameters[SessionParameter.AtomPubUrl] = rootNode.ChildNodes.Item(0).InnerText + "atom/cmis";
                parameters[SessionParameter.User] = rootNode.ChildNodes.Item(1).InnerText;
                parameters[SessionParameter.Password] = rootNode.ChildNodes.Item(2).InnerText;

                SessionFactory factory = SessionFactory.NewInstance();
                ISession session = factory.GetRepositories(parameters)[0].CreateSession();

                // construction de l'arborescence
                string id = null;
                IItemEnumerable<IQueryResult> qr = session.Query("SELECT * from cmis:folder where cmis:name = 'Default domain'", false);

                foreach (IQueryResult hit in qr) { id = hit["cmis:objectId"].FirstValue.ToString(); }
                IFolder doc = session.GetObject(id) as IFolder;

                TreeNode root = treeView.Nodes.Add(doc.Id, doc.Name);
                AddVirtualNode(root);
        }
		public override void SetUp()
		{
			base.SetUp();
			if (this.__test_dir == null)
			{
                System.String tmp_dir = SupportClass.AppSettings.Get("tempDir", "");
				this.__test_dir = new System.IO.FileInfo(System.IO.Path.Combine(tmp_dir, "testIndexWriter"));
				
				bool tmpBool;
				if (System.IO.File.Exists(this.__test_dir.FullName))
					tmpBool = true;
				else
					tmpBool = System.IO.Directory.Exists(this.__test_dir.FullName);
				if (tmpBool)
				{
					throw new System.IO.IOException("test directory \"" + this.__test_dir.FullName + "\" already exists (please remove by hand)");
				}
				
				bool mustThrow = false;
				try
				{
					System.IO.Directory.CreateDirectory(this.__test_dir.FullName);
					if (!System.IO.Directory.Exists(this.__test_dir.FullName))
						mustThrow = true;
				}
				catch
				{
					mustThrow = true;
				}

				if (mustThrow)
					throw new System.IO.IOException("unable to create test directory \"" + this.__test_dir.FullName + "\"");
			}
		}
Example #7
0
        private void cc_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog d = new Microsoft.Win32.OpenFileDialog();
            d.Filter = "JPEG Image (*.JPG)|*.JPG";
               bool? result =  d.ShowDialog(this);
               if (result == true)
               {
               System.IO.FileInfo fi = new System.IO.FileInfo(d.FileName);
               //fi.CopyTo("..\\..\\Resources\\"+fi.Name,true);
               XmlDataProvider xdp = this.Resources["BookData"] as XmlDataProvider;
               System.Xml.XmlElement xe = (System.Xml.XmlElement)(e.Source as System.Windows.Controls.ContentControl).Content;
               if (xe["Image"] != null)
               {
                   xe["Image"].InnerText = fi.FullName;
                   //System.Xml.XmlTextWriter xr = new System.Xml.XmlTextWriter(new System.IO.FileStream(@"C:\a.txt", System.IO.FileMode.OpenOrCreate), Encoding.Unicode);
                   //xe.WriteTo(xr);
                   //xr.Close();

               }
               else
               {
                   System.Xml.XPath.XPathNavigator navigator = xe.CreateNavigator();
                   navigator.AppendChildElement(null, "Image", null, fi.FullName);
                   this.listBox.Items.Refresh();
               }
               }
        }
Example #8
0
        public void RoyaltyFileStorage_PutGetDeleteFile()
        {
            var fileId = Guid.NewGuid();
            var fileName = "test.jpg";
            var fileName2 = "test2.jpg";

            using (var fileStream = System.IO.File.OpenRead(fileName))
            { 
                var info = storage.FilePut(fileId, fileStream, fileName);
                Console.WriteLine("File stored in: {0}", info.FullName);
                try
                {
                    Assert.AreNotEqual(0, info.Length, "File length must be more then 0");
                    using (var res = storage.FileGet(fileId))
                    using (var fs = System.IO.File.OpenWrite(fileName2))
                    {
                        res.CopyTo(fs);
                    }
                    var info2 = new System.IO.FileInfo(fileName2);
                    Assert.AreEqual(info.Length, info2.Length, "Length must equals");
                    System.IO.File.Delete(fileName2);
                }
                finally
                {
                    storage.FileDelete(fileId);
                }
            }
        }
        void LoadPicture()
        {
            this.OpenFile.Filter = "Images | *.jpg; *.png; *.jpeg";

            DialogResult result = this.OpenFile.ShowDialog();

            if ( result == DialogResult.OK )
            {
                string src = this.OpenFile.FileName;

                System.IO.FileInfo info = new System.IO.FileInfo( src );

                if ( ( info.Length / 1048576 ) < 1.5 )
                {
                    this.ptbPicture.Load( src );
                    this.lblSource.Text = src;
                    this._source = src;
                    this.btnCambiar.Enabled = true;
                    this.btnSalir.Enabled = true;
                }
                else
                {
                    MetroMessageBox.Show( this, "El Tamaño maximo para una imagen es de 1.5MB.", "LA imagen a superado el tamaño Maximo", MessageBoxButtons.OK, MessageBoxIcon.Warning );
                }
            }
        }
Example #10
0
        internal Stat fstat(string path)
        {
            System.IO.FileSystemInfo fsi;
            if (System.IO.Directory.Exists(path))
                fsi = new System.IO.DirectoryInfo(path);
            else if (System.IO.File.Exists(path))
                fsi = new System.IO.FileInfo(path);
            else
                throw SystemCallError.rb_sys_fail(path, new System.IO.FileNotFoundException("", path), null).raise(null);

            Stat st = new Stat();
            st.fsi = fsi;
            st.st_dev = (int)fsi.FullName.ToCharArray(0,1)[0];  // drive letter as int, what to do for networked files?
            st.st_ino = 0; // no inode on win32
            st.st_mode = 0;
            st.st_nlink = 1; // no symbolic link support on win32
            st.st_uid = 0;  // no uid in win32
            st.st_gid = 0; // no gid in win32
            //st.st_rdev = 0; // no rdev in win32
            st.st_size = (fsi is System.IO.FileInfo) ? ((System.IO.FileInfo)fsi).Length : 0;
            //st.st_blksize = 0; // no blksize in win32
            //st.st_blocks = 0; // no blocks in win32
            st.st_atime = fsi.LastAccessTime;
            st.st_mtime = fsi.LastWriteTime;
            st.st_ctime = fsi.CreationTime;

            return st;
        }
Example #11
0
 internal static string GetCurrentPageName()
 {
     string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
     System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
     string sRet = oInfo.Name;
     return sRet;
 }
Example #12
0
        private System.Collections.Generic.List<string> getFiles(string location, bool recursive)
        {
            System.Collections.Generic.List<string>  sc = new List<string>();

            System.IO.FileInfo fi = new System.IO.FileInfo(location);

            if(fi.Exists)
            {
                sc.Add(fi.FullName);
                return sc;
            }

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(location);

            if(di.Exists)
            {
                foreach(System.IO.FileInfo f in di.GetFiles())
                {
                    foreach(string s in getFiles(f.FullName,recursive))
                        sc.Add(s);
                }

                if(recursive)
                {
                    foreach(System.IO.DirectoryInfo d in di.GetDirectories())
                    {
                        foreach(string s in getFiles(d.FullName,recursive))
                            sc.Add(s);
                    }
                }
            }

            return sc;
        }
Example #13
0
        public Log4NetProvider()
        {
            GlobalContext.Properties["appname"] = "TutorGroup.Api";

            try
            {
                var codeBaseUri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
                var fileInfo = new System.IO.FileInfo(codeBaseUri.AbsolutePath);
                if (fileInfo.DirectoryName != null)
                {
                    var newConfigFilePath = System.IO.Path.Combine(fileInfo.DirectoryName, "ConfigurationFiles", "Logging/log4net/log4net.config");

                    if (System.IO.File.Exists(newConfigFilePath))
                    {
                        log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(newConfigFilePath));
                    }
                    else
                    {
                        throw new Exception("Log4net config file missing Error:");
                    }
                }
                else
                {
                    throw new Exception("Log4net config file missing Error:");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Log4net Initialize Error:" + ex.Message, ex);
            }

            GetLogger(DEFAULT_LOGGER);
        }
        public bool AddFile(string localFilePath, int roomId)
        {
            var roomsApi = getRoomsApi();
            string fileId = null;
            int maxFileSize = 10000000; // bytes.. 10 MB
            System.IO.FileInfo fi = new System.IO.FileInfo(localFilePath);
            if (!fi.Exists)
            {
                _lastError = "File doesn't exist.";
            }
            else if (fi.Length > maxFileSize)
            {
                _lastError = "File size cannot be greater than " + maxFileSize + " bytes.";
            }
            else
            {
                string fileName = fi.Name;
                byte[] fileContent = new byte[fi.Length];
                System.IO.Stream str = fi.OpenRead();
                str.Read(fileContent, 0, Convert.ToInt32(fi.Length));
                string fileData = Convert.ToBase64String(fileContent);
                var result = roomsApi.PostFile(getAuthHeader(), roomId, 0, fileName, fileData);
                if (result.success && result.data != null) fileId = result.data.ToString();
                else _lastError = result.code.ToString();
                str.Close();
                str.Dispose();
            }

            return fileId != null;
        }
Example #15
0
        public List<string[]> Read()
        {
            try {
                System.IO.FileInfo backlogFile = new System.IO.FileInfo(SQ.Util.Constant.BACKLOG_FILE);
                if (!backlogFile.Exists){
                    backlogFile.Create();
                    return new List<string[]>();
                }

                System.IO.StreamReader sr = new System.IO.StreamReader (SQ.Util.Constant.BACKLOG_FILE);
                Repo.LastSyncTime = backlogFile.LastWriteTime;
                List<string[]> filesInBackLog = new List<string[]>();
                int i = 1;
                while (!sr.EndOfStream) {
                    string [] info = BreakLine (sr.ReadLine (), 5);
                    filesInBackLog.Add (info);
                    i++;
                }
                sr.Dispose();
                sr.Close ();
                return filesInBackLog;
            } catch (Exception e) {
                SQ.Util.Logger.LogInfo("Sync", e);
                return null;
            }
        }
Example #16
0
		internal static System.String GetFileName ( System.String name ) {
			if ( name==null || name.Length==0 )
				return name;
			name = name.Replace("\t", "");
			try {
				name = System.IO.Path.GetFileName(name);
			} catch ( System.ArgumentException ) {
				// Remove invalid chars
				foreach ( char ichar in System.IO.Path.GetInvalidPathChars() ) {
					name = name.Replace ( ichar.ToString(), System.String.Empty );
				}
				name = System.IO.Path.GetFileName(name);
			}
			try {
				System.IO.FileInfo fi = new System.IO.FileInfo(name);
				if ( fi!=null )
					fi = null;
			} catch ( System.ArgumentException ) {
				name = null;
#if LOG
				if ( log.IsErrorEnabled ) {
					log.Error(System.String.Concat("Filename [", name, "] is not allowed by the filesystem"));
				}
#endif
			}
			return name;
		}
Example #17
0
 public static void addLog(string s)
 {
     System.Diagnostics.Debug.WriteLine(s);
     if (bDoLogging)
     {
         try
         {
             if (System.IO.File.Exists(LogFilename))
             {
                 System.IO.FileInfo fi = new System.IO.FileInfo(LogFilename);
                 if (fi.Length > maxFileSize)
                 {
                     //create backup file
                     System.IO.File.Copy(LogFilename, LogFilename + "bak", true);
                     System.IO.File.Delete(LogFilename);
                 }
             }
             System.IO.StreamWriter sw = new System.IO.StreamWriter(LogFilename, true);
             sw.WriteLine(DateTime.Now.ToShortDateString()+ " " + DateTime.Now.ToShortTimeString() + "\t" + s);
             sw.Flush();
             sw.Close();
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine("Exception in addLog FileWrite: " + ex.Message);
         }
     }
 }
Example #18
0
        public void ProcessRequest(HttpContext context)
        {
            string templateDir = context.Request.FilePath.Substring(context.Request.FilePath.LastIndexOf('/'));
            templateDir = templateDir.Substring(0, templateDir.IndexOf('.'));
            templateDir = string.Concat("~/Templates", templateDir);

            string path = context.Request.PathInfo;

            path = Regex.Replace(path, @"\.v\d+\.", ".");
            path = templateDir + path;
            string physicalPath = context.Server.MapPath(path);
            System.IO.FileInfo info = new System.IO.FileInfo(physicalPath);

            string mime = null;

            extensions.TryGetValue(info.Extension, out mime);

            if (mime != null && info.Exists)
            {
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.Cache.SetExpires(DateTime.Now.AddDays(1));
                context.Response.Cache.SetLastModified(info.LastWriteTime);
                context.Response.Cache.SetOmitVaryStar(true);
                context.Response.ContentType = mime;
                context.Response.TransmitFile(physicalPath);
            }
            else
            {
                context.Response.StatusCode = 404;
                context.Response.Write("File not found.");
            }
        }
        public static void SmartTagAdvancedUsage4_Attachment(ServiceClient client)
        {
            var attachment= new System.IO.FileInfo(SampleParameters.Path2AttachmentFile);
            var attachmentReference = client.uploadAttachmentFile(attachment);

            var file = new System.IO.FileInfo(SampleParameters.Path2SmartTagDocument);
            var documentReference = client.uploadDocumentFile(file);

            var signers = new SmartTagInvitee[]
            {
                new SmartTagInvitee
                {
                    FirstName=SampleParameters.Invitee1_FirstName,
                    LastName=SampleParameters.Invitee1_LastName,
                    Email=SampleParameters.Invitee1_Email,
                    //if sms needed
                    //MobileCountry=SampleParameters.Invitee1_MobileCountry,
                    //MobileNumber=SampleParameters.Invitee1_MobileNumber,
                    Attachments=new List<string>
                    {
                        attachmentReference
                    }                  
                }
            };

            var smartTagResp = client.sendSmartTagDocument(new List<string> {
                documentReference
            }, DateTime.Now.AddDays(7), signers);
        }
        public override void ProcessRequest(WebRequest request)
        {
            System.IO.FileInfo info = null;
            if (!String.IsNullOrEmpty(Terraria.Main.worldPathName))
            {
                info = new System.IO.FileInfo(Terraria.Main.worldPathName);
            }

            request.Writer.Buffer(Terraria.Main.worldName ?? String.Empty);
            request.Writer.Buffer(Terraria.Main.maxTilesX);
            request.Writer.Buffer(Terraria.Main.maxTilesY);

            if (info != null && info.Exists)
            {
                request.Writer.Buffer(info.Length);
            }
            else
            {
                request.Writer.Buffer(0L);
            }

            request.Writer.Buffer(Heartbeat.Enabled);
            request.Writer.Buffer(Heartbeat.ServerName);
            request.Writer.Buffer(Heartbeat.ServerDescription);
            request.Writer.Buffer(Heartbeat.ServerDomain);
            request.Writer.Buffer(Heartbeat.PublishToList);

            request.WriteOut();
        }
Example #21
0
        /// <summary>
        /// Get the size of the file as a string in format n Byte(s), n KB, n MB
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static string GetFileSize(string FileName)
        {
            try
            {
                // Open the file for getting the size and then close it                        
                System.IO.FileInfo f = new System.IO.FileInfo(FileName);
                float size = f.Length;

                string sizeStr = "";

                if (size < 1024)
                {
                    sizeStr = size + " Byte(s)";
                }
                else if (size >= 1024 && size < (1024 * 1024))
                {
                    size = size / 1024;
                    sizeStr = Math.Round(size, 1) + " KB";
                }
                else
                {
                    size = size / (1024 * 1024);
                    sizeStr = Math.Round(size, 1) + " MB";
                }

                return sizeStr;
            }
            catch { }
            return "";
        }
Example #22
0
        private void InitLangs()
        {
            bEdit.IsEnabled = (lb.SelectedItem != null);
            lb.Items.Clear();

            var a = System.IO.Directory.GetFiles("Languages", "*.ulex");
            var LstA = new List<string>();
            foreach (var i in a) {
                var u = new System.IO.FileInfo(i).Name;
                u = u.Remove(u.LastIndexOf('.'));
                LstA.Add(u);
            }
            if (System.IO.Directory.GetFiles(Shared.LocalData("Languages")).Length > 0) {
                a = System.IO.Directory.GetFiles(Shared.LocalData("Languages\\"), "*.ulex");
                foreach (var i in a) {
                    var u = new System.IO.FileInfo(i).Name;
                    u = u.Remove(u.LastIndexOf('.'));
                    if (LstA.Contains(u)) LstA.Remove(u);
                    LstA.Add(u);
                }
            }
            foreach (var u in LstA) {
                lb.Items.Add(new Language(u));
            }

        }
Example #23
0
        protected void Application_Start()
        {
            string configFileName = Server.MapPath("~/log.log4net");
            System.IO.FileInfo f = new System.IO.FileInfo(configFileName);
            LogHelper.LogHelper.SetConfig(f, "");
            LogHelper.LogHelper.Info("App Start");

            SqlHelper.SetConnString(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            System.Data.Entity.Database.SetInitializer<OUDAL.Context>(null);
            Application["Login"] = System.Configuration.ConfigurationManager.AppSettings["Login"];
            RootPath = System.Configuration.ConfigurationManager.AppSettings["path"];

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            try
            {
                ClientBLL.AutoTransfer();
            }
            catch (Exception e)
            {

            }
            BundleMobileConfig.RegisterBundles(BundleTable.Bundles);

            //RealEstateCRM.Web.BLL.SynchronismWorkflow.SynchronishJob.Schedule();
        }
 protected void Application_Start()
 {
     GlobalConfiguration.Configure(WebApiConfig.Register);
     System.IO.FileInfo configFile = new System.IO.FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + "\\web.config");
     log4net.Config.XmlConfigurator.Configure(configFile);
     CharityPlatform.Data.AppHelper.Init();
 }
Example #25
0
        protected void itemSelectedBuild(object sender, EventArgs e)
        {
            try
            {
                System.String filename = "myFile.txt";

                // set the http content type to "APPLICATION/OCTET-STREAM
                Response.ContentType = "APPLICATION/OCTET-STREAM";

                // initialize the http content-disposition header to
                // indicate a file attachment with the default filename
                // "myFile.txt"
                System.String disHeader = "Attachment; Filename=\"" + filename +
                   "\"";
                Response.AppendHeader("Content-Disposition", disHeader);

                // transfer the file byte-by-byte to the response object
                System.IO.FileInfo fileToDownload = new
                   System.IO.FileInfo("C:\\downloadJSP\\DownloadConv\\myFile.txt");
                Response.Flush();
                Response.WriteFile(fileToDownload.FullName);
            }
            catch (System.Exception exc)
            // file IO errors
            {
            }
        }
Example #26
0
        internal static void CreateDatabase(string DbFile)
        {
            string path = new System.IO.FileInfo(DbFile).DirectoryName;
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            SQLiteConnection.CreateFile(DbFile);

            using(SQLiteConnection conn = new SQLiteConnection(@"Data Source={0};Version=3;".FormatStr(DbFile))){
                conn.Open();
                foreach (Match match in Regex.Matches(Resources.Files.CreateDatabase_sql, @"(.*?)(([\s]+GO[\s]*)|$)", RegexOptions.Singleline | RegexOptions.IgnoreCase))
                {
                    string sql = match.Value.Trim();
                    if (sql.ToUpper().EndsWith("GO"))
                        sql = sql.Substring(0, sql.Length - 2).Trim();
                    if (sql.Length == 0)
                        continue;
                    using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                using(SQLiteCommand cmd = new SQLiteCommand("INSERT INTO [version](databaseversion) VALUES ({0})".FormatStr(Globals.DB_VERSION), conn))
                {
                    cmd.ExecuteNonQuery();
                }
                conn.Close();
            }

            DbHelper.DbFile = DbFile;
        }
        public static void ShowAddPackageDialog(string selectedFileName, string projectGuid = null)
        {
            Paket.Dependencies dependenciesFile = null;

            try
            {
                dependenciesFile = Paket.Dependencies.Locate(selectedFileName);
            }
            catch (Exception)
            {
                var dir = new System.IO.FileInfo(SolutionExplorerExtensions.GetSolutionFileName()).Directory.FullName;
                Dependencies.Init(dir);
                dependenciesFile = Paket.Dependencies.Locate(selectedFileName);
            }

            var secondWindow = new AddPackage();

            //Create observable paket trace
            var paketTraceObs = Observable.Create<Logging.Trace>(observer =>
            {
                [email protected](x => observer.OnNext(x));
                return Disposable.Create(() =>
                {
                   
                });
               
            });

            Action<NugetResult> addPackageToDependencies = result =>
            {
                if (projectGuid != null)
                {
                    var guid = Guid.Parse(projectGuid);
                    SolutionExplorerExtensions.UnloadProject(guid);
                    dependenciesFile.AddToProject(Microsoft.FSharp.Core.FSharpOption<string>.None, result.PackageName, "", false, false, false, false, selectedFileName, true, SemVerUpdateMode.NoRestriction);
                    SolutionExplorerExtensions.ReloadProject(guid);
                }
                else
                    dependenciesFile.Add(Microsoft.FSharp.Core.FSharpOption<string>.None, result.PackageName, "", false, false, false, false, false, true, SemVerUpdateMode.NoRestriction);
            };

            Func<string, IObservable<string>> searchNuGet = 
                searchText => Observable.Create<string>(obs =>
                {
                    var disposable = new CancellationDisposable();

                    dependenciesFile
                        .SearchPackagesByName(
                            searchText,
                            FSharpOption<CancellationToken>.Some(disposable.Token),
                            FSharpOption<int>.None)
                        .Subscribe(obs);

                    return disposable;
                });
          
            //TODO: Use interfaces?
            secondWindow.ViewModel = new AddPackageViewModel(searchNuGet, addPackageToDependencies, paketTraceObs);
            secondWindow.ShowDialog();
        }
Example #28
0
 private void BrowseButton_Click(object sender, EventArgs e)
 {
     var path = "";
     GameApplicationOpenFileDialog.DefaultExt = ".exe";
     if (!string.IsNullOrEmpty(GameApplicationLocationTextBox.Text))
     {
         var fi = new System.IO.FileInfo(GameApplicationLocationTextBox.Text);
         if (string.IsNullOrEmpty(path)) path = fi.Directory.FullName;
         GameApplicationOpenFileDialog.FileName = fi.Name;
     }
     GameApplicationOpenFileDialog.Filter = Helper.GetFileDescription(".exe") + " (*.exe)|*.exe|All files (*.*)|*.*";
     GameApplicationOpenFileDialog.FilterIndex = 1;
     GameApplicationOpenFileDialog.RestoreDirectory = true;
     if (string.IsNullOrEmpty(path)) path = System.IO.Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
     GameApplicationOpenFileDialog.InitialDirectory = path;
     GameApplicationOpenFileDialog.Title = "Browse for Executable";
     var result = GameApplicationOpenFileDialog.ShowDialog();
     if (result == System.Windows.Forms.DialogResult.OK)
     {
         // Don't allow to add windows folder.
         var winFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Windows);
         if (GameApplicationOpenFileDialog.FileName.StartsWith(winFolder))
         {
             MessageBoxForm.Show("Windows folders are not allowed.", "Windows Folder", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else
         {
             GameApplicationLocationTextBox.Text = GameApplicationOpenFileDialog.FileName;
             ProcessExecutable(GameApplicationOpenFileDialog.FileName);
         }
     }
 }
Example #29
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //read config
            string PathDB = Logs.getPath() + "\\DB\\quran.db";
            System.IO.FileInfo ConFile = new System.IO.FileInfo(PathDB);
            if (!ConFile.Exists)
            {
                MessageBox.Show("Database not found.");
                Application.Current.Shutdown();

            }
            string ConStr = string.Format("Data Source={0};Version=3;", ConFile.FullName);
            BLL.quran_data.Conn = ConStr;

            //string ConStr = ConfigurationManager.ConnectionStrings["quran_context"].ConnectionString;
            //UrlRecitation = ConfigurationManager.AppSettings["UrlRecitation"];

            //player events
            QuranPlayer.MediaFailed += media_MediaFailed;
            QuranPlayer.MediaEnded += QuranPlayer_MediaEnded;

            //button events
            StopBtn.Click += StopBtn_Click;
            PlayBtn.Click += PlayBtn_Click;
            NextBtn.Click += NextBtn_Click;
            PrevBtn.Click += PrevBtn_Click;
            BookmarkBtn.Click += BookmarkBtn_Click;
            //QFE.WPF.Tools.CacheManager<string> Cache = new Tools.CacheManager<string>();
            //Cache["hosni"] = "gendut";
            //MessageBox.Show(Cache["hosni"]);

            InitQuran();

            //Init speech recognizer
            manualResetEvent = new ManualResetEvent(false);

            ListenToBoss();

            /*
            //real sense start
            cam = Camera.Create(); //autodiscovers your sdk (perceptual or realsense)

            //cam.Face.Visible += Face_Visible;
            //cam.Face.NotVisible += Face_NotVisible;
            cam.Gestures.SwipeLeft += Gestures_SwipeLeft;
            cam.Gestures.SwipeRight += Gestures_SwipeRight;
            //cam.Gestures.SwipeUp += Gestures_SwipeUp;
            //cam.Gestures.SwipeDown += Gestures_SwipeDown;
            cam.RightHand.Moved += RightHand_Moved;
            cam.LeftHand.Moved += LeftHand_Moved;
            cam.Start();


            //timer for human detection
            dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, CurrentState.config.ShutdownTime, 0);
            dispatcherTimer.Start();
            */
        }
Example #30
0
 public static string GetCurrentPageName(string URL)
 {
     //string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
     System.IO.FileInfo oInfo = new System.IO.FileInfo(URL);
     string sRet = oInfo.Name;
     return sRet;
 }
Example #31
0
        public Duplicati.Library.Interface.IBackupResults Backup(string[] inputsources, IFilter filter = null)
        {
            Library.UsageReporter.Reporter.Report("USE_BACKEND", new Library.Utility.Uri(m_backend).Scheme);
            Library.UsageReporter.Reporter.Report("USE_COMPRESSION", m_options.CompressionModule);
            Library.UsageReporter.Reporter.Report("USE_ENCRYPTION", m_options.EncryptionModule);

            return(RunAction(new BackupResults(), ref inputsources, ref filter, (result) => {
                if (inputsources == null || inputsources.Length == 0)
                {
                    throw new Exception(Strings.Controller.NoSourceFoldersError);
                }

                var sources = new List <string>(inputsources);

                //Make sure they all have the same format and exist
                for (int i = 0; i < sources.Count; i++)
                {
                    try
                    {
                        sources[i] = System.IO.Path.GetFullPath(sources[i]);
                    }
                    catch (Exception ex)
                    {
                        throw new ArgumentException(Strings.Controller.InvalidPathError(sources[i], ex.Message), ex);
                    }

                    var fi = new System.IO.FileInfo(sources[i]);
                    var di = new System.IO.DirectoryInfo(sources[i]);
                    if (!(fi.Exists || di.Exists) && !m_options.AllowMissingSource)
                    {
                        throw new System.IO.IOException(Strings.Controller.SourceIsMissingError(sources[i]));
                    }

                    if (!fi.Exists)
                    {
                        sources[i] = Library.Utility.Utility.AppendDirSeparator(sources[i]);
                    }
                }

                //Sanity check for duplicate folders and multiple inclusions of the same folder
                for (int i = 0; i < sources.Count - 1; i++)
                {
                    for (int j = i + 1; j < sources.Count; j++)
                    {
                        if (sources[i].Equals(sources[j], Library.Utility.Utility.IsFSCaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase))
                        {
                            result.AddVerboseMessage("Removing duplicate source: {0}", sources[j]);
                            sources.RemoveAt(j);
                            j--;
                        }
                        else if (sources[i].StartsWith(sources[j], Library.Utility.Utility.IsFSCaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase))
                        {
                            bool includes;
                            bool excludes;

                            FilterExpression.AnalyzeFilters(filter, out includes, out excludes);

                            // If there are no excludes, there is no need to keep the folder as a filter
                            if (excludes)
                            {
                                result.AddVerboseMessage("Removing source \"{0}\" because it is a subfolder of \"{1}\", and using it as an include filter", sources[i], sources[j]);
                                filter = Library.Utility.JoinedFilterExpression.Join(new FilterExpression(sources[i]), filter);
                            }
                            else
                            {
                                result.AddVerboseMessage("Removing source \"{0}\" because it is a subfolder of \"{1}\"", sources[i], sources[j]);
                            }

                            sources.RemoveAt(i);
                            i--;
                            break;
                        }
                    }
                }

                using (var h = new Operation.BackupHandler(m_backend, m_options, result))
                    h.Run(sources.ToArray(), filter);

                Library.UsageReporter.Reporter.Report("BACKUP_FILECOUNT", result.ExaminedFiles);
                Library.UsageReporter.Reporter.Report("BACKUP_FILESIZE", result.SizeOfExaminedFiles);
                Library.UsageReporter.Reporter.Report("BACKUP_DURATION", (long)result.Duration.TotalSeconds);
            }));
        }
Example #32
0
        /// <summary>
        /// 导出患者费用信息
        /// </summary>
        /// <param name="alFeeDetail">费用信息</param>
        /// <param name="p">患者信息</param>
        /// <param name="errTxt">错误信息</param>
        /// <returns>1成功 -1失败</returns>
        public int ExportInpatientFeedetail(string path, string tablename, Neusoft.HISFC.Models.RADT.Patient p, ArrayList alFeeDetail, ref string errTxt)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            //try
            //{
            //    foreach (string file in System.IO.Directory.GetFiles(path))
            //    {
            //        System.IO.File.Delete(file);
            //    }
            //}
            //catch { }


            string connect = @"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277; Dbq=" + path;

            System.Data.Odbc.OdbcConnection myconn = new System.Data.Odbc.OdbcConnection(connect);

            string drop = "drop table " + tablename;

            string create = "create table " + tablename +
                            @"(GRSHBZH CHAR(20) , ZYH CHAR(12) , XMXH NUMERIC , XMBH CHAR(15) , XMMC CHAR(40) , FLDM CHAR(3),
                        YPGG CHAR(15),YPJX CHAR(8), JG NUMERIC , MCYL NUMERIC , JE NUMERIC , ZFBL NUMERIC ,
                        ZFJE NUMERIC , CZFBZ CHAR(3) , BZ1 CHAR(20) , BZ2 CHAR(20) , BZ3 CHAR(20))";


            System.Data.Odbc.OdbcCommand cmDrop   = new System.Data.Odbc.OdbcCommand(drop, myconn);
            System.Data.Odbc.OdbcCommand cmCreate = new System.Data.Odbc.OdbcCommand(create, myconn);

            myconn.Open();

            //try
            //{
            //    cmDrop.ExecuteNonQuery();
            //}
            //catch { }
            try
            {
                cmCreate.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                errTxt = "导出文件出错" + ex.Message;
                return(-1);
            }


            System.Data.Odbc.OdbcCommand cmInsert = new System.Data.Odbc.OdbcCommand();
            cmInsert.Connection = myconn;
            int i = 1;

            //System.Data.Odbc.OdbcTransaction trans = myconn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);

            foreach (Neusoft.HISFC.Models.Fee.Inpatient.FeeItemList f in alFeeDetail)
            {
                string insert = "insert into " + tablename +
                                @"(GRSHBZH, ZYH, XMXH, XMBH , XMMC , FLDM ,YPGG ,YPJX ,JG , MCYL, JE, ZFBL,ZFJE, CZFBZ, BZ1, BZ2, BZ3
                )
                values
                (
                  '{0}','{1}',{2},'{3}', '{4}', '{5}','{6}','{7}',{8},{9},{10},{11},{12},'{13}','{14}','{15}','{16}'
                )";



                //传过去的价格应该是优惠之后的价格
                try
                {
                    insert = string.Format(insert, p.IDCard, p.PID.PatientNO, f.Item.User02, f.Item.UserCode, f.Item.Name, f.Item.SysClass.Name, f.Item.Specs, f.Item.User01,
                                           f.Item.Price, f.NoBackQty, f.FT.OwnCost, 0, 0, 0, "", "", "");
                }
                catch (Exception ex)
                {
                    //trans.Rollback();
                    errTxt = "导出文件出错" + ex.Message;
                    return(0);
                }
                i++;
                cmInsert.CommandText = insert;
                //cmInsert.Transaction = trans;
                try
                {
                    cmInsert.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    //trans.Rollback();
                    errTxt = "导出文件出错" + ex.Message;
                    return(-1);
                }
            }
            //trans.Commit();
            cmInsert.Dispose();
            cmCreate.Dispose();
            cmDrop.Dispose();
            myconn.Close();
            try
            {
                string file = System.IO.Directory.GetFiles(path)[0];

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
                fileInfo.MoveTo(path + @"\" + tablename);
            }
            catch { }
            return(1);
        }
        public ActionResult listele(int?galeri_id)
        {
            // query stringte  resim_sil varsa silme işlemini yap
            if (Request.QueryString["resim_sil"] != null)
            {
                int r_id = Convert.ToInt32(Request.QueryString["resim_sil"]);


                GALERI_RESIMLERI galeri = data.GALERI_RESIMLERIs.First(f => f.ID == r_id);

                try
                {
                    System.IO.FileInfo res = new System.IO.FileInfo(Server.MapPath("~") + "Content\\img\\galeri\\" + galeri.RESIM);
                    res.Delete();

                    System.IO.FileInfo temp = new System.IO.FileInfo(Server.MapPath("~") + "Content\\img\\galeri\\t_" + galeri.RESIM);
                    temp.Delete();
                }  catch { }


                try
                {
                    data.GALERI_RESIMLERIs.DeleteOnSubmit(galeri);
                    data.SubmitChanges();

                    mesaj[0]      = "alert-info"; mesaj[1] = "Galeri resmi başarıyla silindi..";
                    ViewBag.mesaj = mesaj;
                }
                catch
                {
                    mesaj[0]      = "alert-error"; mesaj[1] = "Silme işlemi sırasında gata oluştu !";
                    ViewBag.mesaj = mesaj;
                }
            }
            ////////////////////////////////////////////////////////////////////////////////////////


            // query stringde galeri_sil varsa galeriyi sil
            if (Request.QueryString["galeri_sil"] != null)
            {
                int g_id = Convert.ToInt32(Request.QueryString["galeri_sil"]);

                try
                {
                    GALERILER galeri = data.GALERILERs.First(f => f.ID == g_id);
                    data.GALERILERs.DeleteOnSubmit(galeri);
                    data.SubmitChanges();

                    mesaj[0]      = "alert-info"; mesaj[1] = "Resim galerisi başarıyla silindi..";
                    ViewBag.mesaj = mesaj;
                }
                catch
                {
                    mesaj[0]      = "alert-error"; mesaj[1] = "Silme işlemi sırasında gata oluştu !";
                    ViewBag.mesaj = mesaj;
                }
            }
            /////////////////////////////////////////////////////////////



            // id yoksa tüm resimleri listele

            if (galeri_id == null)
            {
                ViewBag.Galeri_Resimleri = data.GALERI_RESIMLERIs.OrderBy(f => f.SIRA_NO);
            }
            else
            {
                ViewBag.Galeri_Resimleri = data.GALERI_RESIMLERIs.Where(f => f.GALERI_ID == galeri_id).OrderBy(f => f.SIRA_NO);
            }

            return(View());
        }
Example #34
0
 public static System.Drawing.Icon GetFileIcon(this System.IO.FileInfo fileInfo)
 {
     return(GetFileIcon(fileInfo, eIconSize.Small));
 }
Example #35
0
        public static void  Main(System.String[] argv)
        {
            try
            {
                System.IO.FileInfo index = new System.IO.FileInfo("index");
                bool create             = false;
                System.IO.FileInfo root = null;

                System.String usage = "IndexHTML [-create] [-index <index>] <root_directory>";

                if (argv.Length == 0)
                {
                    System.Console.Error.WriteLine("Usage: " + usage);
                    return;
                }

                for (int i = 0; i < argv.Length; i++)
                {
                    if (argv[i].Equals("-index"))
                    {
                        // parse -index option
                        index = new System.IO.FileInfo(argv[++i]);
                    }
                    else if (argv[i].Equals("-create"))
                    {
                        // parse -create option
                        create = true;
                    }
                    else if (i != argv.Length - 1)
                    {
                        System.Console.Error.WriteLine("Usage: " + usage);
                        return;
                    }
                    else
                    {
                        root = new System.IO.FileInfo(argv[i]);
                    }
                }

                if (root == null)
                {
                    System.Console.Error.WriteLine("Specify directory to index");
                    System.Console.Error.WriteLine("Usage: " + usage);
                    return;
                }

                System.DateTime start = System.DateTime.Now;

                if (!create)
                {
                    // delete stale docs
                    deleting = true;
                    IndexDocs(root, index, create);
                }
                writer = new IndexWriter(FSDirectory.Open(index), new StandardAnalyzer(Version.LUCENE_CURRENT), create, new IndexWriter.MaxFieldLength(1000000));
                IndexDocs(root, index, create);                 // add new docs

                System.Console.Out.WriteLine("Optimizing index...");
                writer.Optimize();
                writer.Close();

                System.DateTime end = System.DateTime.Now;

                System.Console.Out.Write(end.Millisecond - start.Millisecond);
                System.Console.Out.WriteLine(" total milliseconds");
            }
            catch (System.Exception e)
            {
                System.Console.Error.WriteLine(e.StackTrace);
            }
        }
 private static void Save()
 {
     System.IO.FileInfo filedir = new System.IO.FileInfo(_permissionsLocation);
     filedir.Directory.Create();
     System.IO.File.WriteAllText(_permissionsLocation, Helpers.Serialize <List <LevelPermission> >(_perms));
 }
Example #37
0
 public DressingClassifyByImageFileRequest(System.IO.FileInfo imageFile, string loc = "0-0-1-1")
     : this(loc)
 {
     this.ImageFile = imageFile;
 }
Example #38
0
        /// <summary>
        /// Downloads the folder.
        /// </summary>
        /// <param name="localFolder">The local folder.</param>
        /// <param name="remoteFolder">The remote folder.</param>
        /// <param name="recursive">The recursive.</param>
        /// <remarks></remarks>
        public void DownloadFolder(string localFolder, string remoteFolder, bool recursive)
        {
            this.ftpServer.ChangeWorkingDirectory(remoteFolder);

            var ftpServerFileInfo = this.ftpServer.GetFileInfos();

            var fi = default(System.IO.FileInfo);

            if (!System.IO.Directory.Exists(localFolder))
            {
                Log.Trace("creating {0}", localFolder);
                System.IO.Directory.CreateDirectory(localFolder);
            }

            foreach (EnterpriseDT.Net.Ftp.FTPFile currentFileOrDirectory in ftpServerFileInfo)
            {
                if (recursive)
                {
                    if (currentFileOrDirectory.Dir && currentFileOrDirectory.Name != "." && currentFileOrDirectory.Name != "..")
                    {
                        string localTargetFolder = System.IO.Path.Combine(localFolder, currentFileOrDirectory.Name);
                        string ftpTargetFolder   = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}/{1}", remoteFolder, currentFileOrDirectory.Name);

                        if (!System.IO.Directory.Exists(localTargetFolder))
                        {
                            Log.Trace("creating {0}", localTargetFolder);
                            System.IO.Directory.CreateDirectory(localTargetFolder);
                        }

                        DownloadFolder(localTargetFolder, ftpTargetFolder, recursive);

                        //set the ftp working folder back to the correct value
                        this.ftpServer.ChangeWorkingDirectory(remoteFolder);
                    }
                }

                if (!currentFileOrDirectory.Dir)
                {
                    bool downloadFile = false;

                    string localFile = System.IO.Path.Combine(localFolder, currentFileOrDirectory.Name);


                    // check file existence
                    if (!System.IO.File.Exists(localFile))
                    {
                        downloadFile = true;
                    }
                    else
                    {
                        //check file size
                        fi = new System.IO.FileInfo(localFile);
                        if (currentFileOrDirectory.Size != fi.Length)
                        {
                            downloadFile = true;
                            System.IO.File.Delete(localFile);
                        }
                        else
                        {
                            //check modification time
                            if (currentFileOrDirectory.LastModified != fi.CreationTime)
                            {
                                downloadFile = true;
                                System.IO.File.Delete(localFile);
                            }
                        }
                    }


                    if (downloadFile)
                    {
                        Log.Trace("Downloading {0}", currentFileOrDirectory.Name);
                        this.ftpServer.DownloadFile(localFolder, currentFileOrDirectory.Name);

                        fi = new System.IO.FileInfo(localFile);
                        fi.CreationTime   = currentFileOrDirectory.LastModified;
                        fi.LastAccessTime = currentFileOrDirectory.LastModified;
                        fi.LastWriteTime  = currentFileOrDirectory.LastModified;
                    }
                }
            }
        }
        private void CompareFileInfos(System.IO.FileInfo expected, Alphaleonis.Win32.Filesystem.FileInfo actual, bool exists)
        {
            if (expected == null || actual == null)
            {
                Assert.AreEqual(expected, actual, "The two FileInfo instances are not the same, but are expected to be.");
            }

            UnitTestConstants.Dump(expected, -17);
            Console.WriteLine();
            UnitTestConstants.Dump(actual, -17);


            if (exists)
            {
                Assert.IsTrue(expected.Exists && actual.Exists, "The file does not exist, but is expected to.");
            }
            else
            {
                Assert.IsFalse(expected.Exists && actual.Exists, "The file exists, but is expected not to.");
            }


            var cnt = -1;

            while (cnt != 15)
            {
                cnt++;
                // Compare values of both instances.
                switch (cnt)
                {
                case 0:
                    Assert.AreEqual(expected.Attributes, actual.Attributes, "The property Attributes is not the same, but is expected to be.");
                    break;

                case 1:
                    Assert.AreEqual(expected.CreationTime, actual.CreationTime, "The property CreationTime is not the same, but is expected to be.");
                    break;

                case 2:
                    Assert.AreEqual(expected.CreationTimeUtc, actual.CreationTimeUtc, "The property CreationTimeUtc is not the same, but is expected to be.");
                    break;

                // Need .ToString() here since the object types are obviously not the same.
                case 3:
                    Assert.AreEqual(expected.Directory.ToString(), actual.Directory.ToString(), "The property Directory is not the same, but is expected to be.");
                    break;

                case 4:
                    Assert.AreEqual(expected.DirectoryName, actual.DirectoryName, "The property DirectoryName is not the same, but is expected to be.");
                    break;

                case 5:
                    Assert.AreEqual(expected.Exists, actual.Exists, "The property Exists is not the same, but is expected to be.");
                    break;

                case 6:
                    Assert.AreEqual(expected.Extension, actual.Extension, "The property Extension is not the same, but is expected to be.");
                    break;

                case 7:
                    Assert.AreEqual(expected.FullName, actual.FullName, "The property FullName is not the same, but is expected to be.");
                    break;

                case 8:
                    Assert.AreEqual(expected.IsReadOnly, actual.IsReadOnly, "The property IsReadOnly is not the same, but is expected to be.");
                    break;

                case 9:
                    Assert.AreEqual(expected.LastAccessTime, actual.LastAccessTime, "The property LastAccessTime is not the same, but is expected to be.");
                    break;

                case 10:
                    Assert.AreEqual(expected.LastAccessTimeUtc, actual.LastAccessTimeUtc, "The property LastAccessTimeUtc is not the same, but is expected to be.");
                    break;

                case 11:
                    Assert.AreEqual(expected.LastWriteTime, actual.LastWriteTime, "The property LastWriteTime is not the same, but is expected to be.");
                    break;

                case 12:
                    Assert.AreEqual(expected.LastWriteTimeUtc, actual.LastWriteTimeUtc, "The property LastWriteTimeUtc is not the same, but is expected to be.");
                    break;

                case 13:
                    if (exists)
                    {
                        Assert.AreEqual(expected.Length, actual.Length, "The property Length is not the same, but is expected to be.");
                    }
                    break;

                case 14:
                    Assert.AreEqual(expected.Name, actual.Name, "The property Name is not the same, but is expected to be.");
                    break;
                }
            }
        }
Example #40
0
        private void GetTheList(System.Collections.Generic.List <Modification> mods, string localFolder, string remoteFolder, bool recursive)
        {
            this.ftpServer.ChangeWorkingDirectory(remoteFolder);

            EnterpriseDT.Net.Ftp.FTPFile[] ftpServerFileInfo = this.ftpServer.GetFileInfos();

            string localTargetFolder = null;
            string ftpTargetFolder   = null;
            bool   downloadFile      = false;
            string localFile         = null;

            System.IO.FileInfo fi = default(System.IO.FileInfo);

            if (!System.IO.Directory.Exists(localFolder))
            {
                Log.Trace("creating {0}", localFolder);
                System.IO.Directory.CreateDirectory(localFolder);
            }

            foreach (EnterpriseDT.Net.Ftp.FTPFile currentFileOrDirectory in ftpServerFileInfo)
            {
                if (recursive)
                {
                    if (currentFileOrDirectory.Dir && currentFileOrDirectory.Name != "." && currentFileOrDirectory.Name != "..")
                    {
                        localTargetFolder = System.IO.Path.Combine(localFolder, currentFileOrDirectory.Name);
                        ftpTargetFolder   = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}/{1}", remoteFolder, currentFileOrDirectory.Name);

                        if (!System.IO.Directory.Exists(localTargetFolder))
                        {
                            Log.Trace("creating {0}", localTargetFolder);
                            System.IO.Directory.CreateDirectory(localTargetFolder);
                        }

                        GetTheList(mods, localTargetFolder, ftpTargetFolder, recursive);

                        //set the ftp working folder back to the correct value
                        this.ftpServer.ChangeWorkingDirectory(remoteFolder);
                    }
                }

                if (!currentFileOrDirectory.Dir)
                {
                    downloadFile = false;
                    Modification m = new Modification();

                    localFile = System.IO.Path.Combine(localFolder, currentFileOrDirectory.Name);


                    // check file existence
                    if (!System.IO.File.Exists(localFile))
                    {
                        downloadFile = true;
                        m.Type       = "added";
                    }
                    else
                    {
                        //check file size
                        fi = new System.IO.FileInfo(localFile);
                        if (currentFileOrDirectory.Size != fi.Length)
                        {
                            downloadFile = true;
                            m.Type       = "Updated";
                        }
                        else
                        {
                            //check modification time
                            if (currentFileOrDirectory.LastModified != fi.CreationTime)
                            {
                                downloadFile = true;
                                m.Type       = "Updated";
                            }
                        }
                    }

                    if (downloadFile)
                    {
                        m.FileName     = currentFileOrDirectory.Name;
                        m.FolderName   = remoteFolder;
                        m.ModifiedTime = currentFileOrDirectory.LastModified;

                        mods.Add(m);
                    }
                }
            }
        }
Example #41
0
        private void buttonLoadData_Click(object sender, EventArgs e)
        {
            if (openFileDialogRefract.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            try
            {
                string Content = "";
                using (System.IO.StreamReader S = new System.IO.FileInfo(openFileDialogRefract.FileName).OpenText())
                    Content = S.ReadToEnd();

                Content = Content.Replace("\r", "");
                string[] Lines = Content.Split('\n');

                List <PanelFresnelReflectance.RefractionData> Data = new List <PanelFresnelReflectance.RefractionData>();
                READING_STATE State          = READING_STATE.UNKNOWN;
                bool          InsertExisting = false;
                for (int LineIndex = 0; LineIndex < Lines.Length; LineIndex++)
                {
                    string   Line   = Lines[LineIndex];
                    string[] Values = Line.Split(' ', '\t');
                    if (Line == "" || Values.Length == 0)
                    {
                        continue;                               // Skip empty lines
                    }
                    if (Values.Length != 2)
                    {
                        throw new Exception("Unexpected line " + LineIndex + " does not contain exactly 2 values! (" + Line + ")");
                    }

                    if (Values[0].ToLower() == "wl")
                    {
                        if (Values[1].ToLower() == "n")
                        {
                            State = READING_STATE.N;
                        }
                        else if (Values[1].ToLower() == "k")
                        {
                            State = READING_STATE.K;
                        }
                        else
                        {
                            throw new Exception("Unexpected data type \"" + Values[1] + "\" at line " + LineIndex + ". Expecting either n or k.");
                        }
                        InsertExisting = Data.Count > 0;        // Populate list or insert in existing one?
                        continue;                               // Skip this descriptor line
                    }

                    float wl;
                    if (!float.TryParse(Values[0], out wl))
                    {
                        throw new Exception("Failed to parse wavelength at line " + LineIndex);
                    }
                    float v;
                    if (!float.TryParse(Values[1], out v))
                    {
                        throw new Exception("Failed to parse " + (State == READING_STATE.N ? "n" : "k") + " at line " + LineIndex);
                    }

                    PanelFresnelReflectance.RefractionData D = null;
                    if (InsertExisting)
                    {                           // Find existing slot in list
                        foreach (PanelFresnelReflectance.RefractionData ExistingD in Data)
                        {
                            if (Math.Abs(ExistingD.Wavelength - wl) < 1e-6f)
                            {                                   // Found it!
                                D = ExistingD;
                                break;
                            }
                        }
                        if (D == null)
                        {
                            throw new Exception("Failed to retrieve wavelength " + wl + " in existing array of values populated by " + (State == READING_STATE.N ? "k" : "n") + " values at line " + LineIndex);
                        }
                    }
                    else
                    {                           // Simply append
                        D = new PanelFresnelReflectance.RefractionData()
                        {
                            Wavelength = wl
                        };
                        Data.Add(D);
                    }

                    if (State == READING_STATE.N)
                    {
                        D.n = v;
                    }
                    else
                    {
                        D.k = v;
                    }
                }

                outputPanelFresnelGraph.Data = Data.ToArray();
                checkBoxData.Checked         = true;
            }
            catch (Exception _e)
            {
                MessageBox.Show(this, "Failed to load data file:" + _e.Message, "Argh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #42
0
        private void timer_bak_Tick(object sender, EventArgs e)
        {
            if (isload)
            {
                if (!is_copying)
                {
                    if (server_Config != null)
                    {
                        int    parall_num = server_Config.upload_parallel;
                        string bak_path   = server_Config.backup_path;
                        BlockingCollection <string> list = new BlockingCollection <string>();
                        int index = 0;
                        foreach (var dic in diction)
                        {
                            if (index > parall_num)
                            {
                                break;
                            }
                            index++;
                            list.Add(dic.Key);
                        }
                        is_copying = true;
                        Task.Run(() =>
                        {
                            System.Threading.Tasks.Parallel.ForEach(list, s =>
                            {
                                media_collect_class collect_Class = diction[s];
                                string filepath         = collect_Class.full_path;
                                Entity.Pe_device device = collect_Class.device;
                                if (!string.IsNullOrEmpty(filepath))
                                {
                                    if (!FileUtils.IsFileInUse(filepath))
                                    {
                                        try
                                        {
                                            Entity.media_info media_Info = new Entity.media_info(s, server_Config.backup_path);
                                            LogManager.Info(new Entity.media_option_log()
                                            {
                                                client_ip      = server_Config.client_ip,
                                                device_name    = media_Info.host_body,
                                                media_filename = s,
                                                media_type     = media_Info.file_type,
                                                option_info    = $"开始复制文件:[{s}]",
                                                option_type    = (int)HANGE.Media.Henum.HEnum.media_status.开始备份,
                                                user_code      = media_Info.host_code
                                            });
                                            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filepath);
                                            long file_size = fileInfo.Length;

                                            #region 新建上传实体类
                                            Entity.Pe_video_list video_list_model = new Entity.Pe_video_list()
                                            {
                                                filename     = media_Info.host_code + "@" + media_Info.file_name,
                                                bfilename    = device.Hostname + "@" + media_Info.file_name,
                                                createdate   = DateTime.ParseExact(media_Info.file_name, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd HH:mm:ss"),
                                                filelen      = file_size.ToString(),
                                                playfilelen  = file_size.ToString(),
                                                filetype     = media_Info.file_type,
                                                hostname     = device.Hostname,
                                                hostbody     = device.Hostbody,
                                                hostcode     = device.Hostcode,
                                                danwei       = device.Danwei,
                                                onlyread     = media_Info.is_imp ? 1 : 0,
                                                caserank     = media_Info.is_imp ? "重要" : "",
                                                casetopic    = "",
                                                note         = "",
                                                serverurl    = server_Config.server_name,
                                                servername   = server_Config.client_ip,
                                                thumb        = media_Info.thumb,
                                                saveposition = media_Info.save_position,
                                                playposition = "",
                                                macposition  = media_Info.local_positon,
                                                creater      = server_Config.client_ip,
                                                playtime     = 1000,
                                                resolution   = "1920*1080",
                                                filetotnum   = 1,
                                                filetottime  = 1000,
                                                is_flg       = (int)HANGE.Media.Henum.HEnum.media_status.备份成功
                                            };
                                            var isexsit = HANGE.Media.Mysql.DBContext.DB.From <Entity.Pe_video_list>().Where(p => p.filename == video_list_model.filename).First();
                                            if (isexsit != null)
                                            {
                                                video_list_model.id = isexsit.id;
                                                HANGE.Media.Mysql.DBContext.DB.Update <Entity.Pe_video_list>(video_list_model);
                                            }
                                            else
                                            {
                                                HANGE.Media.Mysql.DBContext.DB.Insert <Entity.Pe_video_list>(video_list_model);
                                            }
                                            #endregion
                                            FileUtils.CopyOrRemoveFileFullPath(media_Info.local_positon, fileInfo);
                                            LogManager.Info(new Entity.media_option_log()
                                            {
                                                client_ip      = server_Config.client_ip,
                                                device_name    = media_Info.host_body,
                                                media_filename = s,
                                                media_type     = media_Info.file_type,
                                                option_info    = $"备份文件:[{s}]成功",
                                                option_type    = (int)HANGE.Media.Henum.HEnum.media_status.备份成功,
                                                user_code      = media_Info.host_code
                                            });
                                        }
                                        catch (Exception ex)
                                        {
                                            LogManager.Error(ex);
                                        }
                                    }
                                }
                                try
                                {
                                    bool result = diction.TryRemove(s, out collect_Class);
                                    if (!result)
                                    {
                                        LogManager.Error(new Exception($"移除key[{s}]失败"));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogManager.Error(ex);
                                }
                            });
                            is_copying = false;
                        });
                    }
                }
            }
        }
        private void START_THE_COPY()
        {
            try
            {
                /// CHECK PATH OF INSTALLER
                Path_Installer = VALIDATE_INSTALLER_PATH(Path_Installer);

                /// OPEN CONNECTION TO NETWORK SHARE
                using (System.Diagnostics.Process Proc = new System.Diagnostics.Process())
                {
                    Proc.StartInfo.FileName    = @"C:\Windows\System32\net.exe";
                    Proc.StartInfo.Arguments   = "use \"" + Path_Installer + "\" /user:\"" + NetShare_Username + "\" " + NetShare_Password;
                    Proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    Proc.Start();
                    Proc.WaitForExit();
                }

                /// START COPYING
                int index = 0;
                foreach (string s in System.IO.Directory.GetFiles(Path_Installer))
                {
                    index++;
                    var file_destination              = System.IO.Path.Combine(LOCAL_DEST, System.IO.Path.GetFileName(s));
                    System.IO.FileInfo fi_source      = new System.IO.FileInfo(s);
                    System.IO.FileInfo fi_destination = new System.IO.FileInfo(file_destination);

                    /// CHECK IF DESTINATION FILE ALREADY EXISTS
                    if (System.IO.File.Exists(file_destination))
                    {
                        if (fi_source.LastWriteTime > fi_destination.LastWriteTime)
                        {
                            System.IO.File.Delete(file_destination);
                        }
                    }

                    Task.Run(() =>
                    {
                        fi_source.Copyfile(fi_destination, x => MyPGB.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            MyPGB.Value = x;
                            // BrdInstall.Visibility = Visibility.Hidden;
                            TxtbFileInProgress.Text = System.IO.Path.GetFileName(s) + " - " + MyPGB.Value.ToString() + "%";
                        })));
                    }).GetAwaiter().OnCompleted(() => MyPGB.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MyPGB.Value             = 100;
                        TxtbFileInProgress.Text = "COMPLETED";

                        //START INSTALL
                        if (System.IO.Directory.GetFiles(Path_Installer).Count() == index)
                        {
                            BrdInstall.Visibility = Visibility.Visible;
                        }
                    })));
                }

                /// CLOSE CONNECTION TO NETWORK SHARE
                using (System.Diagnostics.Process Proc = new System.Diagnostics.Process())
                {
                    Proc.StartInfo.FileName    = @"C:\Windows\System32\net.exe";
                    Proc.StartInfo.Arguments   = "use " + Path_Installer + " /D";
                    Proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    Proc.Start();
                    Proc.WaitForExit();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #44
0
        public void UploadMultipleSmallFiles()
        {
            //Guid requestID = new Guid("63f074ee-cf4c-4838-ae27-aa4700d7ca87");
            //Guid dataMartID = new Guid("84C9440A-0B1F-4EC0-AF75-A85500CC8F16");
            //string sourceFolderPath = @"C:\work\DR-UAT\DP2\v_psu_01_346\msoc";
            string sourceFolderPath = @"C:\work\DR-UAT\DP2\v_psu_01_353\TEST";

            Guid requestID  = new Guid("2D35C33F-11D2-47E3-A2D8-AA4700BCCBBA");
            Guid dataMartID = new Guid("6D55D9BA-9787-40DC-B9B7-A49F00C83946");

            List <DTO.DataMartClient.Criteria.DocumentMetadata> documents = new List <DTO.DataMartClient.Criteria.DocumentMetadata>();

            foreach (var file in System.IO.Directory.GetFiles(sourceFolderPath))
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(file);
                Guid documentID       = Lpp.Utilities.DatabaseEx.NewGuid();
                documents.Add(
                    new DTO.DataMartClient.Criteria.DocumentMetadata
                {
                    CurrentChunkIndex = 0,
                    DataMartID        = dataMartID,
                    ID         = documentID,
                    IsViewable = false,
                    Kind       = string.Empty,
                    MimeType   = Lpp.Utilities.FileEx.GetMimeTypeByExtension(fi.Name),
                    Name       = fi.Name,
                    RequestID  = requestID
                }
                    );

                logger.Debug($"Adding document: {fi.Name} (ID: {documentID})");
            }

            //documents = documents.Skip(12).Take(4).ToList();

            Parallel.ForEach(documents,
                             new ParallelOptions {
                MaxDegreeOfParallelism = 4
            },
                             (doc) =>
            {
                string uploadIdentifier = ("[" + Utilities.Crypto.Hash(Guid.NewGuid()) + "]").PadRight(16);

                System.IO.Stream stream = null;
                try
                {
                    //if (cache.Enabled)
                    //{
                    //    stream = cache.GetDocumentStream(Guid.Parse(doc.DocumentID));
                    //}
                    //else
                    //{
                    //    request.Processor.ResponseDocument(requestId, doc.DocumentID, out stream, doc.Size);
                    //}

                    stream = new System.IO.FileStream(System.IO.Path.Combine(sourceFolderPath, doc.Name), System.IO.FileMode.Open);

                    var dto = new DTO.DataMartClient.Criteria.DocumentMetadata
                    {
                        ID                = doc.ID,
                        DataMartID        = dataMartID,
                        RequestID         = requestID,
                        IsViewable        = doc.IsViewable,
                        Size              = doc.Size,
                        MimeType          = doc.MimeType,
                        Kind              = doc.Kind,
                        Name              = doc.Name,
                        CurrentChunkIndex = 0
                    };

                    DnsServiceManager.PostDocumentChunk(uploadIdentifier, dto, stream, _networkSetting);
                }
                finally
                {
                    stream.Dispose();
                }
            });
        }
Example #45
0
        public static int AutoImport(List <string> args)
        {
            string dir      = @"d:\_svn\GraceNote\GraceNote\DanganRonpaBestOfRebuild\umdimage.dat.ex\";
            string voicedir = @"d:\_svn\GraceNote\GraceNote\Voices\";

            string[] files = System.IO.Directory.GetFiles(dir);

            List <String> dbsToUp = new List <string>();

            foreach (var x in nonstopDict)
            {
                string nonstopFile        = GetFromSubstring(files, x.Key);
                string scriptFile         = GetFromSubstring(files, x.Value);
                string scriptFileFilename = new System.IO.FileInfo(scriptFile).Name;
                string databaseId         = scriptFileFilename.Substring(0, 4);
                string databaseFile       = @"d:\_svn\GraceNote\GraceNote\DanganRonpaBestOfDB\DRBO" + databaseId;
                dbsToUp.Add("DRBO" + databaseId);
                //continue;

                LIN     lin     = new LIN(scriptFile);
                Nonstop nonstop = new Nonstop(nonstopFile);

                int lastScriptEntry = 0;
                foreach (var item in nonstop.items)
                {
                    int stringId = item.data[(int)NonstopSingleStructure.StringID] + 1;
                    int correspondingTextEntry   = stringId * 2;
                    int correspondingScriptEntry = correspondingTextEntry - 1;
                    if (item.data[(int)NonstopSingleStructure.Type] == 0)
                    {
                        lastScriptEntry = correspondingTextEntry;
                    }


                    // --- insert comment info ---
                    string comment = (string)SqliteUtil.SelectScalar(
                        "Data Source=" + databaseFile,
                        "SELECT comment FROM Text WHERE id = ?",
                        new object[] { correspondingTextEntry });

                    bool weakpt = item.data[(int)NonstopSingleStructure.HasWeakPoint] > 0;
                    comment = (comment == "" ? "" : comment + "\n\n")
                              + "Autogenerated Info:\n"
                              + (lastScriptEntry == 0 ? "Corresponds to file: " + scriptFileFilename : "")
                              + (item.data[(int)NonstopSingleStructure.Type] == 0 ? "Normal Line\n" : "Background Noise\n")
                              + (weakpt ? "Has a Weak Point\n" : "No Weakpoint\n")
                              + (weakpt && (item.data[(int)NonstopSingleStructure.ShootWithEvidence] & 0xFF) != 255 ? "Shot with Evidence Bullet: " + item.data[(int)NonstopSingleStructure.ShootWithEvidence] + "\n" : "")
                              + (weakpt && (item.data[(int)NonstopSingleStructure.ShootWithWeakpoint] & 0xFF) != 255 ? "Shot with Weak Point: " + item.data[(int)NonstopSingleStructure.ShootWithWeakpoint] + "\n" : "")
                              + (weakpt && (item.data[(int)NonstopSingleStructure.ShootWithWeakpoint] & 0xFF) == 255 && (item.data[(int)NonstopSingleStructure.ShootWithEvidence] & 0xFF) == 255 ? "Can't be shot\n" : "")
                              + (item.data[(int)NonstopSingleStructure.Type] == 0 ? "" : "Appears around Entry #" + lastScriptEntry + "\n")
                              + (item.data[(int)NonstopSingleStructure.Type] == 0 ? "Sprite: " + DanganUtil.CharacterIdToName((byte)item.data[(int)NonstopSingleStructure.Character]) + " " + item.data[(int)NonstopSingleStructure.Sprite] + "\n" : "")
                    ;
                    SqliteUtil.Update(
                        "Data Source=" + databaseFile,
                        "UPDATE Text SET comment = ?, updated = 1 WHERE id = ?",
                        new object[] { comment, correspondingTextEntry });


                    // --- insert voice info ---
                    string script = (string)SqliteUtil.SelectScalar(
                        "Data Source=" + databaseFile,
                        "SELECT english FROM Text WHERE id = ?",
                        new object[] { correspondingScriptEntry });
                    string voicename;
                    string voicefilecheck;

                    byte charid = (byte)item.data[(int)NonstopSingleStructure.Character];
                    if (item.data[(int)NonstopSingleStructure.Type] == 0)
                    {
                        while (true)
                        {
                            string charac = DanganUtil.CharacterIdToName(charid);
                            if (charac == "Naegi")
                            {
                                charac = "Neagi";
                            }
                            voicename = "[" + charac + "] " + item.data[(int)NonstopSingleStructure.Chapter] + " "
                                        + (item.data[(int)NonstopSingleStructure.AudioSampleId] >> 8) + " " + (item.data[(int)NonstopSingleStructure.AudioSampleId] & 0xFF) + " 100";
                            voicefilecheck = voicedir + voicename + ".mp3";
                            if (System.IO.File.Exists(voicefilecheck))
                            {
                                break;
                            }
                            charid = 0x12;
                        }

                        script += "<__END__>\n"
                                  + "<Voice: " + voicename + ">"
                        ;
                        SqliteUtil.Update(
                            "Data Source=" + databaseFile,
                            "UPDATE Text SET english = ?, updated = 1 WHERE id = ?",
                            new object[] { script, correspondingScriptEntry });


                        // update the header name thingy
                        string header = DanganUtil.CharacterIdToName(charid);
                        SqliteUtil.Update(
                            "Data Source=" + databaseFile,
                            "UPDATE Text SET IdentifyString = ?, updated = 1 WHERE id = ?",
                            new object[] { header, correspondingTextEntry });
                    }
                    else
                    {
                        string header = "Background Noise";
                        SqliteUtil.Update(
                            "Data Source=" + databaseFile,
                            "UPDATE Text SET IdentifyString = ?, updated = 1 WHERE id = ?",
                            new object[] { header, correspondingTextEntry });
                    }
                }
            }

            System.IO.File.WriteAllLines(
                @"d:\_svn\GraceNote\GraceNote\temp.txt", dbsToUp.ToArray());
            return(0);
        }
Example #46
0
        /// <summary>Gets the character endcoding of a file</summary>
        /// <param name="File">The absolute path to a file</param>
        /// <returns>The character encoding, or unknown</returns>
        public static Encoding GetEncodingFromFile(string File)
        {
            if (File == null || !System.IO.File.Exists(File))
            {
                return(Encoding.Unknown);
            }

            try
            {
                System.IO.FileInfo fInfo = new System.IO.FileInfo(File);
                byte[]             Data  = System.IO.File.ReadAllBytes(File);

                if (Data.Length >= 3)
                {
                    if (Data[0] == 0xEF & Data[1] == 0xBB & Data[2] == 0xBF)
                    {
                        return(Encoding.Utf8);
                    }

                    if (Data[0] == 0x2b & Data[1] == 0x2f & Data[2] == 0x76)
                    {
                        return(Encoding.Utf7);
                    }
                }

                if (Data.Length >= 2)
                {
                    if (Data[0] == 0xFE & Data[1] == 0xFF)
                    {
                        return(Encoding.Utf16Be);
                    }

                    if (Data[0] == 0xFF & Data[1] == 0xFE)
                    {
                        return(Encoding.Utf16Le);
                    }
                }

                if (Data.Length >= 4)
                {
                    if (Data[0] == 0x00 & Data[1] == 0x00 & Data[2] == 0xFE & Data[3] == 0xFF)
                    {
                        return(Encoding.Utf32Be);
                    }

                    if (Data[0] == 0xFF & Data[1] == 0xFE & Data[2] == 0x00 & Data[3] == 0x00)
                    {
                        return(Encoding.Utf32Le);
                    }
                }

                CharsetDetector Det = new CharsetDetector();
                Det.Feed(Data, 0, Data.Length);
                Det.DataEnd();

                if (Det.Charset == null)
                {
                    return(Encoding.Unknown);
                }

                switch (Det.Charset.ToUpperInvariant())
                {
                case "SHIFT-JIS":
                case "SHIFT_JIS":
                    return(Encoding.Shift_JIS);

                case "UTF-8":
                    return(Encoding.Utf8);

                case "UTF-7":
                    return(Encoding.Utf7);

                case "WINDOWS-1251":
                    if (System.IO.Path.GetFileName(File).ToLowerInvariant() == "585tc1.csv" && fInfo.Length == 37302)
                    {
                        return(Encoding.Shift_JIS);
                    }
                    return(Encoding.Windows1252);

                case "WINDOWS-1252":
                    if (fInfo.Length == 62861)
                    {
                        //HK tram route. Comes in a non-unicode zip, so filename may be subject to mangling
                        return(Encoding.Big5);
                    }
                    return(Encoding.Windows1252);

                case "WINDOWS-1255":
                    if (System.IO.Path.GetFileName(File).ToLowerInvariant() == "xdbetulasmall.csv" && fInfo.Length == 406)
                    {
                        //Hungarian birch tree; Actually loads OK with 1255, but use the correct one
                        return(Encoding.Windows1252);
                    }
                    return(Encoding.Big5);

                case "BIG5":
                    if (System.IO.Path.GetFileName(File).ToLowerInvariant() == "stoklosy.b3d" && fInfo.Length == 18256)
                    {
                        //Polish Warsaw metro object file uses diacritics in filenames
                        return(Encoding.Windows1252);
                    }
                    return(Encoding.Big5);

                case "EUC-KR":
                    return(Encoding.EUC_KR);

                case "ASCII":
                    return(Encoding.ASCII);

                case "IBM866":
                    return(Encoding.OEM866);

                case "X-MAC-CYRILLIC":
                    if (System.IO.Path.GetFileName(File).ToLowerInvariant() == "exit01.csv" && fInfo.Length == 752)
                    {
                        //hira2
                        return(Encoding.Shift_JIS);
                    }
                    break;

                case "GB18030":
                    //Extended new Chinese charset
                    if (System.IO.Path.GetFileName(File).ToLowerInvariant() == "people6.b3d" && fInfo.Length == 377)
                    {
                        //Polish Warsaw metro object file uses diacritics in filenames
                        return(Encoding.Windows1252);
                    }
                    break;

                case "EUC-JP":
                    if (System.IO.Path.GetFileName(File).ToLowerInvariant() == "xsara.b3d" && fInfo.Length == 3429)
                    {
                        //Uses an odd character in the comments, ASCII works just fine
                        return(Encoding.ASCII);
                    }
                    break;
                }

                Det.Reset();
                return(Encoding.Unknown);
            }
            catch
            {
                return(Encoding.Unknown);
            }
        }
Example #47
0
 public void refreshP4ROAttributes()
 {
     isP4 = assetsMangement.CohAssetMang.isP4file(fileName);
     System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
     isReadOnly = (fi.Attributes & System.IO.FileAttributes.ReadOnly) != 0;
 }
        public void Edit(EducationModel model)
        {
            try
            {
                //model.CodeFileSelectListEvent += _codeFileService.GetDropDownList;
                var education = db.Repository <HealthEdu>().Read(a => a.ID == model.ID);

                if (education != null)
                {
                    var storageAttach = Storage.GetStorage(StorageScope.GuardianUpload);

                    var educationFiles = db.Repository <HealthEdu_File>().ReadAll().Where(a => a.HealthEdu_ID == model.ID);

                    int showOrder = (educationFiles.Count() > 0)
                            ? educationFiles.Max(a => a.Show_Order) + 1
                            : 1;
                    int defaultShowSeconds = 5;

                    foreach (var file in model.UploadFiles.OrEmptyIfNull())
                    {
                        if (file != null && !file.FileName.IsNullOrEmpty())
                        {
                            var fileName = new System.IO.FileInfo(file.FileName).Name;
                            if (!storageAttach.FileExist(fileName, model.ID) &&
                                storageAttach.CheckExtensions(System.IO.Path.GetExtension(fileName)))
                            {
                                fileName = storageAttach.Write(fileName, file, model.ID);
                                var newFile = new HealthEdu_File
                                {
                                    HealthEdu_ID = model.ID,
                                    FileName     = fileName,
                                    Show_Order   = showOrder,
                                    Show_Seconds = defaultShowSeconds,
                                    IsUsed       = true
                                };
                                db.Repository <HealthEdu_File>().Create(newFile);
                                showOrder++;
                            }
                        }
                    }
                    foreach (var file in model.EducationFiles.OrEmptyIfNull())
                    {
                        var updatedFile = db.Repository <HealthEdu_File>().Read(a => a.ID == file.ID && a.HealthEdu_ID == file.HealthEdu_ID);
                        updatedFile.Show_Seconds = file.Show_Seconds;
                        updatedFile.IsUsed       = file.IsUsed;
                        updatedFile.Show_Order   = file.Show_Order;
                    }

                    education.HealthEdu_Type_CodeFile = model.HealthEdu_Type_CodeFile;
                    education.HealthEdu_Name          = model.HealthEdu_Name;
                    education.IsUsed         = model.IsUsed;
                    education.IsForLobbyUsed = model.IsForLobbyUsed;
                    education.QueueMsg       = model.QueueMsg;

                    Save();
                }
            }
            catch (Exception ex)
            {
                ValidationDictionary.AddGeneralError(ex.Message);
            }
        }
    private int RecurseWorkUnit(AssetType in_type, System.IO.FileInfo in_workUnit, string in_currentPathInProj,
                                string in_currentPhysicalPath, System.Collections.Generic.LinkedList <AkWwiseProjectData.PathElement> in_pathAndIcons,
                                string in_parentPath = "")
    {
        m_WwuToProcess.Remove(in_workUnit.FullName);
        var wwuIndex = -1;

        try
        {
            //Progress bar stuff
            var msg = "Parsing Work Unit " + in_workUnit.Name;
            UnityEditor.EditorUtility.DisplayProgressBar(s_progTitle, msg, m_currentWwuCnt / (float)m_totWwuCnt);
            m_currentWwuCnt++;

            in_currentPathInProj =
                System.IO.Path.Combine(in_currentPathInProj, System.IO.Path.GetFileNameWithoutExtension(in_workUnit.Name));
            in_pathAndIcons.AddLast(new AkWwiseProjectData.PathElement(
                                        System.IO.Path.GetFileNameWithoutExtension(in_workUnit.Name), WwiseObjectType.WorkUnit));
            var WwuPhysicalPath = System.IO.Path.Combine(in_currentPhysicalPath, in_workUnit.Name);

            var wwu = ReplaceWwuEntry(WwuPhysicalPath, in_type, out wwuIndex);

            wwu.ParentPath   = in_currentPathInProj;
            wwu.PhysicalPath = WwuPhysicalPath;
            wwu.Guid         = System.Guid.Empty;
            wwu.LastTime     = System.IO.File.GetLastWriteTime(in_workUnit.FullName);

            using (var reader = System.Xml.XmlReader.Create(in_workUnit.FullName))
            {
                reader.MoveToContent();
                reader.Read();

                while (!reader.EOF && reader.ReadState == System.Xml.ReadState.Interactive)
                {
                    if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name.Equals("WorkUnit"))
                    {
                        if (wwu.Guid.Equals(System.Guid.Empty))
                        {
                            var ID = reader.GetAttribute("ID");
                            try
                            {
                                wwu.Guid = new System.Guid(ID);
                            }
                            catch
                            {
                                UnityEngine.Debug.LogWarning("WwiseUnity: Error reading ID <" + ID + "> from work unit <" + in_workUnit.FullName + ">.");
                                throw;
                            }
                        }

                        var persistMode = reader.GetAttribute("PersistMode");
                        if (persistMode == "Reference")
                        {
                            // ReadFrom advances the reader
                            var matchedElement  = System.Xml.Linq.XNode.ReadFrom(reader) as System.Xml.Linq.XElement;
                            var newWorkUnitPath =
                                System.IO.Path.Combine(in_workUnit.Directory.FullName, matchedElement.Attribute("Name").Value + ".wwu");
                            var newWorkUnit = new System.IO.FileInfo(newWorkUnitPath);

                            // Parse the referenced Work Unit
                            if (m_WwuToProcess.Contains(newWorkUnit.FullName))
                            {
                                RecurseWorkUnit(in_type, newWorkUnit, in_currentPathInProj, in_currentPhysicalPath, in_pathAndIcons,
                                                WwuPhysicalPath);
                            }
                        }
                        else
                        {
                            // If the persist mode is "Standalone" or "Nested", it means the current XML tag
                            // is the one corresponding to the current file. We can ignore it and advance the reader
                            reader.Read();
                        }
                    }
                    else if (reader.NodeType == System.Xml.XmlNodeType.Element && (reader.Name.Equals("AuxBus") || reader.Name.Equals("Folder") || reader.Name.Equals("Bus")))
                    {
                        WwiseObjectType objType;
                        switch (reader.Name)
                        {
                        case "AuxBus":
                            objType = WwiseObjectType.AuxBus;
                            break;

                        case "Bus":
                            objType = WwiseObjectType.Bus;
                            break;

                        case "Folder":
                        default:
                            objType = WwiseObjectType.Folder;
                            break;
                        }
                        in_currentPathInProj = System.IO.Path.Combine(in_currentPathInProj, reader.GetAttribute("Name"));
                        in_pathAndIcons.AddLast(new AkWwiseProjectData.PathElement(reader.GetAttribute("Name"), objType));
                        AddElementToList(in_currentPathInProj, reader, in_type, in_pathAndIcons, wwuIndex);
                    }
                    else if (reader.NodeType == System.Xml.XmlNodeType.EndElement &&
                             (reader.Name.Equals("Folder") || reader.Name.Equals("Bus") || reader.Name.Equals("AuxBus")))
                    {
                        // Remove the folder/bus from the path
                        in_currentPathInProj = in_currentPathInProj.Remove(in_currentPathInProj.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
                        in_pathAndIcons.RemoveLast();
                        // Advance the reader
                        reader.Read();
                    }
                    else if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name.Equals(in_type.XmlElementName))
                    {
                        // Add the element to the list
                        AddElementToList(in_currentPathInProj, reader, in_type, in_pathAndIcons, wwuIndex);
                    }
                    else
                    {
                        reader.Read();
                    }
                }
            }

            // Sort the newly populated Wwu alphabetically
            SortWwu(in_type, wwuIndex);
        }
        catch (System.Exception e)
        {
            UnityEngine.Debug.LogError(e.ToString());
            wwuIndex = -1;
        }

        in_pathAndIcons.RemoveLast();
        return(wwuIndex);
    }
Example #50
0
        public DataTable GetOrderHelp(string @s_FileName)
        {
            //jalky bylop w service
            //string s_PathName = @"C:Users\Exist\Desktop\";
            //Nie obsuluguje service
            string s_PathName2 = @"C:\Users\Paweł\Desktop\WCF\Dane\";

            List <string> CatalogList = new List <string>();
            List <string> ValueList   = new List <string>();

            System.Xml.XmlDocument xml = new System.Xml.XmlDocument();

            try
            {
                xml.Load(s_PathName2 + s_FileName);
                System.Xml.XmlNodeList xnList = xml.SelectNodes("/orders/order/rows/row");
                System.IO.FileInfo     fi     = new System.IO.FileInfo(s_PathName2 + s_FileName);

                foreach (System.Xml.XmlNode xnItem in xnList)
                {
                    CatalogList.Add(xnItem["products_sku"].InnerText);
                    ValueList.Add(xnItem["quantity"].InnerText);
                }

                string[] katalog = CatalogList.ToArray();
                string[] wartosc = ValueList.ToArray();
                string[,] tablica = new string[katalog.Length, 6];
                int[] myInts = Array.ConvertAll(wartosc, s => int.Parse(s));

                var result =
                    katalog
                    .Zip(myInts, (f, q) => new { f, q })
                    .GroupBy(x => x.f, x => x.q)
                    .Select(x => new { katalog = x.Key, myInts = x.Sum() })
                    .ToArray();

                var totalProductByCatalog = result.Select(x => x.katalog).ToArray();
                var totalquantity         = result.Select(x => x.myInts).ToArray();



                if (fi.Exists)
                {
                    if (System.IO.Path.GetFileNameWithoutExtension(s_PathName2 + s_FileName).Contains("Wybrane"))
                    {
                        return(GetDataList(katalog, wartosc));
                    }

                    else
                    {
                        fi.MoveTo(m_ChangeFileName(s_PathName2 + "Wybrane" + s_FileName));
                    }
                }


                return(GetDataList(katalog, wartosc));
            }
            catch (Exception E)
            {
                return(null);
            }
        }
Example #51
0
        void CreateExcelDocument()
        {
            System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            Microsoft.Office.Interop.Excel.Application xlApp       = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbooks   xlWorkBooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook    xlWorkBook  = xlWorkBooks.Add(1);
            Microsoft.Office.Interop.Excel.Worksheet   xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            try
            {
                xlWorkSheet.Name        = (rm as ResourceManager).GetString("LB_Expenses");
                xlWorkSheet.Cells[1, 1] = exitems[CB_Offer.SelectedIndex].Venue.Trim() + " - " + exitems[CB_Offer.SelectedIndex].Address.Trim();

                Microsoft.Office.Interop.Excel.Range formatRange = xlWorkSheet.get_Range("A1", "D1");
                formatRange.Font.Bold = true;
                formatRange.WrapText  = true;

                xlWorkSheet.Range["a1", "D1"].Merge();

                string rang = "A1:" + "D" + (expList.Count + 3);
                xlWorkSheet.get_Range(rang).Cells.Font.Name = "Comic Sans MS";
                xlWorkSheet.Range[rang].Font.Size           = 16;
                xlWorkSheet.Range[rang].Interior.Color      = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Pink);
                xlWorkSheet.Range[rang].Font.Color          = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                xlWorkSheet.Range[rang].Borders.Color       = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

                formatRange = xlWorkSheet.get_Range(rang);
                formatRange.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous,
                                         Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic,
                                         Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic);
                xlWorkSheet.Range[rang].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Range[rang].VerticalAlignment   = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

                xlWorkSheet.Cells[2, 1] = LB_Expense.Content;
                xlWorkSheet.Cells[2, 2] = LB_Cost.Content;
                xlWorkSheet.Cells[2, 3] = LB_Count.Content;
                xlWorkSheet.Cells[2, 4] = (rm as ResourceManager).GetString("LB_Amount");

                int sum = 0;
                for (int i = 0; i < expList.Count; i++)
                {
                    xlWorkSheet.Cells[3 + i, 1] = expList[i].ExpenseName.Trim();;
                    xlWorkSheet.Cells[3 + i, 2] = f.StringCurrencyFormat(expList[i].Expense.ToString());
                    xlWorkSheet.Cells[3 + i, 3] = f.StringCurrencyFormat(expList[i].Count.ToString());
                    xlWorkSheet.Cells[3 + i, 4] = f.StringCurrencyFormat((expList[i].Expense * expList[i].Count).ToString());
                    xlWorkSheet.Cells[3 + i, 2].NumberFormat = "0";
                    xlWorkSheet.Cells[3 + i, 3].NumberFormat = "0";
                    xlWorkSheet.Cells[3 + i, 4].NumberFormat = "0";
                    sum += expList[i].Expense * expList[i].Count;
                }

                xlWorkSheet.Range["A" + (expList.Count + 3), "C" + (expList.Count + 3)].Merge();

                xlWorkSheet.Cells[expList.Count + 3, 1] = (rm as ResourceManager).GetString("LB_Amount");
                xlWorkSheet.Cells[expList.Count + 3, 4] = f.StringCurrencyFormat(sum.ToString());

                xlWorkSheet.get_Range(rang).Columns.AutoFit();

                rang        = "A" + (expList.Count + 3) + ":" + "D" + (expList.Count + 3);
                formatRange = xlWorkSheet.get_Range(rang);
                formatRange.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous,
                                         Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic,
                                         Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic);
                xlWorkSheet.Range[rang].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.Range[rang].VerticalAlignment   = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

                xlApp.DisplayAlerts = false;

                Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();

                int venlenght = exitems[CB_Offer.SelectedIndex].Venue.Length;
                int addlenght = exitems[CB_Offer.SelectedIndex].Address.Length;

                saveFileDialog.FileName         = (rm as ResourceManager).GetString("LB_Expenses") + "_" + exitems[CB_Offer.SelectedIndex].Venue.Substring(0, venlenght < 15 ? venlenght:15) + "_" + exitems[CB_Offer.SelectedIndex].Address.Substring(0, addlenght < 15 ? addlenght:15);
                saveFileDialog.Filter           = (rm as ResourceManager).GetString("SaveFileDialogFilter");
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt     = true;
                saveFileDialog.Title            = (rm as ResourceManager).GetString("SaveFileDialogTitle");

                if (saveFileDialog.ShowDialog() == true)
                {
                    System.IO.FileInfo file = new System.IO.FileInfo(saveFileDialog.FileName);
                    if (f.IsFileLocked(file, (rm as ResourceManager), ResourceNames) == false)
                    {
                        xlWorkBook.SaveAs(saveFileDialog.FileName);
                        ViewModel.WinMessageBoxItem wmsgbi = new ViewModel.WinMessageBoxItem((rm as ResourceManager).GetString("MessageBoxSaveTitle"), (rm as ResourceManager).GetString("MessageBoxSaveText"), MaterialDesignThemes.Wpf.PackIconKind.InformationCircle);
                        Windows.WinMessageBox       wmsg   = new Windows.WinMessageBox(wmsgbi, (rm as ResourceManager), ResourceNames, false);
                        wmsg.Show();
                    }
                }
                xlWorkBook.Close(false, Type.Missing, Type.Missing);
                xlApp.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkBook);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
            }
            catch (Exception ex)
            {
                System.Windows.Input.Mouse.OverrideCursor = null;
                ViewModel.WinMessageBoxItem wmsb = new ViewModel.WinMessageBoxItem("Error", ex.Message, MaterialDesignThemes.Wpf.PackIconKind.Error);
                Windows.WinMessageBox       msb  = new Windows.WinMessageBox(wmsb, (rm as ResourceManager), ResourceNames, false);
                msb.Show();

                xlWorkBook.Close(false, Type.Missing, Type.Missing);
                xlApp.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkBook);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
            }
            System.Windows.Input.Mouse.OverrideCursor = null;
        }
Example #52
0
 public void Interpret(System.IO.FileInfo file)
 {
     _parser.Interpret(file, _currentSystem);
 }
Example #53
0
        ///<summary>Executes your service. If multiple services are defined in the assembly, it will run them all in separate threads.</summary>
        /// <param name="Args">The arguments passed in from the command line.</param>
        /// <param name="Types">An array of types we want to inspect for services.</param>
        public static void RunServices(string[] Args, Type[] Types)
        {
            Console.WriteLine("Service Installer");


            //Reads in all the classes in the assembly and finds one that derives
            //from this class. If it finds one, it checks the attributes to see
            //if we should run it. If we should, we create an instance of it and
            //start it on its way...

            //Type[] types = a.GetTypes();

            System.Collections.ArrayList alDispatchTables = new System.Collections.ArrayList();
            List <ServiceBase>           alServices       = new List <ServiceBase>();

            foreach (Type t in Types)
            {
                if (t.IsClass && t.BaseType != null && t.BaseType.Equals(typeof(ServiceBase)))
                {
                    //Gets all the custom attributes of type ServiceAttribute in the class.
                    object[] attributes = t.GetCustomAttributes(typeof(ServiceAttribute), true);
                    foreach (ServiceAttribute info in attributes)
                    {
                        if (info.Run)
                        {
                            ServiceBase s = (ServiceBase)Activator.CreateInstance(t);
                            alServices.Add(s);

                            //Make sure we have a name set for this guy...
                            if (string.IsNullOrWhiteSpace(s.Name))
                            {
                                throw new ServiceRuntimeException("A service was created without a name.");
                            }

                            if (Args.Length == 0)
                            {
                                Console.WriteLine();
                                Console.WriteLine("{0} Service", s.Name);
                                Console.WriteLine("==================================");
                                Console.WriteLine("Install");
                                Console.WriteLine("\t{0} i", System.AppDomain.CurrentDomain.FriendlyName);
                                Console.WriteLine("Uninstall");
                                Console.WriteLine("\t{0} u", System.AppDomain.CurrentDomain.FriendlyName);
                                Console.WriteLine("Interactive Mode");
                                Console.WriteLine("\t{0} c", System.AppDomain.CurrentDomain.FriendlyName);
                            }

                            bool isUacEnabled  = UacHelper.IsUacEnabled;
                            bool isUacElevated = UacHelper.IsProcessElevated;

                            if (isUacEnabled && !isUacElevated)
                            {
                                Console.WriteLine(
                                    "Warning: UAC is enabled but not process is not elevated, some functionality is not possible");

                                ServicesAPI.SERVICE_TABLE_ENTRY entry = new ServicesAPI.SERVICE_TABLE_ENTRY();
                                entry.lpServiceName = info.Name;
                                entry.lpServiceProc = new ServicesAPI.ServiceMainProc(s.baseServiceMain);
                                alDispatchTables.Add(entry);
                                s.Debug = false;
                            }
                            else
                            {
                                if (Args.Length > 0 && (Args[0].ToLower() == "u" || Args[0].ToLower() == "uninstall"))
                                {
                                    //Nothing to uninstall if it's not installed...
                                    if (!IsServiceInstalled(info.Name))
                                    {
                                        break;
                                    }
                                    if (!ServiceInstaller.Uninstall(info.Name))
                                    {
                                        throw new ServiceUninstallException("Unable to remove service \"" + info.DisplayName + "\"");
                                    }
                                    if (!s.Uninstall())
                                    {
                                        throw new ServiceUninstallException("Service \"" + info.DisplayName + "\" was unable to uninstall itself correctly.");
                                    }
                                }
                                else if (Args.Length > 0 && (Args[0].ToLower() == "i" || Args[0].ToLower() == "install"))
                                {
                                    //Just install the service if we pass in "i" or "install"...
                                    //Always check to see if the service is installed and if it isn't,
                                    //then go ahead and install it...
                                    if (!IsServiceInstalled(info.Name))
                                    {
                                        string[] envArgs = Environment.GetCommandLineArgs();
                                        if (envArgs.Length > 0)
                                        {
                                            System.IO.FileInfo fi = new System.IO.FileInfo(envArgs[0]);
                                            if (!ServiceInstaller.Install(fi.FullName, info.Name, info.DisplayName, info.Description, info.ServiceType, info.ServiceAccessType, info.ServiceStartType, info.ServiceErrorControl))
                                            {
                                                throw new ServiceInstallException("Unable to install service \"" + info.DisplayName + "\"");
                                            }
                                            if (!s.Install())
                                            {
                                                throw new ServiceInstallException("Service was not able to install itself correctly.");
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //Always check to see if the service is installed and if it isn't,
                                    //then go ahead and install it...
                                    if (!IsServiceInstalled(info.Name))
                                    {
                                        string[] envArgs = Environment.GetCommandLineArgs();
                                        if (envArgs.Length > 0)
                                        {
                                            System.IO.FileInfo fi = new System.IO.FileInfo(envArgs[0]);
                                            if (!ServiceInstaller.Install(fi.FullName, info.Name, info.DisplayName, info.Description, info.ServiceType, info.ServiceAccessType, info.ServiceStartType, info.ServiceErrorControl))
                                            {
                                                throw new ServiceInstallException("Unable to install service \"" + info.DisplayName + "\"");
                                            }
                                            if (!s.Install())
                                            {
                                                throw new ServiceInstallException("Service was not able to install itself correctly.");
                                            }
                                        }
                                    }

                                    ServicesAPI.SERVICE_TABLE_ENTRY entry = new ServicesAPI.SERVICE_TABLE_ENTRY();
                                    entry.lpServiceName = info.Name;
                                    entry.lpServiceProc = new ServicesAPI.ServiceMainProc(s.baseServiceMain);
                                    alDispatchTables.Add(entry);
                                    s.Debug = false;
                                }
                            }
                        }
                        break;   //We can break b/c we only allow ONE instance of this attribute per object...
                    }
                }
            }

            if (alDispatchTables.Count > 0)
            {
                //Add a null entry to tell the API it's the last entry in the table...
                ServicesAPI.SERVICE_TABLE_ENTRY entry = new ServicesAPI.SERVICE_TABLE_ENTRY();
                entry.lpServiceName = null;
                entry.lpServiceProc = null;
                alDispatchTables.Add(entry);

                ServicesAPI.SERVICE_TABLE_ENTRY[] table = (ServicesAPI.SERVICE_TABLE_ENTRY[])alDispatchTables.ToArray(typeof(ServicesAPI.SERVICE_TABLE_ENTRY));
                if (ServicesAPI.StartServiceCtrlDispatcher(table) == 0)
                {
                    //There was an error. What was it?
                    switch (Marshal.GetLastWin32Error())
                    {
                    case ServicesAPI.ERROR_INVALID_DATA:
                        throw new ServiceStartupException(
                                  "The specified dispatch table contains entries that are not in the proper format.");

                    case ServicesAPI.ERROR_SERVICE_ALREADY_RUNNING:
                        throw new ServiceStartupException("A service is already running.");

                    case ServicesAPI.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                        //Executed when in Console Mode

                        foreach (var s in alServices)
                        {
                            ServiceContainer sc = new ServiceContainer(s);
                            s.Debug = true;
                            s.args  = Args;
                            sc.Start();
                        }

                        //throw new ServiceStartupException("A service is being run as a console application");
                        //"A service is being run as a console application. Try setting the Service attribute's \"Debug\" property to true if you're testing an application."
                        //If we've started up as a console/windows app, then we'll get this error in which case we treat the program
                        //like a normal app instead of a service and start it up in "debug" mode...
                        break;

                    default:
                        throw new ServiceStartupException(
                                  "An unknown error occurred while starting up the service(s).");
                    }
                }
                else
                {
                    //Service Mode
                    DebugLogger.IsConsole = false;
                }
            }
        }
Example #54
0
        public static RenderRespnose RenderJs(CommandDiskSourceProvider sourceProvider, RenderOption option, RenderContext context, string RelativeUrl)
        {
            var fullname = sourceProvider.GetFullFileName(context, RelativeUrl);

            if (string.IsNullOrEmpty(fullname))
            {
                return(new RenderRespnose()
                {
                    Body = null
                });
            }

            // cache
            if (RelativeUrl.ToLower().Contains("monaco"))
            {
                context.Response.Headers["Expires"] = DateTime.UtcNow.AddDays(7).ToString("r");
            }

            if (option.EnableMultilingual && RelativeUrl.ToLower().EndsWith(option.MultilingualJsFile))
            {
                return(RenderJsLangFile(fullname, context));
            }

            System.IO.FileInfo info = new System.IO.FileInfo(fullname);

            if (info != null && info.LastWriteTime != null)
            {
                JsRenderPlan renderplan = null;

                Guid hash = Lib.Security.Hash.ComputeGuidIgnoreCase(info.LastWriteTime.ToLongTimeString());

                var cacheplan = GetJs(RelativeUrl);

                if (cacheplan != null && cacheplan.Hash == hash)
                {
                    renderplan = cacheplan;
                }

                //either not key found not hash not the same.
                if (renderplan == null)
                {
                    string fulltext = VirtualResources.ReadAllText(fullname);

                    renderplan       = new JsRenderPlan();
                    renderplan.Tasks = GetJsRenderPlan(fulltext);
                    renderplan.Hash  = hash;
                    SetJs(RelativeUrl, renderplan);
                }

                if (renderplan != null)
                {
                    string result = string.Empty;
                    foreach (var task in renderplan.Tasks)
                    {
                        result += task.Render(sourceProvider, option, context, RelativeUrl);
                    }
                    return(new RenderRespnose()
                    {
                        Body = result, ContentType = "application/javascript"
                    });
                }
            }
            else
            {
                return(new RenderRespnose()
                {
                    Body = null
                });
            }

            return(new RenderRespnose()
            {
                Body = null
            });
        }
        public void ForceBuildOfBadProjectAfterGoodWithDefaultLabelerWithInitialBuildLabelMustHaveInitialBuildLabelAsLastBuildLabel()
        {
            // in the labeller is a comparison with previous integration result, and an ITaskResult that always returns true for CheckIfSuccess
            // this looks weird and should be investigated
            // old part of the codebase since 2009


            const string ProjectName1      = "LabelTest";
            string       IntegrationFolder = System.IO.Path.Combine("scenarioTests", ProjectName1);
            string       WorkingFolder     = System.IO.Path.Combine(IntegrationFolder, "wf");
            string       CCNetConfigFile   = System.IO.Path.Combine("IntegrationScenarios", "Simple02.xml");
            string       ProjectStateFile  = new System.IO.FileInfo(ProjectName1 + ".state").FullName;

            string CheckFileOfConditionalTask = System.IO.Path.Combine(WorkingFolder, "checkFile.txt");


            IntegrationCompleted.Add(ProjectName1, false);

            Log("Clear existing state file, to simulate first run : " + ProjectStateFile);
            System.IO.File.Delete(ProjectStateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(IntegrationFolder))
            {
                System.IO.Directory.Delete(IntegrationFolder, true);
            }


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            CCNet.Remote.Messages.ProjectRequest        pr1 = new CCNet.Remote.Messages.ProjectRequest(null, ProjectName1);


            Log("Making CruiseServerFactory");
            CCNet.Core.CruiseServerFactory csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + CCNetConfigFile);
            using (var cruiseServer = csf.Create(true, CCNetConfigFile))
            {
                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(cruiseServer_IntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                System.IO.File.WriteAllText(CheckFileOfConditionalTask, "hello");

                System.Threading.Thread.Sleep(250); // give time to start


                Log("Forcing build - conditional ok");
                CheckResponse(cruiseServer.ForceBuild(pr1));


                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    Log(" waiting ...");
                }

                IntegrationCompleted[ProjectName1] = false;
                System.IO.File.Delete(CheckFileOfConditionalTask);
                System.Threading.Thread.Sleep(250); // give time to finish delete


                Log("Forcing build - conditional Not ok");
                CheckResponse(cruiseServer.ForceBuild(pr1));


                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    Log(" waiting ...");
                }


                // un-subscribe to integration complete
                cruiseServer.IntegrationCompleted -= new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(cruiseServer_IntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");
            }

            Log("Checking the data");
            Assert.AreEqual(1, psr.Projects.Count, "Amount of projects in configfile is not correct." + CCNetConfigFile);

            CCNet.Remote.ProjectStatus ps = null;

            Log("checking data of project " + ProjectName1);
            foreach (var p in psr.Projects)
            {
                if (p.Name == ProjectName1)
                {
                    ps = p;
                }
            }

            // 1 good build and 1 bad

            Assert.AreEqual(ProjectName1, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Failure, ps.BuildStatus);
            Assert.AreEqual("bad task", ps.CurrentMessage, "message should be the descripton / name of the failing task");
            Assert.AreEqual("1.5.1603", ps.LastBuildLabel, "do not increase label, because the increase on failure is set to false");
            Assert.AreEqual("1.5.1603", ps.LastSuccessfulBuildLabel, "do not increase label, because the increase on failure is set to false");
        }
Example #56
0
        private static async Task <bool> Process(System.Net.Http.HttpClient client, string path, Uri uri, System.Threading.CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(cancellationToken);
            }

            Console.Write("Processing {0}", uri);
            var fileName = GetFileName(path, uri);

            if (!update && System.IO.File.Exists(fileName))
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(" - Exists");
                Console.ForegroundColor = DefaultConsoleColor;
                return(true);
            }

            // get the head
            IEnumerable <Uri> links;

            using (var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Head, uri))
            {
                System.Net.Http.HttpResponseMessage response;
                if (update)
                {
                    var fileInfo     = new System.IO.FileInfo(fileName);
                    var modifiedDate = fileInfo.LastWriteTimeUtc;
                    request.Headers.IfModifiedSince = modifiedDate;
                }

                try
                {
                    response = await client.SendAsync(request, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken);
                }
                catch (System.Net.Http.HttpRequestException ex)
                {
                    WriteError(ex);
                    return(false);
                }

                using (response)
                {
                    Console.ForegroundColor = response.IsSuccessStatusCode ? ConsoleColor.Green : ConsoleColor.DarkRed;
                    Console.Write(" - {0}", response.StatusCode);
                    Console.ForegroundColor = DefaultConsoleColor;
                    if (!response.IsSuccessStatusCode)
                    {
                        Console.WriteLine();
                        return(true);
                    }

                    if (uri != request.RequestUri)
                    {
                        WriteInformation(" - redirect detected");
                        return(true);
                    }

                    if (response.Content == null)
                    {
                        WriteInformation(" - no content detected");
                        return(true);
                    }

                    Console.WriteLine();
                    if (response.Content.Headers.ContentType != null && response.Content.Headers.ContentType.MediaType == "text/html")
                    {
                        // process this as a HTML page
                        links = await ProcessHtml(client, path, fileName, uri, cancellationToken);
                    }
                    else
                    {
                        // create the file name
                        var contentLength = response.Content.Headers.ContentLength;
                        System.Diagnostics.Debug.Assert(contentLength.HasValue && contentLength.Value > 0);

                        // check to see if this exists
                        if (System.IO.File.Exists(fileName))
                        {
                            var fileInfo   = new System.IO.FileInfo(fileName);
                            var fileLength = fileInfo.Length;

                            if (fileLength == contentLength)
                            {
                                // check the date/time
                                if (response.Content.Headers.Contains("Last-Modified"))
                                {
                                    var lastModified = DateTime.Parse(response.Content.Headers.GetValues("Last-Modified").First());
                                    if (fileInfo.LastWriteTime != lastModified)
                                    {
                                        fileInfo.LastWriteTime = lastModified;
                                        fileInfo.Refresh();
                                    }
                                }

                                return(true);
                            }
                        }

                        int count = 0;
                        while (!await ProcessLink(client, fileName, uri, contentLength, cancellationToken) && count < RetryCount)
                        {
                            count++;
                            System.Threading.Thread.Sleep(5000);
                        }

                        if (System.IO.File.Exists(fileName) && contentLength.HasValue)
                        {
                            var fileInfo   = new System.IO.FileInfo(fileName);
                            var fileLength = fileInfo.Length;

                            if (fileLength != contentLength)
                            {
                                WriteWarning("{0}Invalid length, expected {1} - got {2}", currentIndent, contentLength, fileLength);
                                return(false);
                            }
                        }

                        return(true);
                    }
                }
            }

            if (links != null)
            {
                await ProcessUris(client, path, links, cancellationToken);
            }

            return(true);
        }
        public void ForceBuildOfGoodProjectWithDefaultLabelerWithInitialBuildLabelMustHaveInitialBuildLabelAsLastBuildLabel()
        {
            const string ProjectName1 = "LabelTest";

            string IntegrationFolder = System.IO.Path.Combine("scenarioTests", ProjectName1);
            string WorkingFolder     = System.IO.Path.Combine(IntegrationFolder, "wf");
            string CCNetConfigFile   = System.IO.Path.Combine("IntegrationScenarios", "Simple02.xml");
            string ProjectStateFile  = new System.IO.FileInfo(ProjectName1 + ".state").FullName;

            string CheckFileOfConditionalTask = System.IO.Path.Combine(WorkingFolder, "checkFile.txt");


            IntegrationCompleted.Add(ProjectName1, false);

            Log("Clear existing state file, to simulate first run : " + ProjectStateFile);
            System.IO.File.Delete(ProjectStateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(IntegrationFolder))
            {
                System.IO.Directory.Delete(IntegrationFolder, true);
            }


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            CCNet.Remote.Messages.ProjectRequest        pr1 = new CCNet.Remote.Messages.ProjectRequest(null, ProjectName1);


            Log("Making CruiseServerFactory");
            CCNet.Core.CruiseServerFactory csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + CCNetConfigFile);
            using (var cruiseServer = csf.Create(true, CCNetConfigFile))
            {
                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(cruiseServer_IntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                System.IO.File.WriteAllText(CheckFileOfConditionalTask, "hello");

                System.Threading.Thread.Sleep(250); // give time to start


                Log("Forcing build - conditional ok");
                CheckResponse(cruiseServer.ForceBuild(pr1));


                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    Log(" waiting ...");
                }

                // un-subscribe to integration complete
                cruiseServer.IntegrationCompleted -= new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(cruiseServer_IntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");
            }

            Log("Checking the data");
            Assert.AreEqual(1, psr.Projects.Count, "Amount of projects in configfile is not correct." + CCNetConfigFile);

            CCNet.Remote.ProjectStatus ps = null;

            Log("checking data of project " + ProjectName1);
            foreach (var p in psr.Projects)
            {
                if (p.Name == ProjectName1)
                {
                    ps = p;
                }
            }

            // 1 good build

            Assert.AreEqual(ProjectName1, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Success, ps.BuildStatus);
            Assert.AreEqual(string.Empty, ps.CurrentMessage, "message should be empty after ok build");
            Assert.AreEqual("1.5.1603", ps.LastBuildLabel, "after ok build with initial label, the result must be the inital label");
            Assert.AreEqual("1.5.1603", ps.LastSuccessfulBuildLabel, "after ok build with initial label, the result must be the inital label");
            Assert.AreEqual(0, ps.Messages.Length);
        }
Example #58
0
        /// <summary>
        /// Metoda koja dohvaca lokaciju mjesta(foldera) unutar kojega se nalazi datoteka
        /// </summary>
        /// <param name="lokacijaDatoteke">Putanja do datoteke (njena lokacija)</param>
        /// <returns>Vraća lokaciju (putanju) do mjesta (foldera) u kojem
        /// se datoteka nalazi</returns>
        public static string DohvatiLokacijuMjestaDatoteke(string lokacijaDatoteke)
        {
            string lokacijaMjesta = new System.IO.FileInfo(lokacijaDatoteke).Directory.FullName;

            return(lokacijaMjesta);
        }
Example #59
0
 /// <summary>建立私用的LogManager類別</summary>
 /// <param name="configFile">log4net 參數存放位置</param>
 /// <param name="logName">私用鍵值</param>
 public LogManager(System.IO.FileInfo configFile, string logName) : this(configFile, logName, "")
 {
 }
        public void ForceBuildOf1ProjectAndCheckBasicPropertiesOfProjectStatus()
        {
            const string ProjectName1 = "test01";
            const string ProjectName2 = "test02";

            string IntegrationFolder = System.IO.Path.Combine("scenarioTests", ProjectName1);
            string CCNetConfigFile   = System.IO.Path.Combine("IntegrationScenarios", "Simple.xml");
            string ProjectStateFile  = new System.IO.FileInfo(ProjectName1 + ".state").FullName;

            IntegrationCompleted.Add(ProjectName1, false);
            IntegrationCompleted.Add(ProjectName2, false);

            Log("Clear existing state file, to simulate first run : " + ProjectStateFile);
            System.IO.File.Delete(ProjectStateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(IntegrationFolder))
            {
                System.IO.Directory.Delete(IntegrationFolder, true);
            }


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            CCNet.Remote.Messages.ProjectRequest        pr1 = new CCNet.Remote.Messages.ProjectRequest(null, ProjectName1);
            CCNet.Remote.Messages.ProjectRequest        pr2 = new CCNet.Remote.Messages.ProjectRequest(null, ProjectName2);


            Log("Making CruiseServerFactory");
            CCNet.Core.CruiseServerFactory csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + CCNetConfigFile);
            using (var cruiseServer = csf.Create(true, CCNetConfigFile))
            {
                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(cruiseServer_IntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                System.Threading.Thread.Sleep(250); // give time to start

                Log("Forcing build");
                CheckResponse(cruiseServer.ForceBuild(pr1));

                System.Threading.Thread.Sleep(250); // give time to start the build

                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    Log(" waiting ...");
                }

                // un-subscribe to integration complete
                cruiseServer.IntegrationCompleted -= new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(cruiseServer_IntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");
            }

            Log("Checking the data");
            Assert.AreEqual(2, psr.Projects.Count, "Amount of projects in configfile is not correct." + CCNetConfigFile);

            CCNet.Remote.ProjectStatus ps = null;

            Log("checking data of project " + ProjectName1);
            foreach (var p in psr.Projects)
            {
                if (p.Name == ProjectName1)
                {
                    ps = p;
                }
            }

            Assert.AreEqual(ProjectName1, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Success, ps.BuildStatus);
            Assert.IsTrue(ps.Activity.IsSleeping(), "Activity should be sleeping after an integration");
            Assert.AreEqual(ps.Category, "cat1");
            Assert.AreEqual(string.Empty, ps.CurrentMessage, "message should be empty after an ok build");
            Assert.AreEqual("first testing project", ps.Description);
            Assert.AreEqual("1", ps.LastBuildLabel);
            Assert.AreEqual("1", ps.LastSuccessfulBuildLabel);
            Assert.AreEqual(0, ps.Messages.Length);
            Assert.AreEqual("Q1", ps.Queue);
            Assert.AreEqual(1, ps.QueuePriority);
            Assert.AreEqual(System.Environment.MachineName, ps.ServerName);
            Assert.AreEqual(CCNet.Remote.ProjectIntegratorState.Running, ps.Status);
            Assert.AreEqual("http://confluence.public.thoughtworks.org", ps.WebURL);


            Log("checking data of project " + ProjectName2);
            foreach (var p in psr.Projects)
            {
                if (p.Name == ProjectName2)
                {
                    ps = p;
                }
            }

            Assert.IsFalse(IntegrationCompleted[ProjectName2], "integration not done, event may not be fired");
            Assert.AreEqual(ProjectName2, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Unknown, ps.BuildStatus);
            Assert.IsTrue(ps.Activity.IsSleeping(), "Activity should be still sleeping");
            Assert.AreEqual(ps.Category, "cat2");
            Assert.AreEqual(string.Empty, ps.CurrentMessage, "message should still be empty");
            Assert.AreEqual("second testing project", ps.Description);
            Assert.AreEqual("UNKNOWN", ps.LastBuildLabel);
            Assert.AreEqual("UNKNOWN", ps.LastSuccessfulBuildLabel);
            Assert.AreEqual(0, ps.Messages.Length);
            Assert.AreEqual("Q1", ps.Queue);
            Assert.AreEqual(2, ps.QueuePriority);
            Assert.AreEqual(System.Environment.MachineName, ps.ServerName);
            Assert.AreEqual(CCNet.Remote.ProjectIntegratorState.Unknown, ps.Status);
            Assert.AreEqual("http://" + System.Environment.MachineName + "/ccnet", ps.WebURL, "Default url not correct");
        }