void deimpersonateLink_Click(object sender, EventArgs e)
        {
            if (UserImpersonation.IsImpersonating)
            {
                if (Deimpersonate != null)
                {
                    Deimpersonate.Invoke(this, new EventArgs());
                }

                UserImpersonation.Deimpersonate();
            }
        }
示例#2
0
        /// <summary>
        /// Indexes the files.
        /// </summary>
        /// <param name="servers">The servers.</param>
        /// <returns></returns>
        public bool CreateIndexFiles(ProductType productType)
        {
            string ImpersonatedUser         = ConfigurationManager.AppSettings.Get("User");
            string ImpersonatedUserPassword = ConfigurationManager.AppSettings.Get("Password");
            string ImpersonatedUserDomain   = ConfigurationManager.AppSettings.Get("Domain");

            using (UserImpersonation user = new UserImpersonation(ImpersonatedUser, ImpersonatedUserDomain, ImpersonatedUserPassword))
            {
                if (user.ImpersonateValidUser())
                {
                    XmlProcessor processor = new XmlProcessor();
                    Product      product   = processor.ReadProduct(productType);

                    if (product.LastIndexedDate.HasValue && DateTime.Compare(product.LastIndexedDate.Value, DateTime.Today) == 0)
                    {
                        return(true);
                    }

                    DateTime startDate = product.LastIndexedDate ?? product.IndexStartDate;
                    DateTime endDate   = DateTime.Today.AddDays(-1);

                    string targetDirectory = ConfigurationManager.AppSettings.Get("DecompressedFolder");
                    string indexLocation   = ConfigurationManager.AppSettings.Get("IndexFolder") + productType.ToString();
                    ClearLogDecompress(targetDirectory);
                    DeleteEarlierIndexes(product, processor);

                    while (startDate <= endDate)
                    {
                        foreach (string file in processor.CopyFiles(startDate.ToShortDateString(), productType))
                        {
                            string   fileName;
                            FileInfo fi = new DirectoryInfo(targetDirectory).GetFiles("*.zip").FirstOrDefault();

                            fileName = fi != null?processor.DecompressFile(fi) : string.Empty;

                            if (!string.IsNullOrEmpty(fileName))
                            {
                                LuceneIndexer    li  = new LuceneIndexer();
                                HashSet <string> set = processor.ReadFile(product, fileName);
                                li.IndexFile(indexLocation, fileName, startDate.ToShortDateString(), set);
                            }
                        }

                        startDate = startDate.AddDays(1);
                        this.UpdateProductDate(product, startDate, "LastIndexedDate");
                    }
                }
            }

            return(true);
        }
示例#3
0
        public FileResult DownloadEDDMessage()
        {
            string ImpersonatedUser         = ConfigurationManager.AppSettings.Get("User");
            string ImpersonatedUserPassword = ConfigurationManager.AppSettings.Get("Password");
            string ImpersonatedUserDomain   = ConfigurationManager.AppSettings.Get("Domain");

            string clientPath = ConfigurationManager.AppSettings.Get("TargetFolder")
                                + HttpContext.Request.UserHostAddress;
            string storagePath  = clientPath + "\\EDDMessages";
            string zipTo        = storagePath + ".zip";
            string downloadName = this.logDataModel.PolicyId + ".zip";

            using (UserImpersonation user = new UserImpersonation(ImpersonatedUser, ImpersonatedUserDomain, ImpersonatedUserPassword))
            {
                if (user.ImpersonateValidUser())
                {
                    HelperClass.CreateDirectory(clientPath);
                    HelperClass.CreateDirectory(storagePath);

                    foreach (EDDIORow row in this.logDataModel.EddKeys)
                    {
                        this.logDataModel.EddKey = string.Format("{0}-{1}", row.TRANSACTION_TIME, row.IO_CHAR);
                        string EDDMessage = this.CreateEDDMessage().Replace("|", "|\r\n");
                        string filename   = ConfigurationManager.AppSettings.Get("TargetFolder")
                                            + HttpContext.Request.UserHostAddress
                                            + string.Format("\\EDDMessages\\{0} {1}-{2}-{3}.txt", this.logDataModel.PolicyId,
                                                            row.TRANSACTION_TIME.Replace("/", "-").Replace(":", "-"),
                                                            row.MSG_ID, string.Equals(row.IO_CHAR, "I") ? "Input" : "Output");

                        using (StreamWriter writer = new StreamWriter(filename, false))
                        {
                            writer.WriteLine(EDDMessage);
                            writer.Close();
                        }
                    }



                    using (ZipFile zip = new ZipFile())
                    {
                        zip.AddDirectory(storagePath);
                        zip.Save(zipTo);
                    }
                }
            }
            return(File(zipTo, "application/zip", downloadName));
        }
示例#4
0
        static void Main(string[] args)
        {
            string login    = "";
            string domain   = "";
            string password = "";

            using (UserImpersonation user = new UserImpersonation(login, domain, password))
            {
                if (user.Connected)
                {
                    File.WriteAllText("test2.txt", "Voici mon texte");
                    Console.WriteLine("File writed");
                }
                else
                {
                    Console.WriteLine("User not connected");
                }
            }

            Console.ReadKey();
        }
示例#5
0
        private ActiveDirectoryUser SearchActiveDirectory(string samAccount, string domain)
        {
            if (string.IsNullOrWhiteSpace(domain))
            {
                domain = Environment.UserDomainName;
            }

            // Store the search results as a collection of Users.  This list will be returned.
            var user = new ActiveDirectoryUser();

            user.SamId = samAccount;

            string ldapPath     = $"LDAP://{domain}";
            string searchFilter =
                "(&(objectCategory=person)(objectClass=user)" +
                $"(sAMAccountName={samAccount}))";

            string[] searchProperties =
            {
                "givenName",
                "sn",
                "physicalDeliveryOfficeName",
                "telephoneNumber",
                "mail",
                "title",
                "department",
                "memberOf",
                "objectSid",
                "pwdLastSet",
                "distinguishedName"
            };

            try
            {
                using (
                    GlobalVar.UseAlternateCredentials
                    ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                    : null)
                    using (DirectoryEntry parentEntry = new DirectoryEntry(ldapPath))
                        using (DirectorySearcher directorySearcher = new DirectorySearcher(parentEntry, searchFilter, searchProperties))
                            using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
                            {
                                // Iterate through each search result.
                                foreach (SearchResult searchResult in searchResultCollection)
                                {
                                    DirectoryEntry entry = new DirectoryEntry(searchResult.GetDirectoryEntry().Path);

                                    user.NameFirst = (entry.Properties["givenName"].Value != null) ?
                                                     entry.Properties["givenName"].Value.ToString() : string.Empty;
                                    user.NameLast = (entry.Properties["sn"].Value != null) ?
                                                    entry.Properties["sn"].Value.ToString() : string.Empty;
                                    user.OfficeLocation = (entry.Properties["physicalDeliveryOfficeName"].Value != null)
                            ? entry.Properties["physicalDeliveryOfficeName"].Value.ToString() : string.Empty;
                                    user.OfficePhone = (entry.Properties["telephoneNumber"].Value != null) ?
                                                       entry.Properties["telephoneNumber"].Value.ToString() : string.Empty;
                                    user.JobDepartment = (entry.Properties["department"].Value != null) ?
                                                         entry.Properties["department"].Value.ToString() : string.Empty;
                                    user.JobTitle = (entry.Properties["title"].Value != null) ?
                                                    entry.Properties["title"].Value.ToString() : string.Empty;
                                    user.EmailAddress = (entry.Properties["mail"].Value != null) ?
                                                        entry.Properties["mail"].Value.ToString() : string.Empty;

                                    if (entry.Properties["objectSid"].Value != null)
                                    {
                                        user.SID = new SecurityIdentifier((byte[])entry.Properties["objectSid"].Value, 0).ToString();
                                    }

                                    if (entry.Properties["memberOf"] != null)
                                    {
                                        user.MemberOf = entry.Properties["memberOf"];
                                    }

                                    //user.PasswordLastSet = (entry.Properties["pwdLastSet"].Value != null) ? entry.Properties["pwdLastSet"].Value.ToString() : string.Empty;

                                    for (int i = 0; i < user.MemberOf.Count; ++i)
                                    {
                                        int startIndex = user.MemberOf[i].ToString().IndexOf("CN=", 0) + 3; //+3 for  length of "OU="
                                        int endIndex   = user.MemberOf[i].ToString().IndexOf(",", startIndex);
                                        user.MemberOf[i] = user.MemberOf[i].ToString().Substring((startIndex), (endIndex - startIndex));
                                    }

                                    user.DistinguishedName = entry.Properties["distinguishedName"].Value.ToString();
                                    string dn           = entry.Properties["distinguishedName"].Value.ToString();
                                    int    dnStartIndex = dn.IndexOf(",", 1) + 4; //+3 for  length of "OU="
                                    int    dnEndIndex   = dn.IndexOf(",", dnStartIndex);
                                    user.OrganizationalUnit = dn.Substring((dnStartIndex), (dnEndIndex - dnStartIndex));
                                }
                            }
            }
            catch
            { }

            return(user);
        }
示例#6
0
        public ActionResult Index_Search(IndexModel model, string Find, string Stop)
        {
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(Find))
                {
                    IndexModel.Cancel              = new CancellationTokenSource();
                    IndexModel.CancelToken         = IndexModel.Cancel.Token;
                    IndexModel.ErrorOrAbort        = false;
                    model.EnableLogging            = bool.Parse(ConfigurationManager.AppSettings.Get("Enablelogging"));
                    model.ImpersonatedUser         = ConfigurationManager.AppSettings.Get("User");
                    model.ImpersonatedUserPassword = ConfigurationManager.AppSettings.Get("Password");
                    model.ImpersonatedUserDomain   = ConfigurationManager.AppSettings.Get("Domain");
                    model.SearchLocation           = ConfigurationManager.AppSettings.Get("ProductionLogsFolder");
                    List <string> productionServers = ConfigurationManager.AppSettings.Get("ProductionServers" + model.AppName).Split(new char[] { ',' }, StringSplitOptions.None).ToList <string>();
                    List <IndexerService.IndexInformation> files = new List <IndexInformation>();
                    model.ClientIP = HttpContext.Request.UserHostAddress;
                    string        targetDirectory = ConfigurationManager.AppSettings.Get("TargetFolder");
                    List <string> productionLogFiles;

                    if (model.IsProduction)
                    {
                        using (UserImpersonation user = new UserImpersonation(model.ImpersonatedUser, model.ImpersonatedUserDomain, model.ImpersonatedUserPassword))
                        {
                            if (user.ImpersonateValidUser())
                            {
                                try
                                {
                                    ServiceClient client = new ServiceClient();
                                    Engine.BrodCast(model.ConnectionId, "Creating Index.");
                                    if (client.CreateIndexFiles(model.AppName.GetEnumForValue <ProductType>()))
                                    {
                                        Engine.BrodCast(model.ConnectionId, "Search Started.");
                                        foreach (IndexerService.IndexInformation indexInformation in client.SearchIndex(model.AppName.GetEnumForValue <ProductType>(), model.SearchText))
                                        {
                                            files.Add(indexInformation);
                                        }
                                    }

                                    Engine.BrodCast(model.ConnectionId, string.Format("Found in server files: {0}", files.Count));

                                    if (files.Count > 0)
                                    {
                                        productionLogFiles = Engine.GetFileList(files, model);
                                        Engine.SearchInProductionServersSequentially(model, productionLogFiles);
                                    }
                                    else
                                    {
                                        model.ResultMessage = "No result found for this request.";
                                        //Engine.BrodCast(model.ConnectionId, model.ProcessCompleteMessage);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (model.EnableLogging)
                                    {
                                        Engine.BrodCast(model.ConnectionId, ex.Message);
                                    }
                                    IndexModel.ErrorOrAbort = true;
                                    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                                    model.ResultMessage = "Bad bad Server....Error Occurred, Search Aborted";
                                }
                                finally
                                {
                                    if (IndexModel.CancelToken.IsCancellationRequested)
                                    {
                                        Engine.BrodCast(model.ConnectionId, "Search Aborted");
                                    }
                                    Engine.WriteToFile(model.Results, model);
                                }
                            }
                        }
                    }
                }
                else
                {
                    IndexModel.Cancel.Cancel();
                    IndexModel.ErrorOrAbort = true;
                    model.ResultMessage     = "Search Aborted";
                    Engine.BrodCast(model.ConnectionId, model.ProcessCompleteMessage);
                }
            }
            Engine.BrodCast(model.ConnectionId, model.ProcessCompleteMessage);
            if (model.Results != null && model.Results.Count > 0)
            {
                this.logDataModel.EchannelLogs = model.Results;
            }
            return(PartialView("Results", model));
        }
示例#7
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            const string odbcRoot             = @"SOFTWARE\ODBC\ODBC.INI";
            const string odbcRoot32bitOn64bit = @"SOFTWARE\Wow6432Node\ODBC\ODBC.INI";
            const string serviceName          = "RemoteRegistry";
            bool         isLocal          = RemoteSystemInfo.TargetComputer.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
            bool         isServiceRunning = true;

            // If the target computer is remote, then start the Remote Registry service.
            using (
                GlobalVar.UseAlternateCredentials
                ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                : null)
                using (var sc = new ServiceController(serviceName, RemoteSystemInfo.TargetComputer))
                {
                    try
                    {
                        if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                        {
                            isServiceRunning = false;
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running);
                        }
                    }
                    catch { }

                    try
                    {
                        using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, RemoteSystemInfo.TargetComputer))
                        {
                            if (_OdbcDsn.Is32bitOn64bit)
                            {
                                using (RegistryKey subKey = key.OpenSubKey($@"{odbcRoot32bitOn64bit}\{_OdbcDsn.DataSourceName}", true))
                                {
                                    if (subKey != null)
                                    {
                                        subKey.SetValue(_OdbcValue.OdbcValueName, txtOdbcNewValue.Text);
                                    }
                                }
                            }
                            else
                            {
                                using (RegistryKey subKey = key.OpenSubKey($@"{odbcRoot}\{_OdbcDsn.DataSourceName}", true))
                                {
                                    if (subKey != null)
                                    {
                                        subKey.SetValue(_OdbcValue.OdbcValueName, txtOdbcNewValue.Text);
                                    }
                                }
                            }
                        }
                    }
                    catch { }

                    // Cleanup.
                    if (!isLocal && !isServiceRunning)
                    {
                        try
                        {
                            if (sc != null)
                            {
                                sc.Stop();
                            }
                        }

                        catch (Exception)
                        {
                        }
                    }
                }

            this.Close();
        }
示例#8
0
        /// <summary>
        /// Copies down the newest movie from main storage
        /// </summary>
        public void GetNewestVideo()
        {
            UserImpersonation impersonator = new UserImpersonation();
            impersonator.impersonateUser();

            DirectoryInfo di = new DirectoryInfo(@"\\MAINSTORAGE\Design\Animation\Done\DONE FOR UPLOADING\1080p");

            string user = Controller.dir;

            if (di.Exists)
            {
                try
                {
                    var collection = di.EnumerateFiles();
                    var newestVideo = collection.ElementAt(1);

                    // Indicafilete that the directory already exists.
                    foreach (var item in collection)
                    {
                        if (item.Extension.ToLower() == ".mp4")
                        {
                            if (newestVideo.CreationTime < item.CreationTime)
                            {
                                newestVideo = item;
                            }
                        }
                    }

                    Controller.newestVideoDate = newestVideo.CreationTime;
                    int extention = newestVideo.Name.Count() - 4;

                    if (Controller.newestVideoName == newestVideo.Name.Remove(extention))
                    {
                    }
                    else
                    {
                        if (File.Exists(user + newestVideo.Name))
                            Controller.newestVideoName = newestVideo.Name.Remove(extention);
                        else
                        {
                            DirectoryInfo direc = new DirectoryInfo(user);
                            FileInfo[] files = direc.GetFiles("*.mp4").Where(p => p.Extension == ".mp4").ToArray();
                            foreach (FileInfo file in files)
                            {
                                try
                                {
                                    file.Attributes = FileAttributes.Normal;
                                    File.Delete(file.FullName);
                                }
                                catch { }
                            }

                            Controller.newestVideoName = newestVideo.Name.Remove(extention);
                            File.Copy(newestVideo.FullName, user + newestVideo.Name);
                        }
                    }
                }
                catch (Exception) {}
            }
            else
            {
                DirectoryInfo direc = new DirectoryInfo(user);
                FileInfo[] files = direc.GetFiles("*.mp4").Where(p => p.Extension == ".mp4").ToArray();
                foreach (FileInfo file in files)
                {
                    try
                    {
                        Controller.newestVideoName = file.Name.Remove(file.Name.Count()-4);
                        Controller.newestVideoDate = file.CreationTime;
                    }
                    catch { }
                }
                if (CheckInternetConnection())
                {
                    System.Windows.MessageBox.Show(@"Der kan være opstået et problem med brugeren til i MainStorageUsers.txt. Opdater den her: C:\Users\[User]\(SKJULT)AppData\Local\ATIS", "MainStorage Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
        }
示例#9
0
 protected void Impersonate(object sender, EventArgs e)
 {
     UserImpersonation.ImpersonateUser("Alice", "~/Deimpersonate.aspx");
     Response.Redirect("~/Default.aspx");
 }