Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            try
            {
                FileOps fileOps = new FileOps();

                fileOps.FileOpen("C:\\test.txt");
                fileOps.FileRead();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Ejemplo n.º 2
0
        public AssemblyDateTimeAttribute()
        {
#if EAGLE
            //
            // NOTE: This should be reliable.
            //
            uint timeStamp = 0;

            if (FileOps.GetPeFileTimeStamp(
                    GlobalState.GetAssemblyLocation(), ref timeStamp) &&
                TimeOps.SecondsToDateTime(
                    timeStamp, ref dateTime, TimeOps.PeEpoch))
            {
                return;
            }
#endif

            dateTime = DateTime.MinValue;
        }
        public static void GenerateCode()
        {
            if (!AutoGenerate)
            {
                return;
            }
            UnityDrawerStatics.RefreshAll();
            EntityListFormatted = @"public static class Entities
		{"        ;

            foreach (var ent in UnityDrawerStatics.EntityList)
            {
                string entName = FileOps.GetStringAfterLastSlash(ent).StripNonAlphanumeric();
                EntityListFormatted += "\n\t\t\tpublic const string " + entName + " = \"" + ent + "\";";
            }

            EntityListFormatted += @"
		}
		
		public static class Prefabs
		{"        ;
            foreach (var pre in UnityDrawerStatics.PrefabList)
            {
                string preName = FileOps.GetStringAfterLastSlash(pre).StripNonAlphanumeric();
                EntityListFormatted += "\n\t\t\tpublic const string " + preName + " = \"" + pre + "\";";
            }

            EntityListFormatted += @"
		}"        ;

            string fullString = FileOps.ReplaceLineEndings(HEADER_FORMAT + EntityListFormatted + FOOTER_FORMAT);

            using (var file = File.Open(ResFilePath, FileMode.Create))
            {
                using (var writer = new StreamWriter(file))
                {
                    writer.Write(fullString);
                }
            }

            AssetDatabase.Refresh();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Handles the HideFolderRequested event.
        /// </summary>
        /// <param name="sender">The sender<see cref="object"/>.</param>
        /// <param name="e">The e<see cref="EventArgs"/>.</param>
        private void Vm_HideFolderRequested(object sender, EventArgs e)
        {
            Debug.Assert(sender is FolderViewModel);
            var vm = sender as FolderViewModel;

            var proceed = App.LastChance("Hide Folder Request", $"Hiding {vm.FolderName}", $"This operation will move {vm.FolderName} from the community directory to the hidden directory. Is this what you want to do?.");
            var su      = Locator.SetupViewModel;

            if (proceed)
            {
                if (FileOps.Hide(vm.FolderName, su.CommunityFolder, su.HiddenFilesFolder))
                {
                    vm.IsHidden = true;
                    DbCore.Update(vm);
                    return;
                }

                App.Inform("Hide Folder Request Error", $"{vm.FolderName} could not be hidden. Synchronization may be necessary.");
            }
        }
Ejemplo n.º 5
0
        public void Update <TEntity>(TEntity entity) where TEntity : BaseEntity, new()
        {
            string file      = $"storage_{typeof(TEntity).Name}.json";
            string filePath  = Path.Combine(_storageDirectory, file);
            bool   fileExist = FileOps.IsExistingFile(filePath);

            if (!fileExist)
            {
                throw new Exception("Update operation failed! Stroage file not found.");
            }

            string          content  = FileOps.ReadText(filePath);
            IList <TEntity> dataList = (IList <TEntity>)_serializor.Deserialize <IEnumerable <TEntity> >(content);

            TEntity responseItem = dataList.SingleOrDefault(x => x.Id == entity.Id);

            if (responseItem == null)
            {
                throw new Exception($"Update operation failed! Item not found Type: {entity.GetType().Name} Id:{entity.Id}");
            }

            int index = dataList.IndexOf(responseItem);

            dataList[index] = entity;

            //responseItem = entity;

            content = _serializor.Serialize(dataList).ToString();
            if (fileExist)
            {
                FileOps.DeleteFile(filePath);
            }

            FileOps.WriteFile(
                filePath,
                content,
                new FileWriteOptions {
                OverwriteFileIfExists      = true,
                CreateDirectoryIfNotExists = true
            });
        }
Ejemplo n.º 6
0
        public void MergeFileHead_Success()
        {
            // arrange
            string           fileA      = "./tests/testdata/a.txt";
            string           fileB      = "./tests/testdata/b.txt";
            IDataSourceOps   ops        = new FileOps();
            HashSet <string> mergedHead = null;

            // act
            var head_A = ops.GetHead(fileA);
            var head_B = ops.GetHead(fileB);

            mergedHead = ops.MergeHead(new List <string>()
            {
                head_A, head_B
            });

            // assert
            Assert.IsNotNull(mergedHead);
            Assert.IsTrue(mergedHead.Count > 0);
        }
Ejemplo n.º 7
0
        static public bool BlockFile(string path)
        {
            try
            {
                path = Environment.ExpandEnvironmentVariables(path);
                if (!FileOps.TakeOwn(path))
                {
                    return(false);
                }

                FileSecurity ac = File.GetAccessControl(path);
                ac.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(FileOps.SID_World), FileSystemRights.ExecuteFile, AccessControlType.Deny));
                File.SetAccessControl(path, ac);
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Ejemplo n.º 8
0
        ///////////////////////////////////////////////////////////////////////

        #region Application Exit Event Handler
        private static void ApplicationExit(
            object sender,
            EventArgs e
            )
        {
            Configuration configuration;

            lock (syncRoot)
            {
                configuration = savedConfiguration;
            }

            TraceOps.Trace(configuration, "Exiting.", TraceCategory);

            string error = null;

            if (!FileOps.DeleteInUse(configuration, ref error))
            {
                Fail(configuration, assembly, error, TraceCategory);
            }
        }
Ejemplo n.º 9
0
        public void LoadPositionsFromConfigFile(MainForm f1)
        {
            LogLib.WriteLine("Loading Position.Xml", LogLevel.Debug);
            var configFile = FileOps.CombineCfgDir("positions.xml");

            if (File.Exists(configFile))
            {
                try
                {
                    f1.dockPanel.LoadFromXml(configFile, f1.m_deserializeDockContent);
                }
                catch (Exception ex)
                {
                    LogLib.WriteLine("Error loading config from positions.xml: ", ex);
                    // Re-Set up initial windows - might have bad or incompatible positions file
                    defaultstates();
                }
            }
            else
            {
                // Set up initial windows, when no previous window layout exists
                defaultstates();
            }

            void defaultstates()
            {
                f1.mapPane.Show(f1.dockPanel, DockState.Document);

                f1.SpawnList.Show(f1.dockPanel, DockState.DockLeft);

                f1.SpawnTimerList.Show(f1.dockPanel, DockState.DockTop);

                f1.GroundItemList.Show(f1.dockPanel, DockState.DockBottom);

                f1.SpawnTimerList.DockState = DockState.DockLeft;

                f1.GroundItemList.DockState = DockState.DockLeft;
            }
        }
Ejemplo n.º 10
0
        public bool RemoveDomainBlocklist(string Url)
        {
            DomainBlocklist Blocklist = null;

            ListLock.EnterWriteLock();
            if (Blocklists.TryGetValue(Url, out Blocklist))
            {
                Blocklists.Remove(Url);
            }
            ListLock.ExitWriteLock();
            if (Blocklist == null)
            {
                return(false);
            }

            string fileName = App.dataPath + @"\DnsBlockLists\" + Blocklist.FileName;

            FileOps.DeleteFile(fileName);

            ReloadBlocklists = MiscFunc.GetUTCTimeMs() + 5 * 1000; // schedule reaload
            return(true);
        }
Ejemplo n.º 11
0
        public Entity CreateEntityFromTemplate(string entityName)
        {
            //Debug.Log($"{entityName} creating from template");

            object deserialized = null;

            entityName = FileOps.GetStringAfterLastSlash(entityName);

            _serializer.TryDeserialize(
                _entityTemplates[entityName],
                typeof(Entity),
                ref deserialized
                );

            Entity newEntity = (Entity)deserialized;

            InitializeNewEntity(newEntity);
            engine?.EntityList.Add(newEntity);

            engine?.TriggerEntityAdded(newEntity);
            return(newEntity);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Handles the DeleteSelectedItemsRequested event.
        /// </summary>
        /// <param name="sender">The sender<see cref="object"/>.</param>
        /// <param name="e">The e<see cref="EventArgs"/>.</param>
        private void Vm_DeleteSelectedFoldersRequested(object sender, EventArgs e)
        {
            Debug.Assert(sender is MainViewModel);
            var vm = sender as MainViewModel;

            var selectedToDelete = new List <FolderViewModel>();

            foreach (var item in vm.SelectedFoldersCollection)
            {
                selectedToDelete.Add(item);
            }

            var folderNames = Environment.NewLine +
                              Environment.NewLine;

            foreach (var item in selectedToDelete)
            {
                folderNames += item.FolderName + Environment.NewLine;
            }

            var proceed = App.LastChance("Delete Folders Request", $"Deleting Selected Folders", $"This operation will delete these (this) {selectedToDelete.Count} folder(s) from the community or hidden directories:" +
                                         folderNames +
                                         Environment.NewLine +
                                         "Is this what you want to do?");

            if (proceed)
            {
                var hiddenFolder    = AppSettings.Default.HiddenFilesFolder;
                var communityFolder = AppSettings.Default.CommunityFolder;

                foreach (var item in selectedToDelete)
                {
                    FileOps.Delete(item.FolderName, item.IsHidden ? hiddenFolder : communityFolder);
                    vm.FolderCollection.Remove(item);
                }

                DbCore.Delete(selectedToDelete);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Returns complete model of attachment
        /// Saves attachment to DB
        /// </summary>
        /// <param name="callingForm"></param>
        /// <returns></returns>
        public static List <AttachmentModel> AttachFile(Form callingForm, string PID, string[] labels)
        {
            GV.MODE = Mode.Add_Attachment;
            AttachmentModel model = new AttachmentModel();
            frmAttType      frm   = new frmAttType(model);

            frm.Labels = labels;
            EventHandler <AttachmentModel> Frm_TypeReadyEvent = null;

            frm.TypeReadyEvent += Frm_TypeReadyEvent;

            OpenFileDialog openFD = new OpenFileDialog();

            openFD.Title = "Save Attachment";
            string myDox = Environment.SpecialFolder.MyDocuments.ToString();

            openFD.InitialDirectory = myDox;
            openFD.RestoreDirectory = true;
            openFD.Multiselect      = false;

            if (openFD.ShowDialog() == DialogResult.OK)
            {
                string fullFileName = openFD.FileName;
                string file         = Path.GetFileName(fullFileName);
                model.FileToSave  = fullFileName;
                model.DisplayText = file;
                model.PID         = PID;
                //FC.SetFormPosition(frm);
                callingForm.BringToFront();
                frm.ShowDialog();
            }
            string fileName = GlobalConfig.AttachmentPath + "\\" + model.PID + "\\" + model.DisplayText;

            FileOps.SaveAttFile(model);
            GlobalConfig.Connection.InsertInto_tblAttachments(model);
            List <AttachmentModel> aList = GlobalConfig.Connection.GetAttachments(PID);

            return(aList);
        }
Ejemplo n.º 14
0
        static public bool UnBlockFile(string path)
        {
            try
            {
                path = Environment.ExpandEnvironmentVariables(path);
                if (!FileOps.TakeOwn(path))
                {
                    return(false);
                }

                FileSecurity ac = File.GetAccessControl(path);
                AuthorizationRuleCollection rules = ac.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); // get as SID not string
                foreach (FileSystemAccessRule rule in rules)
                {
                    if (!rule.IdentityReference.ToString().Equals(FileOps.SID_World))
                    {
                        continue;
                    }
                    if (rule.FileSystemRights != FileSystemRights.ExecuteFile)
                    {
                        continue;
                    }
                    if (rule.AccessControlType != AccessControlType.Deny)
                    {
                        continue;
                    }
                    ac.RemoveAccessRule(rule);
                }
                File.SetAccessControl(path, ac);
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Ejemplo n.º 15
0
        public TEntity Insert <TEntity>(TEntity entity) where TEntity : BaseEntity, new()
        {
            IList <TEntity> responseList;
            string          content = default(string);

            string file      = $"storage_{typeof(TEntity).Name}.json";
            string filePath  = Path.Combine(_storageDirectory, file);
            bool   fileExist = FileOps.IsExistingFile(filePath);

            if (fileExist)
            {
                content      = FileOps.ReadText(filePath);
                responseList = (IList <TEntity>)_serializor.Deserialize <IEnumerable <TEntity> >(content);
            }
            else
            {
                responseList = new List <TEntity>();
            }

            SetId(entity);
            responseList.Add(entity);
            content = _serializor.Serialize(responseList).ToString();
            if (fileExist)
            {
                FileOps.DeleteFile(filePath);
            }

            FileOps.WriteFile(
                filePath,
                content,
                new FileWriteOptions {
                OverwriteFileIfExists      = true,
                CreateDirectoryIfNotExists = true
            });

            return(entity);
        }
Ejemplo n.º 16
0
        public void SaveEntityToJson()
        {
            _newEnt = new Entity(FileOps.GetEntityNameFromFullName(EntityName));
            //_newEnt = new Entity(EntityName);
            Debug.Log($"Saving entity: {EntityName}");
            foreach (var typ in ComponentPools)
            {
                foreach (var cmp in typ.Value)
                {
                    //Debug.Log($"Adding comp from gui: {cmp.ObjectType.Name}");
                    _newEnt.AddComponentFromGUI(cmp);
                    cmp.SetId(Guid.Empty);                     //Keep this out of prod code
                }
            }
            _newEnt.IsPooled = ShouldPoolEntity;

            Serializer.TrySerialize(typeof(Entity), _newEnt, out _data).AssertSuccess();

            var filePath = Application.dataPath + "/Resources/Entities/" + EntityName + ".json";

            Directory.CreateDirectory(Application.dataPath + "/Resources/Entities/" + FileOps.GetTypeFromFullName(EntityName) + "/");

            using (var file = File.Open(filePath, FileMode.Create))
            {
                using (var writer = new StreamWriter(file))
                {
                    fsJsonPrinter.PrettyJson(_data, writer);
                }
            }
            IsDirty = false;

            AssetDatabase.Refresh();

            UnityDrawerStatics.RefreshEntityList();
            AvoidDirtyFlag = true;
        }
Ejemplo n.º 17
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(FileOps.FormatSize((UInt64)value) + "/s");
 }
Ejemplo n.º 18
0
        private void Trv_commandTreeView_DoubleClick(object sender, EventArgs e)
        {
            // todo add network capture tcpdump
            try
            {
                string tag;

                if ((tag = trv_commandTreeView.SelectedNode.Tag.ToString()) != null)
                {
                    if (tag.StartsWith("adb ") || tag.StartsWith("fastboot "))
                    {
                        // seriennummer für fastboot implementieren
                        cmdProcess.StartProcessing(tag, formMethods.SelectedDevice());
                    }

                    else if (tag.StartsWith("#"))
                    {
                        switch (tag)
                        {
                        case "#prop":
                            new SetProp(cmdProcess, formMethods).Show();
                            break;

                        case "#screenshot":

                            if (!String.IsNullOrEmpty(formMethods.SelectedDevice()))
                            {
                                saveFileDialog.FileName = "screenshot_" + DateTime.Now.ToString().Replace(' ', '_').Replace(':', '.');
                                saveFileDialog.Filter   = "PNG Image(.png)|*.png";
                                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                                {
                                    cmdProcess.StartProcessing("adb shell screencap -p > " + saveFileDialog.FileName, formMethods.SelectedDevice());
                                }
                            }

                            break;

                        case "#screenrecord":
                            if (screenRecord == null || screenRecord.IsDisposed)
                            {
                                screenRecord = new ScreenRecord(cmdProcess, formMethods);
                                screenRecord.Show();
                            }
                            else
                            {
                                screenRecord.Focus();
                            }
                            break;

                        case "#spoofmac":
                            if (spoofMac == null || spoofMac.IsDisposed)
                            {
                                spoofMac = new SpoofMac(cmdProcess, formMethods);
                                spoofMac.Show();
                            }
                            else
                            {
                                spoofMac.Focus();
                            }
                            break;

                        case "#resolution":
                            if (resolutionChange == null || resolutionChange.IsDisposed)
                            {
                                resolutionChange = new ResolutionChange(cmdProcess, formMethods);
                                resolutionChange.Show();
                            }
                            else
                            {
                                resolutionChange.Focus();
                            }
                            break;

                        case "#density":
                            if (densityChange == null || densityChange.IsDisposed)
                            {
                                densityChange = new Density(cmdProcess, formMethods);
                                densityChange.Show();
                            }
                            else
                            {
                                densityChange.Focus();
                            }
                            break;

                        case "#files":
                            if (fileOps == null || fileOps.IsDisposed)
                            {
                                fileOps = new FileOps(cmdProcess, formMethods);
                                fileOps.Show();
                            }
                            else
                            {
                                fileOps.Focus();
                            }
                            break;

                        case "#installuninstall":
                            if (installUninstall == null || installUninstall.IsDisposed)
                            {
                                installUninstall = new InstallUninstall(cmdProcess, formMethods);
                                installUninstall.Show();
                            }
                            else
                            {
                                installUninstall.Focus();
                            }
                            break;

                        case "#sideload":
                            if (sideLoad == null || sideLoad.IsDisposed)
                            {
                                sideLoad = new Sideload(cmdProcess, formMethods);
                                sideLoad.Show();
                            }
                            else
                            {
                                sideLoad.Focus();
                            }
                            break;

                        case "#backuprestore":
                            if (backupRestore == null || backupRestore.IsDisposed)
                            {
                                backupRestore = new BackupRestore(cmdProcess, formMethods);
                                backupRestore.Show();
                            }
                            else
                            {
                                backupRestore.Focus();
                            }
                            break;

                        case "#logcatadvanced":
                            if (logcatAdvanced == null || logcatAdvanced.IsDisposed)
                            {
                                logcatAdvanced = new LogcatAdvanced(cmdProcess, formMethods);
                                logcatAdvanced.Show();
                            }
                            else
                            {
                                logcatAdvanced.Focus();
                            }
                            break;

                        case "#credits":
                            new Credits().ShowDialog();
                            break;
                        }
                    }
                }
            }
            catch (Exception) { }
        }
Ejemplo n.º 19
0
        public bool Load(string FilePath, Dictionary <string, TweakPresets.Category> Categorys)
        {
            if (!File.Exists(FilePath))
            {
                return(false);
            }

            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(FilePath);

                double fileVersion = 0.0;
                double.TryParse(xDoc.DocumentElement.GetAttribute("Version"), out fileVersion);
#if false
                if (fileVersion != xmlVersion)
                {
                    if (fileVersion != 0 && fileVersion < xmlVersion)
                    {
                        FileOps.MoveFile(FilePath, App.dataPath + @"\Tweaks_old.xml", true);
                        Priv10Logger.LogWarning(App.EventIDs.AppWarning, null, App.EventFlags.Notifications, Translate.fmt("msg_tweaks_updated", App.dataPath + @"\Tweaks_old.xml"));
                    }
                    else
                    {
                        Priv10Logger.LogError("Failed to load tweaklist, unknown file version {0}, expected {1}", fileVersion, xmlVersion);
                    }
                    return(false);
                }
#endif

                int TotalCount = 0;
                int ErrorCount = 0;

                foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
                {
                    TotalCount++;
                    Tweak tweak = new Tweak();
                    if (!tweak.Load(node))
                    {
                        ErrorCount++;
                        continue;
                    }

                    TweakPresets.Category tweak_cat;
                    if (!Categorys.TryGetValue(tweak.Category, out tweak_cat))
                    {
                        tweak_cat = new TweakPresets.Category(tweak.Category);
                        Categorys.Add(tweak.Category, tweak_cat);
                    }

                    tweak_cat.Add(tweak);
                }

#if false
                if (ErrorCount != 0)
                {
                    Priv10Logger.LogError("Failed to load {0} tweak entries out of {1}", ErrorCount, TotalCount);
                }
                Priv10Logger.LogInfo("TweakManager loaded {0} entries", TotalCount - ErrorCount);
#endif
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 20
0
        static public void ExportLayersFromDrawings()
        {
            Document doc   = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database docDB = doc.Database;
            Editor   ed    = doc.Editor;

            string[] fileList = FileOps.selectFiles("Select all the files to export layers.", "dwg", "Select all the files to export layers.");
            if (fileList == null)
            {
                ed.WriteMessage("\nNo file selected, operation Termiated.\n");
                return;
            }

            Dictionary <string, List <string> > dwgLayers   = new Dictionary <string, List <string> >(); //to store the layers in each drawings
            Dictionary <string, List <string> > titleBlocks = new Dictionary <string, List <string> >(); //to store the number of titleblock in a drawing

            foreach (string file in fileList)
            {
                if (File.Exists(file))
                {
                    ed.WriteMessage($"Read layer from {file}\n");
                    try
                    {
                        Database db = new Database(false, true);
                        using (db)
                        {
                            db.ReadDwgFile(file, FileOpenMode.OpenForReadAndAllShare, false, null);
                            db.CloseInput(true);

                            Transaction tr = db.TransactionManager.StartTransaction();

                            using (tr)
                            {
                                ed.WriteMessage($"Start transition....\n");
                                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                                List <string> layers = new List <string>();
                                foreach (ObjectId id in lt)
                                {
                                    LayerTableRecord l       = tr.GetObject(id, OpenMode.ForWrite) as LayerTableRecord;
                                    string           name    = l.Name;
                                    string           revised = name.Trim().ToUpper(); //clean up the layer name

                                    if (!l.IsDependent)
                                    {
                                        if (!layers.Contains(revised))
                                        {
                                            layers.Add(revised);
                                        }
                                    }
                                }

                                List <string> blocks = new List <string>();
                                BlockTable    bt     = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                                //get the record from paper space
                                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.PaperSpace], OpenMode.ForRead) as BlockTableRecord;
                                foreach (ObjectId oId in btr)
                                {
                                    BlockReference br = tr.GetObject(oId, OpenMode.ForRead) as BlockReference; //get block reference
                                    if (oId.ObjectClass.DxfName == "INSERT")                                   //if this block is inserted
                                    {
                                        blocks.Add(br.Name);
                                    }
                                }
                                tr.Commit();

                                ed.WriteMessage($"End transition....\n");
                                dwgLayers.Add(file, layers);
                                titleBlocks.Add(file, blocks);
                            }
                            ed.WriteMessage("\n Finish reading " + System.IO.Path.GetFileName(file) + ".\n");
                        }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                    { ed.WriteMessage(ex.ToString() + Environment.NewLine); }
                }
                else
                {
                    ed.WriteMessage("File " + file + " does not exist.\n");
                }
            }

            Excel.createCSV(dwgLayers, "D:\\dwgLayers.csv");
            Excel.createCSV(titleBlocks, "D:\\dwgBlocks.csv");
            ed.WriteMessage("Done.");
        }
Ejemplo n.º 21
0
        //project to level 0 to find the intersect point
        static public void CheckElevationDifference()
        {
            string msg = string.Empty;

            double checkDistance = 0.55;

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;

            HostApplicationServices hs = HostApplicationServices.Current;
            string outputPath          = hs.FindFile(doc.Name, doc.Database, FindFileHint.Default);
            string logPath             = outputPath + "_log.log";

            System.IO.File.WriteAllText(logPath, msg);

            //get user input
            //select point input file
            ed.WriteMessage("Select the Excel file contains the door step points");
            string excelPath = FileOps.SelectFile();

            #region get Excel Sheet Name
            PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Sheet Name: ");
            pStrOpts.AllowSpaces = true;
            PromptResult pStrRes = doc.Editor.GetString(pStrOpts);
            string       shtName = pStrRes.StringResult;
            #endregion

            List <Point3d> doorStepPts = Excel.getAllpoint(doc, excelPath, shtName);

            PromptEntityResult per = ed.GetEntity("Select polylines");
            ObjectId           oid = per.ObjectId;

            ObjectIdCollection oDBO     = new ObjectIdCollection();
            List <Polyline3d>  poly3ds  = new List <Polyline3d>();
            List <Polyline3d>  poly3ds0 = new List <Polyline3d>();

            if (per.Status == PromptStatus.OK)
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);

                DBObject objPick = tr.GetObject(oid, OpenMode.ForRead);
                Entity   objEnt  = objPick as Entity;
                string   sLayer  = objEnt.Layer.ToString();

                oDBO = CADops.SelectAllPolyline(sLayer);
                foreach (ObjectId id in oDBO)
                {
                    Polyline3d pl = new Polyline3d();
                    System.IO.File.AppendAllText(logPath, $"{id}\n");
                    poly3ds0.Add(CADops.CreatePolylineOnXYPlane(doc, id, ref pl));
                    poly3ds.Add(pl);
                }
            }

            List <Point3d> output = new List <Point3d>();
            List <string>  data   = new List <string>();
            if (poly3ds.Count() > 0)
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);

                using (tr)
                {
                    List <Vector3d> vectorsAlongPath = new List <Vector3d>();
                    List <Vector3d> vectors          = CADops.getVectors(doorStepPts, doc, ref vectorsAlongPath);

                    //foreach (Point3d pt in doorStepPts)
                    for (int i = 0; i < doorStepPts.Count(); i++)
                    {
                        Point3d pt = doorStepPts[i];

                        Point3d pt0 = new Point3d(pt.X, pt.Y, 0);

                        Vector3d v   = vectors[i].GetNormal() * 5;
                        Matrix3d mat = Matrix3d.Displacement(v);
                        Point3d  npt = pt0.TransformBy(mat);

                        v   = vectors[i].GetNormal() * -5;
                        mat = Matrix3d.Displacement(v);
                        Point3d npt2 = pt0.TransformBy(mat);

                        //create a 2d line in XY plane
                        Line ln = new Line(npt, npt2);

                        btr.AppendEntity(ln);
                        tr.AddNewlyCreatedDBObject(ln, true);

                        msg = $"pt => {pt.X}, {pt.Y}, {pt.Z}\n";

                        #region get intersect point from point to polyline
                        Point3d ptNearest = Point3d.Origin;
                        for (int j = 0; j < poly3ds0.Count(); j++)
                        {
                            Polyline3d p3d0 = poly3ds0[j];
                            Polyline3d p3d  = poly3ds[j];

                            Point3d ptTemp = new Point3d();
                            #region get the alignment object and find the nearest point to the nominated point

                            Point3dCollection pts3D = new Point3dCollection();
                            p3d0.IntersectWith(ln, Intersect.OnBothOperands, pts3D, IntPtr.Zero, IntPtr.Zero);

                            try
                            {
                                if (pts3D.Count > 0)
                                {
                                    double para = p3d0.GetParameterAtPoint(pts3D[0]);
                                    //ed.WriteMessage($"{pts3D[0]}, {para}\n");
                                    ptTemp = p3d.GetPointAtParameter(para);
                                }
                            }
                            catch { }

                            #region get the point with lower Z
                            if (ptNearest == Point3d.Origin)
                            {
                                ptNearest = ptTemp;
                            }
                            else
                            {
                                if (ptNearest.Z > ptTemp.Z)
                                {
                                    ptNearest = ptTemp;
                                }
                            }
                            #endregion
                        }
                        #endregion
                        #endregion

                        msg += $"ptNearest: {ptNearest.X}, {ptNearest.Y}, {ptNearest.Z}\n";

                        try
                        {
                            double diff = ptNearest.Z - pt.Z;
                            if (Math.Abs(diff) <= checkDistance)
                            {
                                Point3d newPt = new Point3d(pt.X, pt.Y, ptNearest.Z + checkDistance);
                                output.Add(newPt);
                                data.Add($"{newPt.X},{newPt.Y},{newPt.Z}, less, {diff}, {ptNearest.Z}");
                                msg += $", Z diff: {diff} => less than {checkDistance} => {newPt.X}, {newPt.Y}, {newPt.Z}\n\n";
                            }
                            else
                            {
                                Point3d newPt = pt;
                                output.Add(newPt);
                                data.Add($"{newPt.X},{newPt.Y},{newPt.Z}, more, {diff}, {ptNearest.Z}");
                                msg += $", Z diff: {diff} => more than {checkDistance} => {newPt.X}, {newPt.Y}, {newPt.Z}\n\n";
                            }
                        }
                        catch { }

                        System.IO.File.AppendAllText(logPath, msg);
                    }
                    tr.Commit();
                }
            }
            Excel.createCSV(data, outputPath);
            ed.WriteMessage("\ncsv file has been created under path " + outputPath);
        }
Ejemplo n.º 22
0
        static bool ExecuteCommands()
        {
            if (TestArg("-help") || TestArg("/?"))
            {
                string   Message = "Available command line options\r\n";
                string[] Help    =
                {
                    "Available Console Commands:",
                    "========================================",
                    "",
                    "-state\t\t\tShow instalation state",
                    "-uninstall\t\tUninstall Private Win10",
                    "-shutdown\t\tClose Private Win10 instances",
                    "-restart\t\tRestart Win10 and reload settings",
                    "",
                    "-svc_install\t\tInstall priv10 service (invokes -log_install)",
                    "-svc_remove\t\tRemove priv10 service",
                    "",
                    "-log_install\t\tInstall PrivateWin10 Custom Event Log",
                    "-log_remove\t\tRemove PrivateWin10 Custom Event Log",
                    "",
                    "-restore_dns\t\tRestore original DNS Configuration",
                    "",
                    "-console\t\tShow console with debug output",
                    "-help\t\t\tShow this help message"
                };
                if (!HasConsole)
                {
                    MessageBox.Show(Message + string.Join("\r\n", Help));
                }
                else
                {
                    Console.WriteLine(Message);
                    for (int j = 0; j < Help.Length; j++)
                    {
                        Console.WriteLine(" " + Help[j]);
                    }
                }
                return(true);
            }


            bool bDone = false;

            if (TestArg("-uninstall"))
            {
                AppLog.Debug("Uninstalling Private Win10");
                bDone = true;
            }

            if (TestArg("-svc_remove") || (Priv10Service.IsInstalled() && TestArg("-uninstall")))
            {
                AppLog.Debug("Removing Service...");
                Priv10Service.Uninstall();
                bDone = true;
            }

            if (TestArg("-shutdown") || TestArg("-restart") || TestArg("-restore") || TestArg("-uninstall"))
            {
                AppLog.Debug("Closing instances...");
                if (Priv10Service.IsInstalled())
                {
                    Priv10Service.Terminate();
                }

                Thread.Sleep(500);

                foreach (var proc in Process.GetProcessesByName(App.Key))
                {
                    if (proc.Id == ProcFunc.CurID)
                    {
                        continue;
                    }
                    proc.Kill();
                }

                bDone = true;
            }

            if (TestArg("-restore"))
            {
                string zipPath = GetArg("-restore");

                try
                {
                    if (zipPath == null || !File.Exists(zipPath))
                    {
                        throw new Exception("Data backup zip not specifyed or invalid path");
                    }

                    Console.WriteLine("Restoring settings from {0}", zipPath);

                    string extractPath = App.dataPath;

                    // Normalizes the path.
                    extractPath = Path.GetFullPath(extractPath);

                    // Ensures that the last character on the extraction path
                    // is the directory separator char.
                    // Without this, a malicious zip file could try to traverse outside of the expected
                    // extraction path.
                    if (!extractPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
                    {
                        extractPath += Path.DirectorySeparatorChar;
                    }

                    // create data directory
                    if (!Directory.Exists(dataPath))
                    {
                        Directory.CreateDirectory(dataPath);
                    }

                    // ensure its writable by non administrators
                    FileOps.SetAnyDirSec(dataPath);

                    // Extract the backuped files
                    using (ZipArchive archive = ZipFile.OpenRead(zipPath))
                    {
                        foreach (ZipArchiveEntry entry in archive.Entries)
                        {
                            // Gets the full path to ensure that relative segments are removed.
                            string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName));

                            // Ordinal match is safest, case-sensitive volumes can be mounted within volumes that
                            // are case-insensitive.
                            if (!destinationPath.StartsWith(extractPath, StringComparison.Ordinal))
                            {
                                continue;
                            }

                            Console.WriteLine("Restored file {0}", entry.FullName);
                            if (File.Exists(destinationPath))
                            {
                                FileOps.DeleteFile(destinationPath);
                            }
                            else if (!Directory.Exists(Path.GetDirectoryName(destinationPath)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
                            }

                            entry.ExtractToFile(destinationPath);
                        }
                    }
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.Message);
                    MessageBox.Show(Translate.fmt("msg_restore_error", err.Message), App.Title, MessageBoxButton.OK, MessageBoxImage.Stop);
                }

                bDone = true;
            }

            if (TestArg("-restart") || TestArg("-restore"))
            {
                Thread.Sleep(500);

                AppLog.Debug("Starting instances...");
                if (Priv10Service.IsInstalled())
                {
                    Priv10Service.Startup();
                }

                Thread.Sleep(500);

                ProcessStartInfo startInfo = new ProcessStartInfo(App.exePath);
                startInfo.UseShellExecute = true;
                startInfo.Verb            = "runas";
                Process.Start(startInfo);

                bDone = true;
            }

            if (TestArg("-log_remove") || (Log.UsingEventLog() && TestArg("-uninstall")))
            {
                AppLog.Debug("Removing Event Log...");
                Log.RemoveEventLog(Key);
                bDone = true;
            }

            if (TestArg("-svc_install"))
            {
                AppLog.Debug("Installing Service...");
                Priv10Service.Install(TestArg("-svc_start"));
                bDone = true;
            }

            if (TestArg("-log_install") || TestArg("-svc_install")) // service needs the event log
            {
                AppLog.Debug("Setting up Event Log...");
                Log.SetupEventLog(Key);
                bDone = true;
            }

            if (TestArg("-restore_dns") || (DnsConfigurator.IsAnyLocalDNS() && TestArg("-uninstall")))
            {
                AppLog.Debug("Restoring DNS Config...");
                DnsConfigurator.RestoreDNS();
                bDone = true;
            }

            if (TestArg("-uninstall") && AdminFunc.IsSkipUac(App.Key))
            {
                AppLog.Debug("Removing UAC Bypass...");
                AdminFunc.SkipUacEnable(App.Key, false);
                bDone = true;
            }

            if (TestArg("-uninstall") && App.IsAutoStart())
            {
                AppLog.Debug("Removing Autostart...");
                App.AutoStart(false);
                bDone = true;
            }

            if (bDone)
            {
                AppLog.Debug("done");
            }


            if (TestArg("-state"))
            {
                Console.WriteLine();
                Console.WriteLine("Instalation State:");
                Console.WriteLine("========================="); // 25
                Console.Write("Auto Start:\t");
                Console.WriteLine(App.IsAutoStart());
                Console.Write("UAC Bypass:\t");
                Console.WriteLine(AdminFunc.IsSkipUac(App.Key));
                Console.Write("Service:\t");
                Console.WriteLine(Priv10Service.IsInstalled());
                Console.Write("Event Log:\t");
                Console.WriteLine(Log.UsingEventLog());
                Console.Write("Local DNS:\t");
                Console.WriteLine(DnsConfigurator.IsAnyLocalDNS());
                Console.WriteLine();
                bDone = true;
            }

            if (TestArg("-wait"))
            {
                Console.WriteLine();
                for (int i = 10; i >= 0; i--)
                {
                    Console.Write("\r{0}%   ", i);
                    Thread.Sleep(1000);
                }
            }

            return(bDone);
        }
Ejemplo n.º 23
0
 private void btnTransfer_Click(object sender, EventArgs e)
 {
     ///TODO: Change to use properties
     FileOps.TransferFiles(txtWorkingDirectory.Text);
 }
Ejemplo n.º 24
0
    public void RunAsync()
    {
        new Script(); //To make sure all required resources are loaded.

        Task.Run(() =>
        {
            var lib_files = new HashSet <string>();

            OnLog.Invoke("Exporting library files...");
            try
            {
                {
                    var runnable_file_name = FileOps.CreateTmpFile(CodeExtension);
                    File.WriteAllText(runnable_file_name, RunnableCode);
                    lib_files.Add(runnable_file_name);
                }

                if (!string.IsNullOrEmpty(StandardLibraryCode))
                {
                    var library_file_name = FileOps.CreateTmpFile(CodeExtension);
                    File.WriteAllText(library_file_name, StandardLibraryCode);
                    lib_files.Add(library_file_name);
                }


                if (LibraryFiles != null)
                {
                    var lib_dir = FileOps.CreateTmpDir();
                    foreach (var other_lib_file in LibraryFiles)
                    {
                        var lib_file = Path.Combine(lib_dir, other_lib_file.Key);
                        lib_file     = Path.ChangeExtension(lib_file, CodeExtension);
                        File.WriteAllText(lib_file, other_lib_file.Value);
                        lib_files.Add(lib_file);
                    }
                }
            } catch (Exception e)
            {
                OnLog.Invoke(string.Format("Failure writing down all library files:\n{0}", e));
                return;
            }

            var code_generator = new ArbitraryCodeExecutor(CompilerCommand, RunCommand, ArgumentsGeneratorCode, true);

            OnLog.Invoke("Generating commands...");
            CompileTask compiler;
            try
            {
                compiler = code_generator.Compile(new CompileInstructions
                {
                    files = lib_files
                });
            } catch (SyntaxErrorException e)
            {
                OnLog.Invoke(e.DecoratedMessage);
                return;
            }
            catch (Exception e)
            {
                OnLog.Invoke(e.Message);
                return;
            }

            if (compiler.RequiresCompile)
            {
                try
                {
                    OnLog.Invoke("Compiling...");
                    OnLog.Invoke(compiler.Command);
                    var p = compiler.Process;
                    p.OutputDataReceived += on_process_output;
                    p.ErrorDataReceived  += on_process_output;
                    compiler.Start();
                    p.BeginOutputReadLine();
                    p.BeginErrorReadLine();
                    p.WaitForExit();

                    if (compiler.IsCompilerError())
                    {
                        OnLog.Invoke("Failed to compile.");
                        return;
                    }
                } catch (Exception e)
                {
                    OnLog.Invoke(e.ToString());
                    return;
                }
            }

            OnLog.Invoke("Running...");
            try
            {
                var executable        = compiler.Run();
                var p                 = executable.Process;
                p.OutputDataReceived += on_process_output;
                p.ErrorDataReceived  += on_process_output;
                executable.Start();
                p.BeginOutputReadLine();
                p.BeginErrorReadLine();
                p.WaitForExit();

                if (executable.IsRunError())
                {
                    OnLog.Invoke("Failed to run code.");
                }
                else
                {
                    OnLog.Invoke("Successfully ran code.");
                }
            } catch (Exception e)
            {
                OnLog.Invoke(e.ToString());
                return;
            }
        });
    }
Ejemplo n.º 25
0
 static void Save()
 {
     FileOps.SaveBusiness("e.bin", employees);
     Console.WriteLine("Business saved; press any ket to continue.");
     Console.ReadLine();
 }
Ejemplo n.º 26
0
 static void Load()
 {
     employees = FileOps.LoadBusiness("e.bin");
     Console.WriteLine("Business loaded; press any key to continue");
     Console.ReadLine();
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Default constructor for the RepositoryManager class
 /// </summary>
 public RepositoryManager()
 {
     FileOps.CreateDirectory(RepositoryDirectroyPath);
     LoadRepository();
 }
Ejemplo n.º 28
0
        public void DoUpdate(ProgramSet progSet)
        {
            this.progSet = progSet;

            SuspendChange++;

            ImgFunc.GetIconAsync(progSet.GetIcon(), icon.Width, (ImageSource src) => {
                if (Application.Current != null)
                {
                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        icon.Source = src;
                    }));
                }
                return(0);
            });

            //name.Content = process.Name;
            name.Text = progSet.config.Name;

            int    blockedConnections = 0;
            int    allowedConnections = 0;
            int    socketCount        = 0;
            UInt64 uploadRate         = 0;
            UInt64 downloadRate       = 0;

            foreach (Program prog in progSet.Programs.Values)
            {
                blockedConnections += prog.BlockedCount;
                allowedConnections += prog.AllowedCount;

                socketCount += prog.SocketCount;

                uploadRate   += prog.UploadRate;
                downloadRate += prog.DownloadRate;
            }
            info.Content = Translate.fmt("lbl_prog_info", blockedConnections, allowedConnections, socketCount,
                                         FileOps.FormatSize((decimal)uploadRate), FileOps.FormatSize((decimal)downloadRate));

            WpfFunc.CmbSelect(category, progSet.config.Category == null ? "" : progSet.config.Category);

            WpfFunc.CmbSelect(cmbAccess, progSet.config.GetAccess().ToString());
            if (progSet.config.NetAccess != ProgramSet.Config.AccessLevels.Unconfigured && progSet.config.NetAccess != progSet.config.CurAccess)
            {
                cmbAccess.Background /*grid.Background*/ = FindResource("Stripes") as DrawingBrush;
            }
            else
            {
                cmbAccess.Background = GetAccessColor(progSet.config.GetAccess());
            }

            chkNotify.IsChecked = progSet.config.GetNotify();

            progGrid.Items.Clear();

            foreach (Program prog in progSet.Programs.Values)
            {
                progGrid.Items.Insert(0, new ProgEntry(prog));
            }

            btnSplit.IsEnabled = progSet.Programs.Count > 1;
            SuspendChange--;
        }
        public static void GenerateCode()
        {
            if (!AutoGenerate || IsGenerating)
            {
                return;
            }
            //Re-entrant code generation no good
            IsGenerating           = true;
            ComponentListFormatted = "";
            ComponentEnums         = "";

            var allcomp = GetAllComponentList();

            foreach (var comp in allcomp)
            {
                string entName = FileOps.GetStringAfterLastSlash(comp);
                string comma   = ",";
                if (comp == allcomp.Last())                 //last element
                {
                    comma = "";
                }

                string newLine = "\n\t\t\t" + "{ComponentTypes." + entName + ", typeof(" + entName + ")}" + comma;
                ComponentListFormatted += newLine;
                ComponentEnums         += "\n\t\t" + entName + comma;
                Console.WriteLine(newLine);
            }

            ComponentListFormatted += @"
		};

        public static ComponentEcs Create(ComponentTypes type)
        {
            if (!ComponentLookup.ContainsKey(type)) return null;
	        return ComponentCache.Instance.Get(type);
        }

	    public static ComponentEcs Instantiate(ComponentTypes type)
	    {
		    return (ComponentEcs) Activator.CreateInstance(ComponentLookup[type]);
	    }
    }

    public enum ComponentTypes
    {";

            ComponentListFormatted += ComponentEnums;

            string fullString = FileOps.ReplaceLineEndings(HEADER_FORMAT + ComponentListFormatted + FOOTER_FORMAT);

            //Debug.Log(fullString);

            using (var file = File.Open(CompFactoryFilePath, FileMode.Truncate))
            {
                using (var writer = new StreamWriter(file))
                {
                    writer.Write(fullString);
                }
            }
            int    idx         = CompFactoryFilePath.IndexOf("Assets");
            string newFilePath = CompFactoryFilePath.Substring(idx, CompFactoryFilePath.Length - idx);

            AssetDatabase.ImportAsset(newFilePath);
            IsGenerating = false;
        }
Ejemplo n.º 30
0
        ///////////////////////////////////////////////////////////////////////

        public bool VerifyFile(
            Configuration configuration,
            string fileName,
            bool strongName
            )
        {
            try
            {
                if (!File.Exists(fileName))
                {
                    Trace(configuration, String.Format(
                              "File \"{0}\" does not exist.", fileName),
                          TraceCategory);

                    return(false);
                }

                ///////////////////////////////////////////////////////////////

                string error = null;

                if (strongName)
                {
#if NATIVE && WINDOWS
                    if (VersionOps.IsWindowsOperatingSystem() &&
                        !StrongNameEx.IsStrongNameSigned(
                            configuration, fileName, true, ref error))
                    {
                        Trace(configuration, String.Format(
                                  "Assembly in file \"{0}\" is not signed.",
                                  fileName), TraceCategory);

                        Trace(configuration, String.Format(
                                  "Assembly signature error: {0}", error),
                              TraceCategory);

                        return(false);
                    }
#endif

                    ///////////////////////////////////////////////////////////

                    AssemblyName assemblyName =
                        AssemblyName.GetAssemblyName(fileName);

                    if (assemblyName == null)
                    {
                        Trace(configuration, String.Format(
                                  "Assembly in file \"{0}\" has no name.", fileName),
                              TraceCategory);

                        return(false);
                    }

                    byte[] filePublicKeyToken = assemblyName.GetPublicKeyToken();

                    if (!GenericOps <byte> .Equals(
                            filePublicKeyToken, publicKeyToken))
                    {
                        Trace(configuration, String.Format(
                                  "Assembly in file \"{0}\" has incorrect " +
                                  "public key token \"{1}\".", fileName,
                                  FormatOps.ToHexString(filePublicKeyToken)),
                              TraceCategory);

                        return(false);
                    }
                }

                ///////////////////////////////////////////////////////////////

                byte[] hash = null;

                if (FileOps.Hash(
                        configuration, "md5", fileName, ref hash, ref error))
                {
                    if (!GenericOps <byte> .Equals(hash, md5Hash))
                    {
                        Trace(configuration, String.Format(
                                  "File \"{0}\" MD5 hash mismatch, got: {1}.",
                                  fileName, FormatOps.ToHexString(hash)),
                              TraceCategory);

                        return(false);
                    }
                }
                else
                {
                    Trace(configuration, error, TraceCategory);

                    return(false);
                }

                ///////////////////////////////////////////////////////////////

                if (FileOps.Hash(
                        configuration, "sha1", fileName, ref hash, ref error))
                {
                    if (!GenericOps <byte> .Equals(hash, sha1Hash))
                    {
                        Trace(configuration, String.Format(
                                  "File \"{0}\" SHA1 hash mismatch, got: {1}.",
                                  fileName, FormatOps.ToHexString(hash)),
                              TraceCategory);

                        return(false);
                    }
                }
                else
                {
                    Trace(configuration, error, TraceCategory);

                    return(false);
                }

                ///////////////////////////////////////////////////////////////

                if (FileOps.Hash(
                        configuration, "sha512", fileName, ref hash, ref error))
                {
                    if (!GenericOps <byte> .Equals(hash, sha512Hash))
                    {
                        Trace(configuration, String.Format(
                                  "File \"{0}\" SHA512 hash mismatch, got: {1}.",
                                  fileName, FormatOps.ToHexString(hash)),
                              TraceCategory);

                        return(false);
                    }
                }
                else
                {
                    Trace(configuration, error, TraceCategory);

                    return(false);
                }

                return(true);
            }
            catch (Exception e)
            {
                Trace(configuration, e, TraceCategory);
            }

            return(false);
        }
Ejemplo n.º 31
0
        public static void Main(string[] args)
        {
            App.args = args;

            HasConsole = WinConsole.Initialize(TestArg("-console"));

            if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            if (TestArg("-dbg_log"))
            {
                AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler;
            }

            StartModes startMode = StartModes.Normal; // Normal GUI Mode

            if (TestArg("-svc"))
            {
                startMode = StartModes.Service;
            }
            else if (TestArg("-engine"))
            {
                startMode = StartModes.Engine;
            }

            Log = new AppLog(Key);
            AppLog.ExceptionLogID    = (long)EventIDs.Exception;
            AppLog.ExceptionCategory = (short)EventFlags.DebugEvents;

            if (startMode == StartModes.Normal)
            {
                Log.EnableLogging();
                Log.LoadLog();
            }
            // When running as worker we need the windows event log
            else if (!Log.UsingEventLog())
            {
                Log.SetupEventLog(Key);
            }

            // load current version
            exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath);

            Version = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            if (fvi.FileBuildPart != 0)
            {
                Version += "." + fvi.FileBuildPart;
            }
            if (fvi.FilePrivatePart != 0)
            {
                Version += (char)('a' + (fvi.FilePrivatePart - 1));
            }
            appPath = Path.GetDirectoryName(exePath);

            Translate.Load();

            dataPath = appPath + @"\Data";
            if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run
            {
                isPortable = true;

                AppLog.Debug("Portable Mode");
            }
            else
            {
                string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                if (progData == null)
                {
                    progData = @"C:\ProgramData";
                }

                dataPath = progData + "\\" + Key;
            }

            AppLog.Debug("Config Directory: {0}", dataPath);

            // execute commandline commands
            if (ExecuteCommands())
            {
                return;
            }

            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            if (AdminFunc.IsAdministrator())
            {
                FileOps.SetAnyDirSec(dataPath);
            }

            App.LogInfo("PrivateWin10 Process Started, Mode {0}.", startMode.ToString());

            Session = Process.GetCurrentProcess().SessionId;

            // setup custom assembly resolution for x86/x64 synamic compatybility
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler;

            // is the process starting as a service/worker?
            if (startMode != StartModes.Normal)
            {
                engine = new Priv10Engine();
                if (startMode == StartModes.Service)
                {
                    using (Priv10Service svc = new Priv10Service())
                        ServiceBase.Run(svc);
                }
                else
                {
                    engine.Run();
                }
                return;
            }

            Thread.CurrentThread.Name = "Gui";

            client = new Priv10Client();

            // Encure wie have the required privilegs
            //if (!AdminFunc.IsDebugging())
            {
                AppLog.Debug("Trying to connect to Engine...");
                int conRes = client.Connect(1000);
                if (conRes == 0)
                {
                    if (!AdminFunc.IsAdministrator())
                    {
                        AppLog.Debug("Trying to obtain Administrative proivilegs...");
                        if (AdminFunc.SkipUacRun(App.Key, App.args))
                        {
                            return;
                        }

                        AppLog.Debug("Trying to start with 'runas'...");
                        // Restart program and run as admin
                        string           arguments = "\"" + string.Join("\" \"", args) + "\"";
                        ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments);
                        startInfo.UseShellExecute = true;
                        startInfo.Verb            = "runas";
                        try
                        {
                            Process.Start(startInfo);
                            return; // we restarted as admin
                        }
                        catch
                        {
                            //MessageBox.Show(Translate.fmt("msg_admin_rights", mName), mName);
                            //return; // no point in cintinuing without admin rights or an already running engine
                        }
                    }
                    else if (Priv10Service.IsInstalled())
                    {
                        AppLog.Debug("Trying to start service...");
                        if (Priv10Service.Startup())
                        {
                            AppLog.Debug("Trying to connect to service...");

                            if (client.Connect() != 0)
                            {
                                AppLog.Debug("Connected to service...");
                            }
                            else
                            {
                                AppLog.Debug("Failed to connect to service...");
                            }
                        }
                        else
                        {
                            AppLog.Debug("Failed to start service...");
                        }
                    }
                }
                else if (conRes == -1)
                {
                    MessageBox.Show(Translate.fmt("msg_dupliate_session", Title), Title);
                    return; // no point in cintinuing without admin rights or an already running engine
                }
            }

            //

            tweaks = new TweakManager();

            // if we couldn't connect to the engine start it and connect
            if (!client.IsConnected() && AdminFunc.IsAdministrator())
            {
                AppLog.Debug("Starting Engine Thread...");

                engine = new Priv10Engine();

                engine.Start();

                AppLog.Debug("... engine started.");

                client.Connect();
            }

            var app = new App();

            app.InitializeComponent();

            InitLicense();

            MainWnd = new MainWindow();

            TrayIcon         = new TrayIcon();
            TrayIcon.Action += TrayAction;
            TrayIcon.Visible = (GetConfigInt("Startup", "Tray", 0) != 0) || App.TestArg("-autorun");

            if (!App.TestArg("-autorun") || !TrayIcon.Visible)
            {
                MainWnd.Show();
            }

            app.Run();

            TrayIcon.DestroyNotifyicon();

            client.Close();

            tweaks.Store();

            if (engine != null)
            {
                engine.Stop();
            }
        }