private void PopulateDatabaseNameItemsWorker(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = sender as BackgroundWorker;

            if (backgroundWorker == null)
            {
                return;
            }

            String[] databaseArray = null;

            try
            {
                if (!String.IsNullOrEmpty(this.serverName))
                {
                    using (ImpersonationHelper impersonationHelper = new ImpersonationHelper())
                    {
                        databaseArray = SetupDatabaseHelper.GetSqlDBNames(
                            !SetupDatabaseHelper.SqlServerIsOnLocalComputer(this.serverName),
                            this.serverName,
                            IsDefaultInstance(this.selectedInstance) ? String.Empty : this.selectedInstance,
                            this.port,
                            true);
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                e.Result = databaseArray;
            }
        }
Example #2
0
        /// <summary>
        /// Tries to impersonate the current process as the user which runs explorer.exe currently. The caller should always call <see cref="IDisposable.Dispose"/> on
        /// the returned instance to revert identity to self.
        /// </summary>
        private static ImpersonationHelper.ImpersonationContext ImpersonateUser(ImpersonationHelper.ImpersonationContext requestedIdentity)
        {
            NetworkNeighborhoodResourceProviderSettings settings = _settings.Settings;

            ImpersonationHelper.ImpersonationContext ctx = null;

            // Prefer to impersonate current interactive user.
            if (settings.ImpersonateInteractive)
            {
                if (requestedIdentity != null && !ImpersonationHelper.RequiresImpersonate(requestedIdentity.Identity))
                {
                    return(null);
                }

                ctx = ImpersonationHelper.ImpersonateByProcess("explorer");
            }
            if (ctx != null)
            {
                return(ctx);
            }

            // Second way based on network credentials.
            if (settings.UseCredentials)
            {
                ctx = ImpersonationHelper.ImpersonateUser(settings.NetworkUserName, settings.NetworkPassword);
            }

            return(ctx);
        }
Example #3
0
        private static byte[] ProbeResource(IResourceAccessor accessor, string arguments, int transcoderTimeout)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo()
            {
                FileName               = FFMpegBinary.FFMpegPath,
                Arguments              = arguments,
                UseShellExecute        = false,
                CreateNoWindow         = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding  = Encoding.UTF8
            };

#if !TRANSCODE_CONSOLE_TEST
            using (ServiceRegistration.Get <IImpersonationService>().CheckImpersonationFor(accessor.CanonicalLocalResourcePath))
            {
                //Only when the server is running as a service it will have elevation rights
                using (ImpersonationProcess ffmpeg = new ImpersonationProcess {
                    StartInfo = startInfo
                })
                {
                    IntPtr userToken = IntPtr.Zero;
                    if (!ImpersonationHelper.GetTokenByProcess(out userToken, true))
                    {
                        return(null);
                    }
#else
            {
                {
                    Process ffmpeg = new Process()
                    {
                        StartInfo = startInfo
                    };
#endif
#if !TRANSCODE_CONSOLE_TEST
                    ffmpeg.StartAsUser(userToken);
#else
                    ffmpeg.Start();
#endif
                    ffmpeg.BeginErrorReadLine();

                    var stream = ffmpeg.StandardOutput.BaseStream;
                    if (!ffmpeg.WaitForExit(transcoderTimeout))
                    {
                        ffmpeg.Kill();
                        stream.Dispose();
                        return(null);
                    }

                    ffmpeg.Close();
                    byte[] data = ReadToEnd(stream);
                    stream.Dispose();
#if !TRANSCODE_CONSOLE_TEST
                    NativeMethods.CloseHandle(userToken);
#endif
                    return(data);
                }
            }
        }
Example #4
0
 private static void Main(string[] args)
 {
     ImpersonationHelper.InvokeActionAsImpersonatedUserForRemoteResource <object, object>(
         ConfigurationHelper.AxUserName,
         ConfigurationHelper.AxUserDomain,
         ConfigurationHelper.AxUserPassword,
         f => { return(ReadLogFiles()); }, null);
 }
        private void comboBoxExistingDatabaseName_DropDownOpened(object sender, EventArgs e)
        {
            this.DisableInputMode();
            this.resetServerName();
            this.resetInstanceName();

            String[] databaseArray = null;
            try
            {
                if (!String.IsNullOrEmpty(this.serverName))
                {
                    using (ImpersonationHelper impersonationHelper = new ImpersonationHelper())
                    {
                        databaseArray = SetupDatabaseHelper.GetSqlDBNames(
                            !SetupDatabaseHelper.SqlServerIsOnLocalComputer(this.serverName),
                            this.serverName,
                            IsDefaultInstance(this.selectedInstance) ? String.Empty : this.selectedInstance,
                            this.port,
                            true);
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                this.EnableInputMode();
                this.comboBoxExistingDatabaseName.Text = String.Empty;
                this.comboBoxExistingDatabaseName.Items.Clear();

                if (databaseArray != null && databaseArray.Length > 0)
                {
                    foreach (String databaseName in databaseArray)
                    {
                        this.comboBoxExistingDatabaseName.Items.Add(databaseName);
                    }

                    // First satisfy the below scenario:
                    // - User clicked on existing db radio button and selected a db
                    // - then clicked new db radio button
                    // - and then clicked existing radio db again w/o changin server, instance, or port info
                    // Basically, check if the selected instance already exists in the list
                    // if yes, then choose it
                    // otherwise, this is a new population, select the first item
                    if (this.comboBoxExistingDatabaseName.Items.Contains(this.selectedDatabase))
                    {
                        this.comboBoxExistingDatabaseName.Text = selectedDatabase;
                    }
                    else
                    {
                        this.selectedDatabase = databaseArray[0];
                        this.comboBoxExistingDatabaseName.Text = this.selectedDatabase;
                    }
                }
            }
        }
        public object EvalAsUser(string applicationId, string script)
        {
            object result = null;

            ImpersonationHelper.InvokeAsUser(applicationId, new Action(() =>
            {
                result = this.Engine.Evaluate(script);
            }));
            return(result);
        }
Example #7
0
 public SSDsModelView()
 {
     InitializeComponent();
     ImpersonationHelper.Impersonate("CMSB", "mohit", "Password1", delegate
     {
         CompMgr  = new ClsComponentManager();
         CompColl = new ObservableCollection <ClsComponent>();
         LoadSSDsList();
     });
     DataContext = this;
 }
Example #8
0
        public void PublishFiles(IPublishProject project, Uri destination)
        {
            ImpersonationHelper helper = null;
            NetworkCredential   creds  = null;
            bool impersonated          = false;

            // Use ECWGC here so that a filter cannot run while we're impersonated (and so we always un-impersonate)
            System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
                (_) => {
                var files = project.Files;

                for (int i = 0; i < files.Count; i++)
                {
                    var item = files[i];

                    try {
                        // try copying without impersonating first...
                        CopyOneFile(destination, item, ref helper, creds);
                    } catch (UnauthorizedAccessException) {
                        if (impersonated)
                        {
                            // user entered incorrect credentials
                            throw;
                        }

                        // prompt for new credentials and switch to them if available.
                        var res = VsCredentials.PromptForCredentials(PythonToolsPackage.Instance, destination, new[] { "NTLM" }, "", out creds);
                        if (res == System.Windows.Forms.DialogResult.OK)
                        {
                            impersonated = true;
                            helper       = new ImpersonationHelper(creds);
                        }
                        else
                        {
                            throw;
                        }

                        // re-try the file copy w/ the new credentials.
                        CopyOneFile(destination, item, ref helper, creds);
                    }

                    project.Progress = (int)(((double)i / (double)files.Count) * 100);
                }
            },
                (data, exception) => {
                if (helper != null)
                {
                    helper.Dispose();
                }
            },
                null
                );
        }
Example #9
0
        public LaserficheRepository(IAppSettings appSetting)
        {
            var server                 = appSetting.GetString("lf.server");
            var repository             = appSetting.GetString("lf.repository");
            var user                   = appSetting.GetString("lf.user");
            var password               = appSetting.GetString("lf.password");
            var repositoryRegistration = new RepositoryRegistration(server, repository);

            _session = new Session();
            //_session.LogIn(user, password, repositoryRegistration);
            var impersonate = new ImpersonationHelper("ssf", user, password);

            impersonate.Impersonate(() => _session.LogIn(repositoryRegistration));
        }
        public object CallAsUser(string applicationId, FunctionInstance function, object thisObj, params object[] arguments)
        {
            if (thisObj == null || thisObj == Null.Value || thisObj == Undefined.Value)
            {
                thisObj = this.Engine.Global;
            }

            object result = null;

            ImpersonationHelper.InvokeAsUser(applicationId, new Action(() =>
            {
                result = function.Call(thisObj, arguments);
            }));

            return(result);
        }
        public object GetCredential(string applicationId)
        {
            var result = ImpersonationHelper.GetCredentialsFromSecureStore(applicationId);

            var networkCredential = result as NetworkCredential;

            if (networkCredential == null)
            {
                return(Null.Value);
            }

            var cred = new NetworkCredentialInstance(this.Engine.Object.InstancePrototype, result as NetworkCredential)
            {
                MaskPassword = true
            };

            return(cred);
        }
        private void comboBoxInstance_DropDownOpened(object sender, EventArgs e)
        {
            this.DisableInputMode();
            String[] instanceArray = null;
            try
            {
                this.resetServerName();
                if (!String.IsNullOrEmpty(this.serverName))
                {
                    using (ImpersonationHelper impersonationHelper = new ImpersonationHelper())
                    {
                        //PropertyBagDictionary.Instance.SafeAdd("SQLMachineName", this.serverName);
                        instanceArray = SetupDatabaseHelper.GetSqlInstanceNames(this.serverName);
                    }
                }
                this.comboBoxInstance.Text = String.Empty;
                this.comboBoxInstance.Items.Clear();
                if (instanceArray != null && instanceArray.Length > 0)
                {
                    foreach (String instanceName in instanceArray)
                    {
                        this.comboBoxInstance.Items.Add(instanceName);
                    }

                    if (this.comboBoxInstance.Items.Contains(this.selectedInstance))
                    {
                        this.comboBoxInstance.Text = this.selectedInstance;
                    }
                    else
                    {
                        this.selectedInstance      = instanceArray[0];
                        this.comboBoxInstance.Text = this.selectedInstance;
                    }
                }
            }
            catch (Exception backEndErrorException)
            {
                SetupLogger.LogException(backEndErrorException);
                SetupHelpers.ShowError(backEndErrorException.Message);
            }

            this.EnableInputMode();
        }
Example #13
0
        public void TestPublishFilesImpersonate()
        {
            var project = DebugProject.OpenProject(@"Python.VS.TestData\HelloWorld.sln");

            try {
                string subDir = Guid.NewGuid().ToString();
                project.Properties.Item("PublishUrl").Value = Path.Combine(TestSharePrivate, subDir);
                string dir = Path.Combine(TestSharePrivate, subDir);
                var    app = new VisualStudioApp(VsIdeTestHostContext.Dte);

                app.OpenSolutionExplorer();
                var window = app.SolutionExplorerTreeView;

                // find Program.py, send copy & paste, verify copy of file is there
                var programPy = window.FindItem("Solution 'HelloWorld' (1 project)", "HelloWorld");

                programPy.SetFocus();

                ThreadPool.QueueUserWorkItem(x => VsIdeTestHostContext.Dte.ExecuteCommand("Build.PublishSelection"));

                var creds = new CredentialsDialog(app.WaitForDialog());
                creds.UserName = PrivateShareUser;
                creds.Password = PrivateSharePassword;
                creds.Ok();

                System.Threading.Thread.Sleep(2000);

                using (var impHelper = new ImpersonationHelper(new System.Net.NetworkCredential(PrivateShareUser.Split('\\')[1], PrivateSharePassword, PrivateShareUser.Split('\\')[0]))) {
                    for (int i = 0; i < 10 && !Directory.Exists(dir); i++)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }

                    var files = Directory.GetFiles(dir);
                    Assert.AreEqual(files.Length, 1);
                    Assert.AreEqual(Path.GetFileName(files[0]), "Program.py");

                    Directory.Delete(dir, true);
                }
            } finally {
                project.Properties.Item("PublishUrl").Value = "";
            }
        }
        private void PopulateInstanceItemsWorker(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = sender as BackgroundWorker;

            if (backgroundWorker == null)
            {
                return;
            }

            String[] instanceArray = null;

            if (!String.IsNullOrEmpty(this.serverName))
            {
                using (ImpersonationHelper impersonationHelper = new ImpersonationHelper())
                {
                    instanceArray = SetupDatabaseHelper.GetSqlInstanceNames(this.serverName);
                }
            }

            e.Result = instanceArray;
        }
Example #15
0
        public async Task <IActionResult> Impersonate(ImpersonationViewModel model)
        {
            var user = await _userManager.FindByIdAsync(model.UserId);

            var newPrincipal = await _claimsFactory.CreateAsync(user);

            if (model.UserId != User.FindFirstValue(TolkClaimTypes.ImpersonatingUserId))
            {
                if (newPrincipal.IsInRole(Roles.SystemAdministrator))
                {
                    throw new InvalidOperationException("Cannot impersonate a system administrator user");
                }

                var newIdentity = newPrincipal.Identities.Single();

                ImpersonationHelper.SetupImpersonationClaims(User, newIdentity);
            }

            await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, newPrincipal);

            return(RedirectToAction("Index", "Home"));
        }
Example #16
0
        private static void CopyOneFile(Uri destination, IPublishFile item, ref ImpersonationHelper impersonate, NetworkCredential creds)
        {
            var    destFile = Path.Combine(destination.LocalPath, item.DestinationFile);
            string destDir  = Path.GetDirectoryName(destFile);

            if (!Directory.Exists(destDir))
            {
                // don't create a file share (\\foo\bar)
                if (!Path.IsPathRooted(destDir) || Path.GetPathRoot(destDir) != destDir)
                {
                    Directory.CreateDirectory(destDir);
                }
            }

            if (impersonate != null)
            {
                // we need to unimpersonate to read the file, then re-impersonate when we're done.
                using (FileStream destStream = new FileStream(destFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) {
                    impersonate.UndoImpersonate();
                    impersonate = null;
                    try {
                        using (FileStream file = new FileStream(item.SourceFile, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
                            byte[] buffer = new byte[1024];
                            int    bytesRead;
                            while ((bytesRead = file.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                destStream.Write(buffer, 0, bytesRead);
                            }
                        }
                    } finally {
                        impersonate = new ImpersonationHelper(creds);
                    }
                }
            }
            else
            {
                File.Copy(item.SourceFile, destFile, true);
            }
        }
        public override async Task ValidateAsync(CookieValidatePrincipalContext context)
        {
            var oldPrincipal = context?.Principal;

            await base.ValidateAsync(context);

            if (context.Principal == null ||                      // Session rejected by base class, everyting is handled.
                ReferenceEquals(oldPrincipal, context.Principal)) // Same principal => not time for refresh yet.
            {
                return;
            }

            var impersonatingUserId = oldPrincipal.FindFirstValue(TolkClaimTypes.ImpersonatingUserId);

            if (impersonatingUserId != null)
            {
                var impersonatingIdentity      = new ClaimsIdentity();
                var impersonatingSecurityStamp = oldPrincipal.FindFirstValue(TolkClaimTypes.ImpersonatingUserSecurityStamp);
                impersonatingIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, impersonatingUserId));
                impersonatingIdentity.AddClaim(new Claim(TolkClaimTypes.AspNetSecurityStamp, impersonatingSecurityStamp));
                var impersonatingPrincipal = new ClaimsPrincipal(impersonatingIdentity);

                var impersonatingUser = await _signInManager.ValidateSecurityStampAsync(impersonatingPrincipal);

                if (impersonatingUser != null &&
                    await _userManager.IsInRoleAsync(impersonatingUser, Roles.Impersonator))
                {
                    var newIdentity = context.Principal.Identities.Single();
                    ImpersonationHelper.SetupImpersonationClaims(oldPrincipal, newIdentity);
                }
                else
                {
                    context.RejectPrincipal();
                    await _signInManager.SignOutAsync();
                }
            }
        }
        private async void TranscodeProcessor(object args)
        {
            FFMpegTranscodeThreadData data = (FFMpegTranscodeThreadData)args;
            bool isStream = data.Context.Live && !data.Context.Segmented;
            bool isFile   = true;
            bool isSlimTv = false;

            try
            {
                if (data.Context.Segmented == true)
                {
                    await FFMpegPlaylistManifest.CreatePlaylistFilesAsync(data.TranscodeData).ConfigureAwait(false);
                }

                int  liveChannelId = 0;
                bool runProcess    = true;
                using (IResourceAccessor mediaAccessor = data.TranscodeData.GetFirstResourceAccessor())
                {
                    if (mediaAccessor is ITranscodeLiveAccessor tla)
                    {
                        isSlimTv      = true;
                        liveChannelId = tla.ChannelId;
                    }
                }

                data.Context.Start();
                data.TranscodeData.ClearRuntimeResourcePaths();
                int exitCode = -1;

                string identifier = "Transcode_" + data.TranscodeData.ClientId;
                if (isSlimTv)
                {
                    var result = await _slimtTvHandler.StartTuningAsync(identifier, liveChannelId).ConfigureAwait(false);

                    if (!result.Success)
                    {
                        _logger.Error("FFMpegMediaConverter: Transcoder unable to start timeshifting for channel {0}", liveChannelId);
                        runProcess = false;
                        exitCode   = 5000;
                    }
                    else
                    {
                        using (var mediaAccessor = await _slimtTvHandler.GetDefaultAccessorAsync(liveChannelId).ConfigureAwait(false))
                        {
                            if (mediaAccessor is INetworkResourceAccessor)
                            {
                                int mediaStreamIndex = data.TranscodeData.FirstResourceIndex;
                                data.TranscodeData.AddRuntimeResourcePath(ResourcePath.Deserialize(data.TranscodeData.InputMediaFilePaths[mediaStreamIndex]), mediaAccessor.CanonicalLocalResourcePath.Serialize());
                            }
                            else
                            {
                                _logger.Error("FFMpegMediaConverter: Transcoder unable to start timeshifting for channel {0} because no URL was found", liveChannelId);
                                runProcess = false;
                                exitCode   = 5001;
                            }
                        }
                    }
                }

                ResourcePath firstPath;
                using (var mediaAccessor = data.TranscodeData.GetFirstResourceAccessor())
                {
                    firstPath = mediaAccessor.CanonicalLocalResourcePath;
                    if (mediaAccessor is INetworkResourceAccessor)
                    {
                        isFile = false;
                    }
                }

                if (runProcess)
                {
                    //Prepare resources
                    List <IDisposable> disposables = new List <IDisposable>();
                    foreach (var res in data.TranscodeData.GetResourceAccessors())
                    {
                        if (!(res is INetworkResourceAccessor))
                        {
                            var rah = new LocalFsResourceAccessorHelper(res);
                            data.TranscodeData.AddRuntimeResourcePath(res.CanonicalLocalResourcePath, rah.LocalFsResourceAccessor.LocalFileSystemPath);
                            var accessToken = rah.LocalFsResourceAccessor.EnsureLocalFileSystemAccess();
                            if (accessToken != null)
                            {
                                disposables.Add(accessToken);
                            }
                            disposables.Add(rah);
                        }

                        disposables.Add(res);
                    }

                    ProcessStartInfo startInfo = new ProcessStartInfo()
                    {
                        FileName               = data.TranscodeData.TranscoderBinPath,
                        WorkingDirectory       = data.TranscodeData.WorkPath,
                        Arguments              = data.TranscodeData.TranscoderArguments,
                        UseShellExecute        = false,
                        CreateNoWindow         = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        RedirectStandardInput  = true,
                        StandardOutputEncoding = Encoding.UTF8,
                        StandardErrorEncoding  = Encoding.UTF8
                    };

                    _logger.Debug("FFMpegMediaConverter: Transcoder '{0}' invoked with command line arguments '{1}'", data.TranscodeData.TranscoderBinPath, data.TranscodeData.TranscoderArguments);

                    IntPtr userToken = IntPtr.Zero;
                    try
                    {
                        //TODO: Fix usages of obsolete and deprecated methods when alternative is available
#if !TRANSCODE_CONSOLE_TEST
                        using (ServiceRegistration.Get <IImpersonationService>().CheckImpersonationFor(firstPath))
                        {
                            //Only when the server is running as a service it will have elevation rights
                            using (ImpersonationProcess ffmpeg = new ImpersonationProcess {
                                StartInfo = startInfo
                            })
                            {
                                if (isFile && !ImpersonationHelper.GetTokenByProcess(out userToken, true))
                                {
                                    return;
                                }
#else
                        {
                            using (Process ffmpeg = new Process()
                            {
                                StartInfo = startInfo
                            })
                            {
#endif
                                ffmpeg.EnableRaisingEvents = true; //Enable raising events because Process does not raise events by default.
                                if (isStream == false)
                                {
                                    ffmpeg.OutputDataReceived += data.Context.OutputDataReceived;
                                }

                                ffmpeg.ErrorDataReceived += data.Context.ErrorDataReceived;
#if !TRANSCODE_CONSOLE_TEST
                                if (isFile)
                                {
                                    ffmpeg.StartAsUser(userToken);
                                }
                                else
                                {
                                    ffmpeg.Start();
                                }
#else
                                ffmpeg.Start();
#endif
                                ffmpeg.BeginErrorReadLine();
                                if (isStream == false)
                                {
                                    ffmpeg.BeginOutputReadLine();
                                }
                                else
                                {
                                    data.TranscodeData.LiveStream = ffmpeg.StandardOutput.BaseStream;
                                }

                                RunTranscodingProcess(ffmpeg, data, isStream);

                                ffmpeg.WaitForExit();
                                exitCode = ffmpeg.ExitCode;
                                ffmpeg.Close();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (isStream || data.TranscodeData.OutputFilePath == null)
                        {
                            _logger.Error("FFMpegMediaConverter: Transcoder command failed for stream '{0}'", ex, data.TranscodeData.TranscodeId);
                        }
                        else
                        {
                            _logger.Error("FFMpegMediaConverter: Transcoder command failed for file '{0}'", ex, data.TranscodeData.OutputFilePath);
                        }

                        data.Context.Fail();
                    }
                    finally
                    {
#if !TRANSCODE_CONSOLE_TEST
                        if (userToken != IntPtr.Zero)
                        {
                            NativeMethods.CloseHandle(userToken);
                        }
#endif
                        data.TranscodeData.LiveStream?.Dispose();
                        foreach (var disposable in disposables)
                        {
                            disposable?.Dispose();
                        }
                    }
                }

                if (exitCode > 0)
                {
                    data.Context.Fail();
                }
                else
                {
                    data.Context.Stop();
                }
                _ffMpegEncoderHandler.EndEncoding(data.TranscodeData.Encoder, data.TranscodeData.TranscodeId);

                if (isSlimTv)
                {
                    if (await _slimtTvHandler.EndTuningAsync(identifier).ConfigureAwait(false) == false)
                    {
                        _logger.Error("FFMpegMediaConverter: Transcoder unable to stop timeshifting for channel {0}", liveChannelId);
                    }
                }

                string filePath = data.Context.TargetFile;
                bool   isFolder = false;
                if (string.IsNullOrEmpty(data.Context.SegmentDir) == false)
                {
                    filePath = data.Context.SegmentDir;
                    isFolder = true;
                }

                if (exitCode > 0 || data.Context.Aborted)
                {
                    if (exitCode > 0)
                    {
                        if (isStream || data.TranscodeData.OutputFilePath == null)
                        {
                            _logger.Debug("FFMpegMediaConverter: Transcoder command failed with error {1} for stream '{0}'", data.TranscodeData.TranscodeId, exitCode);
                        }
                        else
                        {
                            _logger.Debug("FFMpegMediaConverter: Transcoder command failed with error {1} for file '{0}'", data.TranscodeData.OutputFilePath, exitCode);
                        }
                    }

                    if (data.Context.Aborted)
                    {
                        if (isStream || data.TranscodeData.OutputFilePath == null)
                        {
                            _logger.Debug("FFMpegMediaConverter: Transcoder command aborted for stream '{0}'", data.TranscodeData.TranscodeId);
                        }
                        else
                        {
                            _logger.Debug("FFMpegMediaConverter: Transcoder command aborted for file '{0}'", data.TranscodeData.OutputFilePath);
                        }
                    }
                    else
                    {
                        _logger.Debug("FFMpegMediaConverter: FFMpeg error \n {0}", data.Context.ConsoleErrorOutput);
                    }

                    data.Context.DeleteFiles();
                }
                else
                {
                    //Touch cache files so they will not be cleaned up
                    if (isFolder == false)
                    {
                        TouchFile(filePath);
                    }
                    else
                    {
                        TouchDirectory(filePath);
                    }
                }
            }
            catch (Exception ex)
            {
                if (isStream || data.TranscodeData.OutputFilePath == null)
                {
                    _logger.Error("FFMpegMediaConverter: Transcoder failed processing '{0}'", ex, data.TranscodeData.TranscodeId);
                }
                else
                {
                    _logger.Error("FFMpegMediaConverter: Transcoder failed processing file '{0}'", ex, data.TranscodeData.OutputFilePath);
                }
            }
            finally
            {
                await RemoveTranscodeContextAsync(data.TranscodeData.ClientId, data.TranscodeData.TranscodeId, data.Context).ConfigureAwait(false);
            }
        }
 public static SafeAccessTokenHandle Impersonate([NotNull] this NetworkCredential thisValue, LogonType logonType)
 {
     return(ImpersonationHelper.Impersonate(thisValue, logonType));
 }
Example #20
0
        public bool CheckDuplicate(Ticket ticket)
        {
            string host                     = "";
            string path                     = "";
            string fullFileName             = "";
            string fileNameWithoutExtension = "";
            string extension                = "";
            string cmdRename                = "";
            string cmdCheck                 = "";
            // ticket.RootText e.g. of content  "File already exists: /opt/cloudhost/intbroker/integrations/archive/incoming/BI/FieldGlass-TimeSheet-20170309.csv already exists on the remote filesystem"
            int posPath = ticket.RootText.LastIndexOf("/");

            if (posPath >= 0)
            {
                path = ticket.RootText.Substring(0, posPath);
            }
            // path e.g. of content "File already exists: /opt/cloudhost/intbroker/integrations/archive/incoming/BI"
            path = path.Substring(path.IndexOf("/"), path.Length - path.IndexOf("/"));
            // path e.g. of content  "/opt/cloudhost/intbroker/integrations/archive/incoming/BI"
            int x = 0;

            //exit=true represents a rename applied and will check over the list of affected servers if multiple ( like a cluster )
            while (exit != true && x < ticket.HostArray.Length)
            {
                host         = ticket.HostArray[x];
                fullFileName = ticket.RootText.Substring(ticket.RootText.LastIndexOf("/"), ticket.RootText.Length - ticket.RootText.LastIndexOf("/"));
                fullFileName = fullFileName.Substring(0, fullFileName.IndexOf(" "));
                // fullFileName e.g. of content "/FieldGlass-TimeSheet-20170309.csv"

                //Saves extension of the file if it has to be used later while renaming
                int filePos = fullFileName.IndexOf(".");
                if (filePos >= 0)
                {
                    fileNameWithoutExtension = fullFileName.Substring(0, filePos);
                }
                // fileNameWithoutExtension e.g. of content "/FieldGlass-TimeSheet-20170309"
                if (filePos != -1)
                {
                    extension = fullFileName.Substring(filePos, fullFileName.Length - filePos);
                }
                // extension e.g. of content ".csv"

                //LINUX CONNECTION
                try
                {
                    SshConnection con    = new SshConnection(host, user, passwd);
                    SshClient     sshCon = con.connect();
                    if (path.EndsWith("/"))
                    {
                        path = path.Substring(0, path.Length - 1);
                    }

                    string OS = sshCon.RunCommand("uname").Result;
                    if (OS == "Linux\n")
                    {
                        //Run the commmand to check if file exists and rename if necessary
                        cmdCheck = "/opt/pb/bin/pbrun bash -c 'ls -l " + path + fullFileName + ";'";
                        var command = sshCon.RunCommand(cmdCheck);
                        if (command.ExitStatus == 0)
                        {
                            cmdRename = "/opt/pb/bin/pbrun bash -c 'cd " + path + ";" + "mv " + path + fullFileName + " " + path + fileNameWithoutExtension + "_$(date +%s)" + extension + ";'";
                            if (sshCon.RunCommand(cmdRename).ExitStatus == 0)
                            {
                                exit = true;
                                return(exit);
                            }
                        }
                    }
                    if (OS == "HP-UX\n")
                    {
                        //Run the commmand to check if file exists and rename if necessary
                        cmdCheck = "/opt/pb/bin/pbrun ksh -c 'ls -l " + path + fullFileName + ";'";
                        var command = sshCon.RunCommand(cmdCheck);
                        if (command.ExitStatus == 0)
                        {
                            cmdRename = "/opt/pb/bin/pbrun ksh -c 'cd " + path + ";" + "mv " + path + fullFileName + " " + path + fileNameWithoutExtension + "_$(date +%s)" + extension + ";'";
                            if (sshCon.RunCommand(cmdRename).ExitStatus == 0)
                            {
                                exit = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                }
                //WINDOWS CONNECTION
                try
                {
                    string DomainSvcAccount    = "";
                    string winUserSvcAccount   = "";
                    string winPasswdSvcAccount = "";
                    ImpersonationHelper.Impersonate(DomainSvcAccount, winUserSvcAccount, winPasswdSvcAccount, delegate
                    {
                        //Your code here
                        //If connection was done
                        if (File.Exists(@"\\\iten\hpsb.txt"))
                        {
                            string origin      = "\\" + host + path.Replace(@"/", @"\") + fileNameWithoutExtension.Replace(@"/", @"\");
                            string destination = "\\" + host + path.Replace(@"/", @"\") + fileNameWithoutExtension.Replace(@"/", @"\") + "1";
                            File.Move(@"\\hc4w00433\iten\hpsb.txt", @"\\hc4w00433\iten\hpsb.txt1");
                            exit = true;
                        }
                    });
                }
                catch (Exception e)
                {
                }

                x++;
            }
            //Exit contains a vaule True if ticket was SOLVED
            return(exit);
        }
 public void ExecAsUser(string applicationId, string script)
 {
     ImpersonationHelper.InvokeAsUser(applicationId, new Action(() => this.Engine.Execute(script)));
 }
Example #22
0
 public static void InvokeWithElevatedPrivilege([NotNull] this ServiceController thisValue, [NotNull] Action <ServiceController> action)
 {
     ImpersonationHelper.RunWithElevatedPrivilege(() => action(thisValue));
 }
Example #23
0
 public static T InvokeWithElevatedPrivilege <T>([NotNull] this ServiceController thisValue, [NotNull] Func <ServiceController, T> action)
 {
     return(ImpersonationHelper.RunWithElevatedPrivilege(() => action(thisValue)));
 }
Example #24
0
 public static void InvokeWithCredential([NotNull] this ServiceController thisValue, [NotNull] Action <ServiceController> action, [NotNull] NetworkCredential credential)
 {
     ImpersonationHelper.RunWithCredential(credential, LogonType.Interactive, () => action(thisValue));
 }
Example #25
0
 public static T InvokeWithCredential <T>([NotNull] this ServiceController thisValue, [NotNull] Func <ServiceController, T> action, [NotNull] NetworkCredential credential)
 {
     return(ImpersonationHelper.RunWithCredential(credential, LogonType.Interactive, () => action(thisValue)));
 }