GetTempPath() public static méthode

public static GetTempPath ( ) : string
Résultat string
Exemple #1
0
        /// <summary>
        /// Returns a temp <see cref="T:System.Uri"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Uri" /> file.
        /// </returns>
        public static Uri GetUniqueTempRandomFile()
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core.IO, Namespace: iTin.Core.IO, Class: File");
            Logger.Instance.Debug($" Returns a temp {typeof(Uri)}");
            Logger.Instance.Debug($" > Signature: ({typeof(Uri)}) GetUniqueTempRandomFile()");

            string tempPath       = NativePath.GetTempPath();
            string randomFileName = NativePath.GetRandomFileName();
            string path           = NativePath.Combine(tempPath, randomFileName);

            Logger.Instance.Debug($"  > Output: {path}");

            return(new Uri(path));
        }
        /// <summary>
        /// Generates the winners certificates and stores them to a file
        ///
        /// The file path is returned
        /// </summary>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="rank"></param>
        /// <param name="tournamentname"></param>
        /// <param name="place"></param>
        /// <param name="date"></param>
        /// <returns>Path to generated certificate</returns>
        public static XpsDocument Generate(string name, int rank, string tournamentname, string place, string date)
        {
            Word.Application wApp = new Word.Application();
            wApp.Visible = false;

            Word.Documents wDocs        = wApp.Documents;
            object         missing      = System.Reflection.Missing.Value;
            string         templatePath = AppDomain.CurrentDomain.BaseDirectory + @"WinnerCertificatesTemplate\Urkunde_v2_final.docm";

            Word.Document wDoc = wDocs.Open(templatePath,
                                            missing,
                                            ReadOnly: false,
                                            Visible: false,
                                            Revert: false);
            wApp.WindowState = WdWindowState.wdWindowStateMinimize;
            wDoc.Activate();

            Word.Bookmarks wBookmarks = wDoc.Bookmarks;
            Word.Bookmark  wBookmark  = wBookmarks["TournamentName"];
            Word.Range     wRange     = wBookmark.Range;
            wRange.Text = tournamentname;

            Word.Bookmark wBookmark2 = wBookmarks["Name"];
            Word.Range    wRange2    = wBookmark2.Range;
            wRange2.Text = name;

            Word.Bookmark wBookmark3 = wBookmarks["Rank"];
            Word.Range    wRange3    = wBookmark3.Range;
            wRange3.Text = rank.ToString();

            Word.Bookmark wBookmark4 = wBookmarks["Place"];
            Word.Range    wRange4    = wBookmark4.Range;
            wRange4.Text = place;

            Word.Bookmark wBookmark5 = wBookmarks["Date"];
            Word.Range    wRange5    = wBookmark5.Range;
            wRange5.Text = date;

            string convertedXpsDoc = string.Concat(Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps");

            wDoc.SaveAs(convertedXpsDoc, WdSaveFormat.wdFormatXPS);
            XpsDocument xpsDocument = new XpsDocument(convertedXpsDoc, FileAccess.Read);

            wDoc.Close(SaveChanges: false);
            wApp.Quit();

            return(xpsDocument);
        }
Exemple #3
0
        private void TempPanel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (TempPanel.Visibility != Visibility.Visible)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(Settings.Default.TemporaryFolder))
            {
                //string.Format(@"ScreenToGif\Recording\{0}\", DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
                Settings.Default.TemporaryFolder = Path.GetTempPath();
            }

            _tempDel = CheckTemp;
            _tempDel.BeginInvoke(e, CheckTempCallBack, null);
        }
        public static IFeatureWorkspace CreateTestAccessWorkspace(
            [NotNull] string mdbName)
        {
            string dir = Path.GetTempPath();

            string mdb = Path.Combine(dir, mdbName) + ".mdb";

            if (File.Exists(mdb))
            {
                File.Delete(mdb);
            }

            IFeatureWorkspace testWs = WorkspaceUtils.CreatePgdbWorkspace(dir, mdbName);

            return(testWs);
        }
        public static IFeatureWorkspace CreateTestFgdbWorkspace(
            [NotNull] string gdbName)
        {
            string dir = Path.GetTempPath();

            string gdb = Path.Combine(dir, gdbName) + ".gdb";

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

            IWorkspaceName wsName = WorkspaceUtils.CreateFileGdbWorkspace(dir, gdbName);

            return((IFeatureWorkspace)((IName)wsName).Open());
        }
        public void RequiresCheckInAndOutIsTrailingBackslashInsensitive()
        {
            using (var configurationReaderMockInjectionScope = new SsoConfigurationReaderMockInjectionScope())
            {
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckInDirectory)))
                // makes sure there is one trailing '\'
                .Returns(Path.GetTempPath().ToUpper().TrimEnd('\\') + '\\');
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckOutDirectory)))
                // makes sure there is no trailing '\'
                .Returns(Path.GetTempPath().ToLower().TrimEnd('\\'));

                ClaimStore.RequiresCheckInAndOut.Should().BeFalse();
            }
        }
Exemple #7
0
        public void RequiresCheckInAndOutIsTrailingBackslashInsensitive()
        {
            using (var configurationReaderMockInjectionScope = new SsoConfigurationReaderMockInjectionScope())
            {
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_IN_DIRECTORY_PROPERTY_NAME))
                // makes sure there is one trailing '\'
                .Returns(Path.GetTempPath().ToUpper().TrimEnd('\\') + '\\');
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_OUT_DIRECTORY_PROPERTY_NAME))
                // makes sure there is no trailing '\'
                .Returns(Path.GetTempPath().ToLower().TrimEnd('\\'));

                ClaimStore.RequiresCheckInAndOut.Should().BeFalse();
            }
        }
        public static IFeatureWorkspace CreateTestShapefileWorkspace(
            [NotNull] string gdbName)
        {
            string dir = Path.GetTempPath();

            string folder = Path.Combine(dir, gdbName);

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

            IWorkspaceName wsName = WorkspaceUtils.CreateShapefileWorkspace(dir, gdbName);

            return((IFeatureWorkspace)((IName)wsName).Open());
        }
        private void preparePreRunXml()
        {
            try
            {
                var filePreRun = Path.Combine(Path.GetTempPath(), PNStrings.PRE_RUN_FILE);
                var xdoc       = File.Exists(filePreRun) ? XDocument.Load(filePreRun) : new XDocument();
                var xroot      = xdoc.Root ?? new XElement(PNStrings.ELM_PRE_RUN);
                var addCopy    = false;
                var xcopies    = xroot.Element(PNStrings.ELM_COPY_THEMES);
                if (xcopies == null)
                {
                    addCopy = true;
                    xcopies = new XElement(PNStrings.ELM_COPY_THEMES);
                }
                else
                {
                    xcopies.RemoveAll();
                }
                foreach (var tuple in _FilesList)
                {
                    var fromPath =
                        Path.Combine(
                            Path.Combine(Path.Combine(Path.GetTempPath(), PNStrings.TEMP_THEMES_DIR), "themes"),
                            tuple.Item4);
                    var name = string.IsNullOrEmpty(fromPath) ? "" : Path.GetFileName(fromPath);

                    var xc = new XElement(PNStrings.ELM_COPY);
                    xc.Add(new XAttribute(PNStrings.ATT_NAME, tuple.Item4));
                    xc.Add(new XAttribute(PNStrings.ATT_FROM, fromPath));
                    xc.Add(new XAttribute(PNStrings.ATT_TO, tuple.Item3));
                    xcopies.Add(xc);
                }
                if (addCopy)
                {
                    xroot.Add(xcopies);
                }
                if (xdoc.Root == null)
                {
                    xdoc.Add(xroot);
                }
                xdoc.Save(filePreRun);
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
Exemple #10
0
        public void Should_Push_New_Asset_With_Put_Under_5MB(string assetUri)
        {
            _server.Stub(x => x.Put(assetUri))
            .OK();

            var asset    = new ProGetAssetPusher(_log, _config);
            var tempFile = new FilePath($"{Path.GetTempPath()}{Path.GetRandomFileName()}");

            using (var fileStream = new FileStream(tempFile.FullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                fileStream.SetLength(4194304);
            }
            var result = Record.Exception(() => asset.Publish(tempFile, $"{Host}{assetUri}"));

            File.Delete(tempFile.FullPath);
            Assert.Null(result);
        }
Exemple #11
0
        public void Should_Throw_Exception_When_Asset_Push_Fails_As_Put(string assetUri)
        {
            _server.Stub(x => x.Put(assetUri))
            .WithStatus(HttpStatusCode.BadRequest);

            var asset    = new ProGetAssetPusher(_log, _config);
            var tempFile = new FilePath($"{Path.GetTempPath()}{Path.GetRandomFileName()}");

            using (var fileStream = new FileStream(tempFile.FullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                fileStream.SetLength(4194304);
            }
            var result = Record.Exception(() => asset.Publish(tempFile, $"{Host}{assetUri}"));

            File.Delete(tempFile.FullPath);
            Assert.IsCakeException(result, "Upload failed. This request would have overwritten an existing package.");
        }
        public void CaptureMessageBodyWillHaveMessageClaimedButSsoApplicationDoesNotExist()
        {
            // setup a mock's callback to ensure that, even if the BizTalk.Factory SSO store is deployed, the call will look for an SSO store that does not exist
            SsoSettingsReaderMock
            .Setup(ssr => ssr.ReadString(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_IN_DIRECTORY_PROPERTY_NAME))
            .Callback(() => _ssoSettingsReaderInstance.ReadString("NONEXISTENT_APPLICATION", BizTalkFactorySettings.CLAIM_STORE_CHECK_IN_DIRECTORY_PROPERTY_NAME))
            .Returns(Path.GetTempPath());

            var trackingStreamMock = new Mock <TrackingStream>(FakeTextStream.Create(1024 * 1024))
            {
                CallBase = true
            };

            Assert.That(
                () => ClaimStore.Instance.SetupMessageBodyCapture(trackingStreamMock.Object, ActivityTrackingModes.Claim, null),
                Throws.TypeOf <COMException>().With.Message.EqualTo("The application does not exist.\r\n"));
        }
Exemple #13
0
        public void TlsTrustOnFirstUse()
        {
            var knownHostsFileName = Path.GetTempPath() + Guid.NewGuid() + ".tmp";

            var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "neo4j"),
                                              Config.Builder.WithEncryptionLevel(EncryptionLevel.Encrypted).WithTrustStrategy(TrustStrategy.TrustAllCertificates)
                                              .ToConfig());

            using (var session = driver.Session())
            {
                var result = session.Run("RETURN 1 as n");
                result.Single()["n"].As <int>().Should().Be(1);
            }
            driver.Dispose();

            File.Delete(knownHostsFileName);
        }
Exemple #14
0
        public void ShouldGetFileInfo()
        {
            var path = IOPath.GetTempPath();

            path = IOPath.Combine(path, IOPath.GetRandomFileName());
            var file = IOFile.Create(path);

            file.Close();
            try
            {
                var fileInfo = new CFileInfo(path);
                BY_HANDLE_FILE_INFORMATION kernelFileInfo;
                using (file = IOFile.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    try
                    {
                        CFileInfo.GetFileInformationByHandle(file.SafeFileHandle, out kernelFileInfo);
                    }
                    finally
                    {
                        file.Close();
                    }
                }

                Assert.That(fileInfo.LinkCount, Is.EqualTo(kernelFileInfo.NumberOfLinks), "LinkCount");
                Assert.That(fileInfo.VolumeSerialNumber, Is.EqualTo(kernelFileInfo.VolumeSerialNumber), "VolumeSerialNumber");

                UInt64 fileIndex = kernelFileInfo.FileIndexHigh;
                fileIndex  = fileIndex << 32;
                fileIndex |= kernelFileInfo.FileIndexLow;

                Assert.That(fileInfo.FileIndex, Is.EqualTo(fileIndex), "FileIndex");

                fileIndex = fileInfo.FileIndex;
                var upperIndex = (uint)((fileIndex >> 32) & 0xffffffff);
                Assert.That(kernelFileInfo.FileIndexHigh, Is.EqualTo(upperIndex));

                var lowerIndex = (uint)(fileIndex & 0xffffffff);
                Assert.That(kernelFileInfo.FileIndexLow, Is.EqualTo(lowerIndex));
            }
            finally
            {
                IOFile.Delete(path);
            }
        }
        public override void _ExportEnd()
        {
            base._ExportEnd();

            string aotTempDir = Path.Combine(Path.GetTempPath(), $"godot-aot-{Process.GetCurrentProcess().Id}");

            if (Directory.Exists(aotTempDir))
                Directory.Delete(aotTempDir, recursive: true);

            // TODO: Just a workaround until the export plugins can be made to abort with errors
            if (!string.IsNullOrEmpty(maybeLastExportError)) // Check empty as well, because it's set to empty after hot-reloading
            {
                string lastExportError = maybeLastExportError;
                maybeLastExportError = null;

                GodotSharpEditor.Instance.ShowErrorDialog(lastExportError, "Failed to export C# project");
            }
        }
        public void Should_Push_New_Asset_With_Multipart_Post_Over_5MB(string assetUri)
        {
            using (var server = FluentMockServer.Start())
            {
                server.Given(Request.Create().WithPath(assetUri).UsingPost())
                .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK));

                var asset    = new ProGetAssetPusher(_log, _config);
                var tempFile = new FilePath($"{Path.GetTempPath()}{Path.GetRandomFileName()}");
                using (var fileStream = new FileStream(tempFile.FullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    fileStream.SetLength(6291456);
                }
                var result = Record.Exception(() => asset.Publish(tempFile, $"http://localhost:{server.Ports[0]}{assetUri}"));
                File.Delete(tempFile.FullPath);
                Assert.Null(result);
            }
        }
        public static ISymbol GetForbiddenSymbol(int sizeLayer, Color color)
        {
            var       size025   = sizeLayer;
            var       size075   = size025 * 3;
            var       size      = size025 * 4;
            var       size15    = size025 * 6;
            var       size175   = size025 * 7;
            var       size3     = size025 * 12;
            var       bitmap    = new Bitmap(size3, size3);
            const int sizeLine2 = 2;
            const int sizeLine3 = 3;
            const int sizeLine6 = 6;

            color = Color.FromArgb(255, color);

            using (Graphics ga = Graphics.FromImage(bitmap))
            {
                ga.Clear(Color.White);
                ga.DrawEllipse(new Pen(color, sizeLine2), size, size, size, size);
                ga.FillEllipse(new SolidBrush(color), size, size, size, size);
                ga.DrawEllipse(new Pen(Color.Red, sizeLine2), size15, size15, size075, size075);
                ga.FillEllipse(Brushes.Red, size15, size15, size075, size075);
                ga.DrawRectangle(new Pen(Color.WhiteSmoke, sizeLine2), size15 + sizeLine3, size175, size075 - sizeLine6, size025);
                ga.FillRectangle(Brushes.WhiteSmoke, size15 + sizeLine3, size175, size075 - sizeLine6, size025);
            }

            // ReSharper disable CSharpWarnings::CS0612
            // ReSharper disable CSharpWarnings::CS0618
            Bitmap bitmap8B  = bitmap.To8BppIndexed();
            string tempPath  = Path.GetTempPath();
            string writePath = Path.Combine(tempPath, string.Format("{0}forbidden.bmp", color.Name));

            bitmap8B.Save(writePath, ImageFormat.Bmp);
            IPictureMarkerSymbol symbol = new PictureMarkerSymbolClass();

            symbol.CreateMarkerSymbolFromFile(esriIPictureType.esriIPictureBitmap, writePath);
            symbol.Size = size075;
            symbol.BitmapTransparencyColor = Converter.ToRGBColor(Color.White);
            return(symbol as ISymbol);
            // ReSharper restore CSharpWarnings::CS0618
            // ReSharper restore CSharpWarnings::CS0612
        }
        private static FixedDocumentSequence CreateDocument()
        {
            string tempFileName = Path.Combine(Path.GetTempPath(), "ThemePreviewer.DocumentSample.Fixed.xps");

            if (File.Exists(tempFileName))
            {
                File.Delete(tempFileName);
            }

            var document = new XpsDocument(tempFileName, FileAccess.ReadWrite);

            try {
                return(CreateDocument(document));
            } finally {
                document.Close();
                // DocumentViewer tries to reload from the loaded uri if the
                // theme changes.
                //File.Delete(tempFileName);
            }
        }
        private void OpenFileWithDefaultApp(object sender)
        {
            // save text to a temp file and open with windows
            try
            {
                TextEditor editor  = (TextEditor)sender;
                string     docPath = Path.Combine(Path.GetTempPath(), editor.Tag + ".sql");

                // Write the string array to a new file named "WriteLines.txt".
                using (StreamWriter outputFile = new StreamWriter(docPath))
                {
                    outputFile.WriteLine(editor.Text);
                }
                System.Diagnostics.Process.Start(docPath);
            }
            catch (Exception)
            {
                // swallow
            }
        }
Exemple #20
0
        private void CreateBackupClicked(object sender, RoutedEventArgs e)
        {
            var dialog = new SaveFileDialog();

            dialog.Filter           = "Backup files (*.bak)|*.bak";
            dialog.FileName         = String.Format("{0:yyMMdd} Photo.bak", DateTime.Now);
            dialog.InitialDirectory = "E:\\Develop\\Backup";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try {
                    var    streamReader = new StreamReader("Scripts\\CreateBackupScript.sql");
                    var    backupPath   = Path.Combine(Settings.BackupLocation, "Photo.bak");
                    string script       = String.Format(streamReader.ReadToEnd(), backupPath);
                    streamReader.Close();
                    var sqlFileTemp = Path.Combine(Path.GetTempPath(), "CreateBackupScript.sql");
                    if (File.Exists(sqlFileTemp))
                    {
                        File.Delete(sqlFileTemp);
                    }
                    var streamWriter = new StreamWriter(sqlFileTemp);
                    streamWriter.Write(script);
                    streamWriter.Close();
                    var process = Process.Start(Settings.SqlCmdLocation, String.Format("-E -S .\\SQLEXPRESS -d Photo -i \"{0}\"", sqlFileTemp));
                    process.WaitForExit();
                    if (File.Exists(backupPath))
                    {
                        if (File.Exists(dialog.FileName))
                        {
                            File.Delete(dialog.FileName);
                        }
                        File.Move(backupPath, dialog.FileName);
                    }
                    else
                    {
                        MessageBox.Show("File not created!");
                    }
                } catch (Exception exception) {
                    MessageBox.Show(exception.Message);
                }
            }
        }
        public void ClaimMessageBody()
        {
            using (var configurationReaderMockInjectionScope = new SsoConfigurationReaderMockInjectionScope())
            {
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckInDirectory)))
                .Returns(Path.GetTempPath());
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckOutDirectory)))
                .Returns(@"\\server\share");

                using (var contentStream = TextStreamDummy.Create(1024 * 1024))
                    using (var trackingStream = new TrackingStream(contentStream))
                    {
                        MessageMock.Object.BodyPart.Data = trackingStream;

                        ClaimStore.Instance.SetupMessageBodyCapture(trackingStream, ActivityTrackingModes.Claim, null);
                        ClaimStore.Instance.Claim(MessageMock.Object, ResourceTrackerMock.Object);

                        // message's actual body stream has been exhausted (i.e. saved to disk)
                        contentStream.Position.Should().Be(contentStream.Length);

                        // message's body stream is replaced by a token message
                        using (var reader = new StreamReader(MessageMock.Object.BodyPart.Data))
                        {
                            reader.ReadToEnd().Should().Be(ClaimFactory.CreateCheckIn(trackingStream.CaptureDescriptor.Data).OuterXml);
                        }

                        // MessageType of token message is promoted in message context
                        var schemaMetadata = SchemaMetadata.For <Claim.CheckIn>();
                        MessageMock.Verify(m => m.Promote(BtsProperties.MessageType, schemaMetadata.MessageType), Times.Once());
                        MessageMock.Verify(m => m.Promote(BtsProperties.SchemaStrongName, schemaMetadata.DocumentSpec.DocSpecStrongName), Times.Once());

                        // payload is claimed to disk and file extension is .chk
                        var captureDescriptor = trackingStream.CaptureDescriptor;
                        captureDescriptor.CaptureMode.Should().Be(MessageBodyCaptureMode.Claimed);
                        captureDescriptor.Data.Should().StartWith(DateTime.Today.ToString(@"yyyyMMdd\\"));
                        File.Exists(Path.Combine(Path.GetTempPath(), captureDescriptor.Data.Replace("\\", "") + ".chk")).Should().BeTrue();
                    }
            }
        }
        public static void InitializeFileTarget()
        {
            var config = NLog.LogManager.Configuration;

            LogFilePath = $"{Path.Combine(Path.GetTempPath(), $"AutoMuteUs-Portable")}.log";

            var logger = NLog.LogManager.GetLogger("Main");

            logger.Info($"{LocalizationProvider.GetLocalizedValue<string>("MainLogger_LogOutputStarted")} \"{LogFilePath}\"");

            var fileTarget = new FileTarget()
            {
                FileName = LogFilePath,
                DeleteOldFileOnStartup = true
            };

            config.AddTarget("LogFile", fileTarget);
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, "LogFile", "*");

            NLog.LogManager.Configuration = config;
        }
Exemple #23
0
            public void ShouldSaveNewServerIdToKnownHostsFileAndReturnTrue()
            {
                var fileName = Path.GetTempPath() + Guid.NewGuid() + ".tmp";

                try
                {
                    var trustStrategy = new TrustOnFirstUse(null, fileName);
                    var mockCert      = new Mock <X509Certificate>();
                    mockCert.Setup(x => x.GetCertHash()).Returns(ServerCertText.ToByteArray());
                    var valid = trustStrategy.ValidateServerCertificate(new Uri(ServerId), mockCert.Object, SslPolicyErrors.None);

                    valid.Should().BeTrue();
                    trustStrategy.KnownHost.Count.Should().Be(1);
                    trustStrategy.KnownHost.Keys.Single().Should().Be(ServerId);
                    trustStrategy.KnownHost.Values.Single().Should().Be(Fingerprint);
                }
                finally
                {
                    File.Delete(fileName);
                }
            }
Exemple #24
0
        private void frmExportData_Load(object sender, EventArgs e)
        {
            this.cboExportData.Items.Clear();
            this.cboExportData.Items.Add("所有要素");
            this.cboExportData.Items.Add("视图范围内的要素");
            if ((this.m_pFeatureLayer as IFeatureSelection).SelectionSet.Count > 0)
            {
                this.cboExportData.Items.Add("选中要素");
            }
            this.cboExportData.SelectedIndex = 0;
            string str  = Path.GetTempPath() + @"\Export_Data";
            int    num  = 0;
            string path = str + ".shp";

            while (File.Exists(path))
            {
                num++;
                path = str + "_" + num.ToString() + ".shp";
            }
            this.txtOutName.Text = path;
        }
Exemple #25
0
        public override void Execute()
        {
            RegistryKey runOnceKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", RegistryKeyPermissionCheck.ReadWriteSubTree);

            Int32 i = 1;

            foreach (ExtraFile file in Files)
            {
                String path = file.FileName;

                String vName = "AnolisRO" + (i++).ToStringInvariant();

                // copy the file to a temp directory
                String destFn = P.Combine(P.GetTempPath(), P.GetFileName(path));

                File.Copy(path, destFn, true);

                runOnceKey.SetValue(vName, destFn, RegistryValueKind.String);
            }

            runOnceKey.Close();
        }
        private async Task RunAsync()
        {
            var items   = listFiles.Items.OfType <string>().ToList();
            var outpath = textPath.Text;

            SetProgress(1, "正在创建临时文件夹");
            var tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            LogDebugInfo($"临时文件夹: {tempFolder}");
            Directory.CreateDirectory(tempFolder);


            var ffmpeg          = Path.Combine(AppContext.BaseDirectory, "lib", "ffmpeg.exe");
            var filelistBuilder = new StringBuilder();

            for (int i = 0; i < items.Count; i++)
            {
                SetProgress(1 + 59 * i / (double)items.Count, $"正在转换第{i}/{items.Count}个视频");

                var filename = Path.Combine(tempFolder, $"{i}.mp4");
                filelistBuilder.AppendLine($"file '{filename}'");

                var subprocess = Process.Start(ffmpeg, $"-i \"{items[i]}\" -af apad -c:v copy -c:a aac -b:a 256k -shortest \"{filename}\"");
                await subprocess.WaitForExitAsync();
            }

            var filelistPath = Path.Combine(tempFolder, "filelist");

            File.WriteAllText(filelistPath, filelistBuilder.ToString());

            var combineProcess = Process.Start(ffmpeg, $"-f concat -safe 0 -i \"{filelistPath}\" -c copy \"{outpath}\"");
            await combineProcess.WaitForExitAsync();

            SetProgress(99, "正在清理临时文件");
            Directory.Delete(tempFolder, recursive: true);

            SetProgress(100, "任务已完成");
        }
        public void ClaimMessageBody()
        {
            SsoSettingsReaderMock
            .Setup(ssr => ssr.ReadString(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_IN_DIRECTORY_PROPERTY_NAME))
            .Returns(Path.GetTempPath());
            SsoSettingsReaderMock
            .Setup(ssr => ssr.ReadString(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_OUT_DIRECTORY_PROPERTY_NAME))
            .Returns(@"\\network\share");

            using (var contentStream = FakeTextStream.Create(1024 * 1024))
                using (var trackingStream = new TrackingStream(contentStream))
                {
                    MessageMock.Object.BodyPart.Data = trackingStream;

                    ClaimStore.Instance.SetupMessageBodyCapture(trackingStream, ActivityTrackingModes.Claim, null);
                    ClaimStore.Instance.Claim(MessageMock.Object, ResourceTrackerMock.Object);

                    // message's actual body stream has been exhausted (i.e. saved to disk)
                    Assert.That(contentStream.Position, Is.EqualTo(contentStream.Length));

                    // message's body stream is replaced by a token message
                    using (var reader = new StreamReader(MessageMock.Object.BodyPart.Data))
                    {
                        Assert.That(reader.ReadToEnd(), Is.EqualTo(MessageFactory.CreateClaimCheckIn(trackingStream.CaptureDescriptor.Data).OuterXml));
                    }

                    // MessageType of token message is promoted in message context
                    var schemaMetadata = typeof(Claim.CheckIn).GetMetadata();
                    MessageMock.Verify(m => m.Promote(BtsProperties.MessageType, schemaMetadata.MessageType), Times.Once());
                    MessageMock.Verify(m => m.Promote(BtsProperties.SchemaStrongName, schemaMetadata.DocumentSpec.DocSpecStrongName), Times.Once());

                    // payload is claimed to disk and file extension is .chk
                    var captureDescriptor = trackingStream.CaptureDescriptor;
                    Assert.That(captureDescriptor.CaptureMode, Is.EqualTo(MessageBodyCaptureMode.Claimed));
                    Assert.That(captureDescriptor.Data, Does.StartWith(DateTime.Today.ToString(@"yyyyMMdd\\")));
                    Assert.That(File.Exists(Path.Combine(Path.GetTempPath(), captureDescriptor.Data.Replace("\\", "") + ".chk")), Is.True);
                }
        }
        public void RedeemClaimToken()
        {
            const string content = "dummy";
            const string url     = "cca95baa39ab4e25a3c54971ea170911";

            using (var file = File.CreateText(Path.Combine(Path.GetTempPath(), url)))
            {
                file.Write(content);
            }

            using (var configurationReaderMockInjectionScope = new SsoConfigurationReaderMockInjectionScope())
            {
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckInDirectory)))
                .Returns(Path.GetTempPath());
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckOutDirectory)))
                .Returns(Path.GetTempPath());

                using (var tokenStream = ClaimFactory.CreateCheck(url).AsStream())
                {
                    MessageMock.Object.BodyPart.Data = tokenStream;

                    ClaimStore.Instance.Redeem(MessageMock.Object, ResourceTrackerMock.Object);

                    MessageMock.Object.BodyPart.Data.Should().BeOfType <TrackingStream>();
                    var captureDescriptor = ((TrackingStream)MessageMock.Object.BodyPart.Data).CaptureDescriptor;
                    captureDescriptor.CaptureMode.Should().Be(MessageBodyCaptureMode.Claimed);
                    // previously captured payload is reused and not captured/claimed anew
                    captureDescriptor.Data.Should().Be(url);
                }

                using (var reader = new StreamReader(MessageMock.Object.BodyPart.Data))
                {
                    reader.ReadToEnd().Should().Be(content);
                }
            }
        }
Exemple #29
0
        /// <summary>
        /// Creates a new temporary directory.
        /// </summary>
        /// <param name="prefix">a prefix to give to the directory's name</param>
        /// <exception cref="IOException">if there is an error creating the directory</exception>
        public TempDir(string prefix)
        {
            try
            {
                do
                {
                    string filename = (String.IsNullOrEmpty(prefix)) ? "" : prefix + ".";
                    filename += IOPath.GetRandomFileName();
                    Info      = new DirectoryInfo(IOPath.Combine(IOPath.GetTempPath(), filename));
                }while (Info.Exists);

                Info.Create();
                Info.Refresh();
            }
            catch (UnauthorizedAccessException uae)
            {
                throw new IOException(uae.Message, uae);
            }
            catch (System.Security.SecurityException se)
            {
                throw new IOException(se.Message, se);
            }
        }
Exemple #30
0
            public void ShouldLoadFromKnownHostIfFileExists()
            {
                var fileName = Path.GetTempPath() + Guid.NewGuid() + ".tmp";

                try
                {
                    using (var fileWriter = File.CreateText(fileName))
                    {
                        fileWriter.WriteLine("#this line should be ignored!");
                        fileWriter.WriteLine("serverId fingerprint");
                    }
                    File.Exists(fileName).Should().BeTrue();

                    var trustStrategy = new TrustOnFirstUse(null, fileName);

                    trustStrategy.KnownHost.Count.Should().Be(1);
                    trustStrategy.KnownHost["serverId"].Should().Be("fingerprint");
                }
                finally
                {
                    File.Delete(fileName);
                }
            }