public BeanstalkEnvironmentCommand(IToolInteractiveService toolInteractiveService, IAWSResourceQueryer awsResourceQueryer, OrchestratorSession session, ConsoleUtilities consoleUtilities)
 {
     _toolInteractiveService = toolInteractiveService;
     _awsResourceQueryer     = awsResourceQueryer;
     _session          = session;
     _consoleUtilities = consoleUtilities;
 }
Example #2
0
 private static async Task SocketLog(LogMessage arg)
 {
     ConsoleUtilities.LogCustom(arg.Severity, arg.Message);
     await Task.Delay(100);
 }
 public DotnetPublishBuildConfigurationCommand(ConsoleUtilities consoleUtilities)
 {
     _consoleUtilities = consoleUtilities;
 }
Example #4
0
        static void Main(string[] args)
        {
            ConsoleUtilities consoleUtilities = new ConsoleUtilities();

            consoleUtilities.WriteLine("Hello World");
        }
Example #5
0
 public DotnetPublishArgsCommand(ConsoleUtilities consoleUtilities)
 {
     _consoleUtilities = consoleUtilities;
 }
Example #6
0
        private static void ProcessFeed(HttpListenerRequest p_HttpRequest)
        {
            s_Response.statusCode = HttpStatusCode.OK;
            s_Response.reason     = "";

            if (p_HttpRequest != null && p_HttpRequest.HttpMethod == HttpMethod.Post.Method.ToUpperInvariant())
            {
                ConsoleUtilities.WriteLine("Processing the GSA Feed.", ConsoleColor.Green);

                string sourceId = s_Configuration.SourceId;
                string orgId    = s_Configuration.OrganizationId;
                string apiKey   = s_Configuration.ApiKey;

                // Read in the query string parameters to optionally allow the post to direct the push.
                // The SourceId is not optional.
                foreach (string q_key in p_HttpRequest.QueryString.AllKeys)
                {
                    if (string.Equals(q_key, "sourceid", StringComparison.OrdinalIgnoreCase))
                    {
                        sourceId = p_HttpRequest.QueryString.Get(q_key);
                    }
                    else if (string.Equals(q_key, "orgid", StringComparison.OrdinalIgnoreCase))
                    {
                        orgId = p_HttpRequest.QueryString.Get(q_key);
                    }
                    else if (string.Equals(q_key, "apikey", StringComparison.OrdinalIgnoreCase))
                    {
                        apiKey = p_HttpRequest.QueryString.Get(q_key);
                    }
                    else if (string.Equals(q_key, "providerid", StringComparison.OrdinalIgnoreCase))
                    {
                        s_Configuration.ProviderId = p_HttpRequest.QueryString.Get(q_key);
                    }
                }

                if (sourceId != null)
                {
                    string        feedFilePath = p_HttpRequest.Headers.Get("FeedFilePath");
                    GsaFeedParser parser       = new GsaFeedParser(feedFilePath);
                    GsaFeedHeader header       = parser.ParseFeedHeader();

                    if (header == null)
                    {
                        m_Logger.Fatal("Malformed XML exception, aborting.");
                        return;
                    }

                    string datasource = header.DataSource;
                    string feedtype   = header.FeedType.ToString();

                    ICoveoPushApiConfig clientConfig = new CoveoPushApiConfig(s_Configuration.PushApiEndpointUrl, s_Configuration.PlatformApiEndpointUrl, apiKey, orgId);
                    ICoveoPushApiClient client       = new CoveoPushApiClient(clientConfig);

                    m_Logger.Info("--------------------------------------------------------");
                    m_Logger.Info("Organization: " + orgId);
                    m_Logger.Info("Security provider: " + s_Configuration.ProviderId);
                    m_Logger.Info("Push source: " + sourceId);
                    m_Logger.Info("Datasource: " + datasource + ", Type: " + feedtype);
                    m_Logger.Info("Feed File: " + feedFilePath);
                    m_Logger.Info("Records:");

                    int addedDocs   = 0;
                    int deletedDocs = 0;
                    int ignoredDocs = 0;

                    ulong orderingIdRef      = 0;
                    ulong firstOrderingIdRef = 0;

                    try
                    {
                        client.ActivityManager.UpdateSourceStatus(sourceId, header.FeedType == GsaFeedType.Full ? SourceStatusType.Refresh : SourceStatusType.Incremental);
                    } catch (Exception e) {
                        m_Logger.Error("Failed to update source status: " + e.Message);
                    }

                    //foreach (GsaFeedAcl acl in parser.ParseFeedAcl()) {
                    //    Console.WriteLine(acl.ToString());
                    //}

                    foreach (GsaFeedRecord record in parser.ParseFeedRecords())
                    {
                        ConsoleUtilities.WriteLine("{4}>>> {0}|{1}|{2}|{3}",
                                                   record.Action == GsaFeedRecordAction.Delete ? ConsoleColor.Yellow : ConsoleColor.Cyan,
                                                   record.Action.ToString().ToUpperInvariant(),
                                                   record.Url, record.MimeType ?? "None",
                                                   record.LastModified?.ToUniversalTime().ToString(CultureInfo.InvariantCulture) ?? "Unspecified",
                                                   DateTime.Now);
                        m_Logger.Info("Processing: " + record.Action.ToString().ToUpperInvariant() + " " + record.Url);

                        if ((record.Action == GsaFeedRecordAction.Add) || (record.Action == GsaFeedRecordAction.Unspecified))
                        {
                            try
                            {
                                //We need to push the acl virtual groups
                                PushGroupFromAcl(client.PermissionManager, s_Configuration.ProviderId, record.Acl);
                                orderingIdRef = client.DocumentManager.AddOrUpdateDocument(sourceId,
                                                                                           CreateDocumentFromRecord(record, header.FeedType == GsaFeedType.MetadataAndUrl),
                                                                                           null);
                                addedDocs++;
                                m_Logger.Info("Success: " + record.Action.ToString().ToUpperInvariant() + " " + record.Url);
                            }
                            catch (Exception e)
                            {
                                m_Logger.Error("Failed to add item: " + record.Url);
                                m_Logger.Error("Reason: " + e.Message);
                            }
                        }
                        else if (record.Action == GsaFeedRecordAction.Delete)
                        {
                            record.Url    = record.Url.Replace("&", "|");
                            orderingIdRef = client.DocumentManager.DeleteDocument(sourceId, record.Url, null);
                            deletedDocs++;
                        }
                        else
                        {
                            m_Logger.Error("No action was specified for the record " + record.Url);
                            ignoredDocs++;
                        }

                        if (firstOrderingIdRef == 0)
                        {
                            firstOrderingIdRef = orderingIdRef;
                        }

                        // Note that each record may contain attachments which also need to be pushed with the metadata of their parent
                        // record. This version supports an ATTACHMENTS tag to specify the path where the attachment files can be found.
                        if (record.Attachments != null)
                        {
                            // Create a duplicate of the parent record and update the body based on the file input
                            GsaFeedRecord attachRecord  = record;
                            string        recordBaseUrl = record.Url;

                            // Get a list of files that should be pushed as part of this record.
                            string dirPath = record.Attachments.Value;
                            m_Logger.Info("Processing attachment folder: " + dirPath);

                            //if (Directory.Exists(dirPath))
                            //{
                            try
                            {
                                string[] fileList = Directory.GetFiles(dirPath);
                                foreach (string filePath in fileList)
                                {
                                    m_Logger.Info("Processing: " + attachRecord.Action.ToString().ToUpperInvariant() + " " + filePath);
                                    string sourceFileName = Path.GetFileName(@filePath);
                                    string sourceFileExt  = Path.GetExtension(@filePath);
                                    string sourceFile     = @filePath;
                                    string targetFile     = Path.Combine(@s_Configuration.TempFolder, String.Format("{0}_{1}.{2}", sourceFileName, Guid.NewGuid(), sourceFileExt));
                                    int    buffLength     = 24 * 1024; //24KB
                                    byte[] buff           = new byte[buffLength];
                                    if ((attachRecord.Action == GsaFeedRecordAction.Delete))
                                    {
                                        attachRecord.Url = recordBaseUrl + "|" + sourceFileName;
                                        attachRecord.Url = attachRecord.Url.Replace("&", "|");
                                        orderingIdRef    = client.DocumentManager.DeleteDocument(sourceId, attachRecord.Url, null);
                                        deletedDocs++;
                                    }
                                    else
                                    {
                                        try
                                        {
                                            using (FileStream sourceStream = File.OpenRead(sourceFile))
                                            {
                                                using (FileStream targetStream = File.OpenWrite(targetFile))
                                                {
                                                    using (ZlibStream zipStream = new ZlibStream(targetStream, Ionic.Zlib.CompressionMode.Compress))
                                                    {
                                                        int offset  = 0;
                                                        int count   = buffLength;
                                                        int numRead = 0;

                                                        do
                                                        {
                                                            numRead = sourceStream.Read(buff, offset, count);
                                                            zipStream.Write(buff, 0, numRead);
                                                        }while (numRead == buffLength);
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            m_Logger.Error("Failed to process attachment: " + sourceFile + ", " + e.Message);
                                            m_Logger.Error("Trace: " + e.StackTrace);
                                            // Skip to the next attachment
                                            continue;
                                        }

                                        byte[] fileBytes = File.ReadAllBytes(@targetFile);
                                        attachRecord.Content.Value    = Convert.ToBase64String(fileBytes);
                                        attachRecord.Content.Encoding = GsaFeedContentEncoding.Base64Compressed;

                                        if ((attachRecord.Action == GsaFeedRecordAction.Add))
                                        {
                                            // Update the record url so it doesn't overwrite the parent, but leave the displayUrl as is
                                            attachRecord.Url = recordBaseUrl + "|" + sourceFileName;

                                            //We need to push the acl virtual groups
                                            PushGroupFromAcl(client.PermissionManager, s_Configuration.ProviderId, attachRecord.Acl);

                                            int parentIdx = attachRecord.Metadata.Values.FindIndex(item => item.Name == "uid");
                                            if (parentIdx >= 0)
                                            {
                                                try
                                                {
                                                    string parentId = attachRecord.Metadata.Values[parentIdx].Content;

                                                    client.DocumentManager.AddOrUpdateDocument(sourceId,
                                                                                               CreateDocumentFromRecord(attachRecord, header.FeedType == GsaFeedType.MetadataAndUrl, parentId, sourceFileExt),
                                                                                               null);
                                                    addedDocs++;
                                                    m_Logger.Info("Success: " + attachRecord.Action.ToString().ToUpperInvariant() + " " + filePath);
                                                }
                                                catch (Exception e)
                                                {
                                                    m_Logger.Error("Failed to add item: " + recordBaseUrl);
                                                    m_Logger.Error("Reason: " + e.Message);
                                                }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    m_Logger.Warning("Metadata field \"uid\" missing in record. Attachment will not be bound to the parent.");
                                                    client.DocumentManager.AddOrUpdateDocument(sourceId,
                                                                                               CreateDocumentFromRecord(attachRecord, header.FeedType == GsaFeedType.MetadataAndUrl),
                                                                                               null);
                                                    addedDocs++;
                                                    m_Logger.Info("Success: " + attachRecord.Action.ToString().ToUpperInvariant() + " " + attachRecord.Url);
                                                }
                                                catch (Exception e)
                                                {
                                                    m_Logger.Error("Failed to add item: " + recordBaseUrl);
                                                    m_Logger.Error("Reason: " + e.Message);
                                                }
                                            }
                                        }
                                    }
                                    // Remove this file from the temp space
                                    File.Delete(filePath);
                                }

                                // Remove this directory from the temp space
                                if (Directory.GetFiles(dirPath).Length > 0)
                                {
                                    m_Logger.Error("Attachment folder is not empty: " + dirPath);
                                }
                                else
                                {
                                    Directory.Delete(dirPath);
                                }
                            }
                            catch (Exception e)
                            {
                                m_Logger.Error("Failed to read attachment: " + dirPath + ", " + e.Message);
                                m_Logger.Error("Trace: " + e.StackTrace);
                            }
                            //} else {
                            //    m_Logger.Warning("Attachment folder does not exist: " + dirPath);
                            //}
                        }
                    }

                    if (header.FeedType == GsaFeedType.Full)
                    {
                        m_Logger.Info("Full feed detected - Deleting old documents. Reference ordering Id: " + firstOrderingIdRef);
                        client.DocumentManager.DeleteDocumentsOlderThan(sourceId, firstOrderingIdRef, 5);
                    }

                    try
                    {
                        client.ActivityManager.UpdateSourceStatus(sourceId, SourceStatusType.Idle);
                    }
                    catch (Exception e)
                    {
                    }

                    m_Logger.Info("The feed was processed.");
                    m_Logger.Info(" ");
                    m_Logger.Info("Statistics:");
                    m_Logger.Info("> Added documents: " + addedDocs);
                    m_Logger.Info("> Deleted documents: " + deletedDocs);
                    m_Logger.Info("> Ignored documents: " + ignoredDocs);
                    m_Logger.Info(" ");

                    // The local XML files are no longer needed
                    var files = new DirectoryInfo(s_Configuration.TempFolder).GetFiles("*.*");
                    foreach (var file in files)
                    {
                        if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(10))
                        {
                            File.Delete(file.FullName);
                        }
                    }
                }
            }
            else
            {
                if (p_HttpRequest == null)
                {
                    m_Logger.Error("No HTTP request to process.");
                }
                else
                {
                    m_Logger.Error("Invalid received request: " + p_HttpRequest.HttpMethod + " - " + p_HttpRequest.Url);
                }
            }
        }
 public ECSClusterCommand(IAWSResourceQueryer awsResourceQueryer, OrchestratorSession session, ConsoleUtilities consoleUtilities)
 {
     _awsResourceQueryer = awsResourceQueryer;
     _session            = session;
     _consoleUtilities   = consoleUtilities;
 }
Example #8
0
        /// <summary>
        /// Get configured modules from the module manager
        /// </summary>
        /// <param name="gameStats">GameStats module will be returned in this variable</param>
        /// <param name="cdKeyValidator">CD Key Validator module will be returned in this variable</param>
        /// <returns>True if all modules were loaded correctly</returns>
        private static bool LoadConfiguredModules(out IGameStatsLog gameStats, out ICDKeyValidator cdKeyValidator)
        {
            Console.WriteLine("Initialising log writer module...");
            logWriter = ModuleManager.GetModule <ILogWriter>();

            ConsoleColor oldColour = Console.ForegroundColor;

            // Warn if the CD key validator module was not loaded
            if (logWriter == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Configuration error: the specified log writer module was not loaded");
                Console.ForegroundColor = oldColour;

                MasterServer.Log("Configuration error: the specified log writer module was not loaded");

                if (!ConsoleUtilities.InConsoleSession())
                {
                    WinForms.MessageBox.Show("Configuration error: the specified log writer module was not loaded", "Configuration error", WinForms.MessageBoxButtons.OK);
                }
            }

            Console.WriteLine("Initialising GameStats module...");
            gameStats = ModuleManager.GetModule <IGameStatsLog>();

            // Warn if the GameStats module was not loaded
            if (gameStats == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Configuration error: the specified gamestats module was not loaded");
                Console.ForegroundColor = oldColour;

                MasterServer.Log("Configuration error: the specified gamestats module was not loaded");

                if (!ConsoleUtilities.InConsoleSession())
                {
                    WinForms.MessageBox.Show("Configuration error: the specified gamestats module was not loaded", "Configuration error", WinForms.MessageBoxButtons.OK);
                }
            }

            Console.WriteLine("Initialising CD key validator module...");
            cdKeyValidator = ModuleManager.GetModule <ICDKeyValidator>();

            // Can't continue without a CD key validator module
            if (cdKeyValidator == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Configuration error: the specified CD key validator module was not loaded");
                Console.WriteLine("Critical. Master server shutting down");
                Console.ForegroundColor = oldColour;

                if (!ConsoleUtilities.InConsoleSession())
                {
                    WinForms.MessageBox.Show("Configuration error: the specified CD key validator module was not loaded", "Critical error", WinForms.MessageBoxButtons.OK);
                }

                ReleaseModules();
                return(false);
            }

            Console.WriteLine();

            return(true);
        }
 public DockerBuildArgsCommand(ConsoleUtilities consoleUtilities)
 {
     _consoleUtilities = consoleUtilities;
 }
Example #10
0
 public Task StartApp()
 {
     ConsoleUtilities.ShowTitle(_Title);
     Configure();
     return(OrganizeAsync());
 }
        public static void ManageClient(object service)
        {
            IMessagingClient client = (IMessagingClient)service;

            while (true)
            {
                try
                {
                    if (Program.ServerState == 0)
                    {
                        client.SendShutdown("The server is shutting down.");
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                    CommandParameterPair message = client.RecieveMessage();
                    if (message == null)
                    {
                        Program.Disconnect(ThreadType.ClientThread, client.UserName);
                        return;
                    }
                    var parameters = new StringBuilder();
                    foreach (string param in message.Parameters)
                    {
                        parameters.Append(param + " ");
                    }
                    ConsoleUtilities.PrintCommand("Command {0} was sent from the user {1} with parameters '{2}'", message.Command,
                                                  client.UserName,
                                                  parameters);
                    ClientCommand command;
                    if (Program.ClientCommands.TryGetValue(message.Command, out command))
                    {
                        CommandParameterPair classic = command(client.UserName, message.Parameters);
                        if (classic == null)
                        {
                            continue;
                        }
                        client.SendCommand(classic);
                    }
                    else
                    {
                        client.SendInvalid(String.Format("Unknown command: {0}", message.Command));
                    }
                    if (Program.ServerState == 0)
                    {
                        client.SendShutdown("The server is shutting down.");
                        return;
                    }
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch (ThreadInterruptedException)
                {
                }
                catch (ObjectDisposedException e)
                {
                    ConsoleUtilities.PrintWarning("User {0} has disconnected. Data: {1}", client.Client.UserName, e.Message);
                    Program.Disconnect(ThreadType.ClientThread, client.UserName);
                    return;
                }
                catch (IOException e)
                {
                    ConsoleUtilities.PrintWarning("User {0} has disconnected. Data: {1}", client.Client.UserName, e.Message);
                    Program.Disconnect(ThreadType.ClientThread, client.UserName);
                    return;
                }
                catch (SocketException e)
                {
                    ConsoleUtilities.PrintWarning("User {0} has disconnected. Data: {1}", client.Client.UserName, e.Message);
                    Program.Disconnect(ThreadType.ClientThread, client.UserName);
                    return;
                }
                catch (NetworkInformationException e)
                {
                    ConsoleUtilities.PrintWarning("A user has disconnected {0}", e.Message);
                    client.Disconnect("An unknown error has occurred.");
                    Program.Disconnect(ThreadType.ClientThread, client.Client.UserName);
                    return;
                }
            }
        }
Example #12
0
        /// <summary>
        /// Populates the <c>_ComicsNewPaths</c> dictionary with all the comics that need to be moved.
        /// It does so in a way that all comics that need to be moved appear just once in the entire dictionary,
        /// this way we can move all comics asynchronously.
        /// </summary>
        void PopulateDictionary()
        {
            ConsoleUtilities.InfoMessage("Scanning directories...");
            try
            {
                Environment.CurrentDirectory = Path.GetPathRoot(Environment.SystemDirectory);
                if (_DoGroups)
                {
                    GetPreviousToDictionary();
                }

                foreach (var subDirectoryPath in Directory.EnumerateDirectories(_MainPath))
                {
                    string subDirectoryName = Path.GetFileName(subDirectoryPath);

                    //If it isn't a directory with files already organized, organize it
                    if (_AlreadyOrganizedRegex.IsMatch(subDirectoryName))
                    {
                        continue;
                    }

                    for (int i = 0; i < _Regices.Count(); i++)
                    {
                        Regex regex = _Regices[i];
                        if (!regex.IsMatch(subDirectoryName))
                        {
                            continue;
                        }

                        int[] idsGroup = regex.GetGroupNumbers();
                        (string groupName, string artistName, string comicName) =
                            GetComicInfo(idsGroup, regex.Match(subDirectoryName).Groups);

                        (string groupPath, string artistPath) = CreatePaths(groupName, artistName);

                        string artistFinalPath = Path.Combine(artistPath, comicName);
                        string groupFinalPath  = Path.Combine(groupPath, comicName);

                        InitializeKeyIfNotExists(artistPath);
                        _ComicsNewPaths[artistPath].Add(new ComicInfo(subDirectoryPath, artistFinalPath, artistName));

                        if (!_DoGroups || Directory.Exists(artistPath))
                        {
                            break;
                        }


                        InitializeKeyIfNotExists(groupPath);
                        _ComicsNewPaths[groupPath].Add(new ComicInfo(subDirectoryPath, groupFinalPath, artistName));

                        if (_ComicsNewPaths[artistPath].Count < _MinNumberOfComics)
                        {
                            break;
                        }

                        //Removes all references to previous comics that belonged to the same artist and group,
                        //which makes it safe to move all comics asynchonously
                        if (_ComicsNewPaths.TryGetValue(groupPath, out List <ComicInfo> listOfPaths))
                        {
                            listOfPaths.RemoveAll(info => info.ArtistName.Equals(artistName));
                        }

                        break;
                    }
                }
                ConsoleUtilities.InfoMessage("Finished!");
            }
            catch (Exception e)
            {
                ConsoleUtilities.ErrorMessage("An error ocurred...");
                Console.Error.WriteLine(e.Message);
            }
        }
 public DockerExecutionDirectoryCommand(ConsoleUtilities consoleUtilities)
 {
     _consoleUtilities = consoleUtilities;
 }
Example #14
0
        private static PushDocument CreateDocumentFromRecord(GsaFeedRecord p_Record,
                                                             bool p_DownloadContent, string p_ParentId, string p_fileExt)
        {
            IDictionary <string, JToken> metadata = p_Record.ConvertMetadata();

            if (p_Record.DisplayUrl == null)
            {
                p_Record.DisplayUrl = p_Record.Url;
            }

            p_Record.Url = p_Record.Url.Replace("&", "|");

            metadata.Add("clickableuri", p_Record.DisplayUrl);
            metadata.Add(nameof(p_Record.DisplayUrl), p_Record.DisplayUrl);
            metadata.Add(nameof(p_Record.Lock), p_Record.Lock);
            metadata.Add(nameof(p_Record.MimeType), p_Record.MimeType);
            metadata.Add(nameof(p_Record.PageRank), p_Record.PageRank);
            metadata.Add(nameof(p_Record.Scoring), p_Record.Scoring);
            metadata.Add(nameof(p_Record.Url), p_Record.Url);
            metadata.Add(nameof(p_Record.AuthMethod), p_Record.AuthMethod.ToString());
            metadata.Add(nameof(p_Record.CrawlImmediately), p_Record.CrawlImmediately);
            metadata.Add(nameof(p_Record.CrawlOnce), p_Record.CrawlOnce);

            PushDocument document = new PushDocument(p_Record.Url)
            {
                ModifiedDate  = p_Record.LastModified ?? DateTime.MinValue,
                Metadata      = metadata,
                ParentId      = p_ParentId,
                FileExtension = p_fileExt
            };

            if (p_Record.Acl != null)
            {
                DocumentPermissionSet currentDocSet = new DocumentPermissionSet();

                PermissionIdentity denyGroup  = new PermissionIdentity(p_Record.Url + DISALLOW_GROUP, PermissionIdentityType.VirtualGroup);
                PermissionIdentity allowGroup = new PermissionIdentity(p_Record.Url + ALLOW_GROUP, PermissionIdentityType.VirtualGroup);
                currentDocSet.DeniedPermissions.Add(denyGroup);
                currentDocSet.AllowedPermissions.Add(allowGroup);
                DocumentPermissionLevel currentDocLevel = new DocumentPermissionLevel();
                currentDocLevel.PermissionSets.Add(currentDocSet);


                if (p_Record.Acl.ParentAcl != null)
                {
                    GsaFeedAcl currentAcl = p_Record.Acl;
                    List <DocumentPermissionLevel> allLevels = new List <DocumentPermissionLevel>();
                    allLevels.Add(currentDocLevel);
                    int currentLevelIndex = 0;

                    while (currentAcl.ParentAcl != null)
                    {
                        GsaFeedAcl            curParentAcl     = currentAcl.ParentAcl;
                        DocumentPermissionSet curParentDocSet  = new DocumentPermissionSet();
                        PermissionIdentity    parentDenyGroup  = new PermissionIdentity(curParentAcl.DocumentUrl + DISALLOW_GROUP, PermissionIdentityType.VirtualGroup);
                        PermissionIdentity    parentAllowGroup = new PermissionIdentity(curParentAcl.DocumentUrl + ALLOW_GROUP, PermissionIdentityType.VirtualGroup);


                        //We sill always need the parents in a different set
                        curParentDocSet.DeniedPermissions.Add(parentDenyGroup);
                        curParentDocSet.AllowedPermissions.Add(parentAllowGroup);
                        switch (curParentAcl.InheritanceType)
                        {
                        case GsaFeedAclInheritance.BothPermit:
                            //The parent and the document are in two different sets

                            allLevels.ElementAt(currentLevelIndex).PermissionSets.Add(curParentDocSet);
                            break;

                        case GsaFeedAclInheritance.ChildOverrides:
                            //The parent is in a lower level than the current document
                            DocumentPermissionLevel parentLowerDocLevel = new DocumentPermissionLevel();
                            parentLowerDocLevel.PermissionSets.Add(curParentDocSet);
                            //We are adding our self after the children
                            currentLevelIndex++;
                            allLevels.Insert(currentLevelIndex, parentLowerDocLevel);
                            break;

                        case GsaFeedAclInheritance.ParentOverrides:
                            //The parent is in a higher level than the current document
                            //on doit ajouter avant l'enfant
                            DocumentPermissionLevel parentHigherDocLevel = new DocumentPermissionLevel();
                            parentHigherDocLevel.PermissionSets.Add(curParentDocSet);
                            allLevels.Insert(currentLevelIndex, parentHigherDocLevel);
                            break;

                        case GsaFeedAclInheritance.LeafNode:
                            //The document is not suppose to have inheritance from a leaf node
                            ConsoleUtilities.WriteLine("> Warning: You are trying to have inheritance on a LeafNode. Document in error: {0}", ConsoleColor.Yellow, p_Record.Url);
                            curParentAcl.ParentAcl = null;
                            break;
                        }
                        currentAcl = curParentAcl;
                    }
                    //Now we push the permissions
                    foreach (DocumentPermissionLevel documentPermissionLevel in allLevels)
                    {
                        document.Permissions.Add(documentPermissionLevel);
                    }
                }
                else
                {
                    //We might need to add the parent level before, so we will not default this action.
                    document.Permissions.Add(currentDocLevel);
                }
            }

            if (p_DownloadContent)
            {
                string content = s_HttpDownloader.Download(p_Record.Url);

                PushDocumentHelper.SetCompressedEncodedContent(document, Compression.GetCompressedBinaryData(content));
            }
            else
            {
                if (p_Record.Content.Encoding == GsaFeedContentEncoding.Base64Compressed)
                {
                    PushDocumentHelper.SetCompressedEncodedContent(document, p_Record.Content.Value.Trim(Convert.ToChar("\n")));
                }
                else
                {
                    PushDocumentHelper.SetContent(document, p_Record.Content.GetDecodedValue());
                }
            }

            return(document);
        }
Example #15
0
        private static void ProcessConsoleData(Push_Stdio_StdOut std)
        {
            if (std.WindowsX != LastBuffer.WindowsX || std.WindowsY != LastBuffer.WindowsY)
            {
                ConsoleUtilities.CONSOLE_SCREEN_BUFFER_INFO_EX ex = new ConsoleUtilities.CONSOLE_SCREEN_BUFFER_INFO_EX();
                ex.cbSize = 96;
                res       = ConsoleUtilities.GetConsoleScreenBufferInfoEx(StdOutHandle, ref ex);
                ex.dwMaximumWindowSize.X = ex.dwSize.X = (short)std.WindowsX;
                ex.dwMaximumWindowSize.Y = ex.dwSize.Y = (short)std.WindowsY;
                ex.srWindow.Top          = ex.srWindow.Left = 0;
                ex.srWindow.Right        = (short)std.WindowsX;
                ex.srWindow.Bottom       = (short)std.WindowsY;
                res = ConsoleUtilities.SetConsoleScreenBufferInfoEx(StdOutHandle, ref ex);
            }

            if (std.CursorX != LastBuffer.CursorX || std.CursorY != LastBuffer.CursorY)
            {
                ConsoleUtilities.COORD c = new ConsoleUtilities.COORD();
                c.X = (short)std.CursorX;
                c.Y = (short)std.CursorY;
                res = ConsoleUtilities.SetConsoleCursorPosition(StdOutHandle, c);
            }

            if (std.Data == null)
            {
                std.Data = new ConsoleUtilities.CHAR_INFO2[1];
            }
            if (LastBuffer.Data == null)
            {
                LastBuffer.Data = new ConsoleUtilities.CHAR_INFO2[1];
            }

            bool DataModified = false;

            if (std.Data.Length != LastBuffer.Data.Length)
            {
                DataModified = true;
            }
            if (DataModified == false)
            {
                for (int i = 0; i < std.Data.Length; i++)
                {
                    if (LastBuffer.Data[i].b[0] != std.Data[i].b[0] ||
                        LastBuffer.Data[i].b[1] != std.Data[i].b[1] ||
                        LastBuffer.Data[i].b[2] != std.Data[i].b[2] ||
                        LastBuffer.Data[i].b[3] != std.Data[i].b[3])
                    {
                        DataModified = true;
                        break;
                    }
                }
            }

            if (DataModified == true)
            {
                ConsoleUtilities.COORD c = new ConsoleUtilities.COORD();
                c.X = (short)std.WindowsX;
                c.Y = (short)std.WindowsY;
                ConsoleUtilities.COORD p = new ConsoleUtilities.COORD();
                p.X = p.Y = 0;
                ConsoleUtilities.SMALL_RECT r = new ConsoleUtilities.SMALL_RECT();
                r.Left   = r.Top = 0;
                r.Right  = (short)std.WindowsX;
                r.Bottom = (short)std.WindowsY;
                res      = ConsoleUtilities.WriteConsoleOutput(StdOutHandle, std.Data, c, p, ref r);
            }

            LastBuffer = std;
        }
        public static void AcceptNewClients()
        {
            Console.WriteLine("Thread started");
            while (true)
            {
                try
                {
                    TcpClient tcpClient = Program.ServerSocket.AcceptTcpClient();
                    if (Program.ServerState == 0)
                    {
                        ConsoleUtilities.PrintCritical("Thread has been ended {0}", DateTime.UtcNow);
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                    NetworkStream clientStream = tcpClient.GetStream();
                    ConsoleUtilities.PrintCommand("Connection has been accepted from {0}", tcpClient.Client.RemoteEndPoint);

                    if (Program.AnonymousThreads.ContainsKey(tcpClient.Client.RemoteEndPoint.ToString()))
                    {
                        SocketUtilities.SendInvalid(clientStream, "Your network is already connected. Try again later.");
                        tcpClient.Close();
                        continue;
                    }

                    int messageLength = SocketUtilities.RecieveMessageLength(clientStream);
                    if (messageLength == -1)
                    {
                        ConsoleUtilities.PrintCommand("Connection has been closed for {0}", tcpClient.Client.RemoteEndPoint);
                        tcpClient.Close();
                        continue;
                    }
                    string stringmessage = SocketUtilities.RecieveMessage(clientStream, messageLength);
                    if (stringmessage == null)
                    {
                        tcpClient.Close();
                        continue;
                    }

                    CommandParameterPair message = MessageUtilites.DecodeMessage(stringmessage);
                    if (message == null)
                    {
                        SocketUtilities.SendInvalid(clientStream, "The message was formatted incorrectly.");
                        tcpClient.Close();
                        continue;
                    }

                    if (!Program.InitializeCommands.ContainsKey(message.Command))
                    {
                        SocketUtilities.SendInvalid(clientStream, "The command was not found");
                        tcpClient.Close();
                        continue;
                    }

                    InitializeCommand execute;
                    if (Program.InitializeCommands.TryGetValue(message.Command, out execute))
                    {
                        execute(tcpClient, message.Parameters);
                        continue;
                    }
                    SocketUtilities.SendError(clientStream, "Unable to find command (Concurrency Issues)");
                    if (Program.ServerState == 0)
                    {
                        Console.WriteLine("Thread has been ended");
                        return;
                    }
                    if (Program.ServerState == 2)
                    {
                        Thread.Sleep(Timeout.Infinite);
                    }
                }
                catch (ThreadAbortException e)
                {
                    Console.WriteLine("Thread has been stopped {0}", e.Data.Values);
                    return;
                }
                catch (InvalidOperationException e)
                {
                    ConsoleUtilities.PrintCritical("Accept thread has been terminated {0}", e.Message);
                    return;
                }
                catch (ThreadInterruptedException)
                {
                    Console.WriteLine("Resuming accepting threads");
                }
                catch (IOException e)
                {
                    ConsoleUtilities.PrintWarning("Impropert disconnect. {1}", e.Message);
                }
                catch (SocketException e)
                {
                    ConsoleUtilities.PrintWarning("Improper disconnect. Data: {0}", e.Data);
                }
            }
        }
Example #17
0
        static void RunRemoteApp(string Server, string MID, string Username, string Password, string Program, string Args)
        {
            ConsoleColor c = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Yellow;

#if DEBUG
            Console.WriteLine("MachineID:      " + MID);
#endif

            if (Password == "*")
            {
                IntPtr      hwnd = ConsoleUtilities.GetConsoleWindow();
                frmPassword pwd  = new frmPassword(Server, Username);
                if (pwd.ShowDialog(new WindowWrapper(hwnd)) != System.Windows.Forms.DialogResult.OK)
                {
                    Console.ForegroundColor = c;
                    return;
                }
                Password = pwd.Password;
            }

            Console.WriteLine("Connecting to server: " + Server);

            net = new Network();
            if (net.Connect(Server) == false)
            {
                Console.ForegroundColor = c;
                net = null;
                return;
            }

            if (net.Login(Username, Password) == false)
            {
                if (net.LoginError == null)
                {
                    Console.WriteLine("Login failed: ???");
                }
                else
                {
                    Console.WriteLine("Login failed: " + net.LoginError.Error);
                }
                Console.ForegroundColor = c;
                net = null;
                return;
            }

            if (LoopPing == false)
            {
                if (net.PushPing(MID) == false)
                {
                    Console.WriteLine("Remote machine does not respond to \"Ping\"");
                    Console.ForegroundColor = c;
                    net.CloseConnection();
                    net = null;
                    return;
                }
            }
            else
            {
                Console.CancelKeyPress += Console_CancelKeyPress_BreakPing;
                do
                {
                    if (net.PushPing(MID) == false)
                    {
                        Console.WriteLine("Remote machine does not respond to \"Ping\" - Retrying");
                        Thread.Sleep(2000);
                    }
                    else
                    {
                        break;
                    }
                } while (LoopPing == true);
                Console.CancelKeyPress -= Console_CancelKeyPress_BreakPing;
                if (LoopPing == false)
                {
                    Console.ForegroundColor = c;
                    net.CloseConnection();
                    net = null;
                    return;
                }
            }

            PushRunTask rt = new PushRunTask();
            rt.Executable = Program;
            rt.Args       = Args;
            rt.Option     = PushRunTaskOption.SystemUserConsoleRedir;

            PushRunTaskResult rtres = net.PushRunFile(MID, rt);
            if (rtres == null)
            {
                Console.WriteLine("Cannot start application: ???");
                Console.ForegroundColor = c;
                net.CloseConnection();
                net = null;
                return;
            }
            if (rtres.Result != 0)
            {
                string errorMessage = new Win32Exception((int)(rtres.Result)).Message;
                Console.WriteLine("Cannot start application: 0x" + rtres.Result.ToString("X") + " " + errorMessage);
                Console.ForegroundColor = c;
                net.CloseConnection();
                net = null;
                return;
            }

            StdIOSession = rtres.SessionID;
            MachineID    = MID;

#if DEBUG
            Console.WriteLine("SessionID:      " + net.Session);
            Console.WriteLine("STDIOSessionID: " + StdIOSession);
#endif

            Console.WriteLine("Connected.");
            Console.ForegroundColor = c;
            Thread.Sleep(1000);
        }
 public DotnetPublishSelfContainedBuildCommand(ConsoleUtilities consoleUtilities)
 {
     _consoleUtilities = consoleUtilities;
 }