Пример #1
0
        ///<Summary>
        ///Fetches Alerts based on the parameters passed.
        ///If no parameters are specified returns all the Alerts.
        /// </Summary>
        ///<param name="name">
        ///The name of the Alert
        ///</param>
        ///<param name="severity">
        ///The Severity of the Alert
        ///</param>
        ///<param name="category">
        ///The Category of the Alert
        ///</param>
        ///<param name="number">
        ///The number of alerts to be fetched
        ///</param>
        public static List <Alert> GetAlert(string name = "", string severity = "", string category = "", int?number = null)
        {
            LogUtility.LogInfoFunction("Entered GetAlert.");
            //For Loading the powershell scripts ( Main.ps1 ) in memory.
            LogUtility.LogInfoFunction("Calling BemcliHelper function LoadPowerShellScript(); ");
            PowerShell powershell = BemcliHelper.LoadPowerShellScript();

            //Calling the powershell function GetAlerts(Name,Severity,Category,Number) which is present in BEMCLIScripts\Alerts.psm1
            LogUtility.LogInfoFunction("Invoking PowerShell Command GetAlerts(Name,Severity,Category,Number) ");
            powershell.AddCommand("GetAlerts");
            powershell.AddParameter("Name", name);
            powershell.AddParameter("Severity", severity);
            powershell.AddParameter("Category", category);
            powershell.AddParameter("Number", number);
            powershell.AddCommand("Out-String");
            var results = powershell.Invoke <string>();

            //check if the results string is empty
            if (String.IsNullOrWhiteSpace(results[0]))
            {
                //If the string is empty, there were no records found. Threfore return null.
                LogUtility.LogInfoFunctionFinished();
                return(null);
            }
            //If records are found pass it to ConvertFromJson.
            string mediaServerName = MediaServerController.GetMediaSever();
            var    alertObjects    = ConvertFromJson(results[0]);

            foreach (Alert alert in alertObjects)
            {
                alert.MediaServerName = mediaServerName;
            }
            LogUtility.LogInfoFunctionFinished();
            return(alertObjects);
        }
Пример #2
0
        public static MediaServer GetMediaSeverData()
        {
            LogUtility.LogInfoFunction("Entered GetMediaServerData.");
            LogUtility.LogInfoFunction("Calling BemcliHelper function LoadPowerShellScript(); ");
            PowerShell powershell = BemcliHelper.LoadPowerShellScript();

            LogUtility.LogInfoFunction("Invoking the PowerShell command GetLocalMediaServer()");
            powershell.AddCommand("GetLocalMediaServer");
            powershell.AddCommand("Out-String");
            var results = powershell.Invoke <string>();

            //check if the results string is empty
            if (String.IsNullOrWhiteSpace(results[0]))
            {
                //If the string is empty, there were no records found. Threfore return an empty Alert List.
                LogUtility.LogInfoFunction("Media Server Data not fetched");
                LogUtility.LogInfoFunctionFinished();
                return(null);
            }

            //If records are found pass it to ConvertFromJson.
            MediaServer mediaServer = ConvertFromJson(results[0]);

            LogUtility.LogInfoFunctionFinished();
            mediaServer.LastUpdate = DateTime.UtcNow;
            return(mediaServer);
        }
Пример #3
0
        ///<summary>
        /// Calls SaveAlertData() to save the data to a file , database or any other storage media based on
        /// storageType
        ///</summary>
        ///<param name="storageType">
        ///Storage type like file, DocumentDB database instance etc.
        /// </param>
        public static void SaveAlertData(IStorageService storageType, string storageId)
        {
            LogUtility.LogInfoFunction("Entered SaveAlertData.");
            if (storageType.GetType() == typeof(FileDataController))
            {
                fetchEndTime = Convert.ToDateTime(UserSettingsHelper.FileGetAlertFetchEndTime(storageId));
                UserSettingsHelper.FileSetAlertFetchStartTime(storageId, fetchEndTime);
                currentTime = DateTime.Now;
                UserSettingsHelper.FileSetAlertFetchEndTime(storageId, currentTime);
            }
            else
            {
                fetchEndTime = Convert.ToDateTime(UserSettingsHelper.GetFetchEndTime(storageId));
                UserSettingsHelper.DocumetDBSetAlertFetchStartTime(storageId, fetchEndTime);
                currentTime = DateTime.Now;
                UserSettingsHelper.SetFetchEndTime(storageId, currentTime);
            }

            List <Alert> alertObjects = GetAlertByDate(fetchEndTime, currentTime);

            if (alertObjects != null)
            {
                storageType.SaveAlertData(alertObjects, storageId);
            }
            else
            {
                LogUtility.LogInfoFunction("No Alert records found.");
            }
            LogUtility.LogInfoFunctionFinished();
        }
Пример #4
0
        public static PowerShell LoadPowerShellScript()
        {
            try
            {
                LogUtility.LogInfoFunction("Entered LoadPowerShellScript.");
                PowerShell powershell = PowerShell.Create();

                powershell.AddScript(str, false);

                LogUtility.LogInfoFunction("Loading powershell scripts.");
                Collection <PSObject> obj = powershell.Invoke();

                powershell.Commands.Clear();

                LogUtility.LogInfoFunctionFinished();
                return(powershell);
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                LogUtility.LogInfoFunction("Error:" + e.Message + "Message:" + baseException.Message);
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
                return(null);
            }
        }
Пример #5
0
        /// <summary>
        /// Saves the Jobs into the DocumentDB Collection with Id: "JobCollection"
        /// </summary>
        /// <param name="jobObject">
        ///Contains the Job Data
        /// </param>
        /// <param name="documentDBName">
        /// The documentDB name to determine to which EndPointUrl the data is to be stored.
        /// </param>
        public async void SaveJobData(List <Job> jobObject, string documentDBName)
        {
            try
            {
                LogUtility.LogInfoFunction("Entered SaveJobData.");
                List <string> list = GetEndpointUrlAndAuthorizationKey(documentDBName);
                EndpointUrl      = list[0];
                AuthorizationKey = list[1];

                await DeleteJob(documentDBName);

                using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey))
                {
                    //To get or create the documentDB database and Job collection.
                    Init(databaseId, jobCollectionId);
                    var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, jobCollectionId);
                    LogUtility.LogInfoFunction("Pushing Jobs into DocumentDB.");
                    foreach (Job job in jobObject)
                    {
                        //Push job to JobCollection.
                        await client.CreateDocumentAsync(collectionLink, job);
                    }
                    LogUtility.LogInfoFunction("Jobs successfully stored in DocumentDB");
                }
                LogUtility.LogInfoFunctionFinished();
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                LogUtility.LogInfoFunction("Error:" + e.Message + "Message:" + baseException.Message);
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
            }
        }
Пример #6
0
        ///<summary>
        /// Calls SaveJobHistoryData() to save the data to a file , database or any other storage media based on
        /// StorageType
        ///</summary>
        ///<param name="storageType">
        ///Storage type like file, DocumentDB database instance etc.
        /// </param>
        public static void SaveJobHistoryData(IStorageService storageType, string storageId)
        {
            LogUtility.LogInfoFunction("Entered SaveJobHistoryData.");
            //check the storage type to get the specific data from UserSettings.xml file
            if (storageType.GetType() == typeof(FileDataController))
            {
                LogUtility.LogInfoFunction("The storage type is FileSystem.");
                fetchEndTime = Convert.ToDateTime(UserSettingsHelper.FileGetJobHistoryFetchEndTime(storageId));
                UserSettingsHelper.FileSetJobHistoryFetchStartTime(storageId, fetchEndTime);
                currentTime = DateTime.Now;
                UserSettingsHelper.FileSetJobHistoryFetchEndTime(storageId, currentTime);
            }
            else
            {
                LogUtility.LogInfoFunction("The storage type is DocumentDB.");
                fetchEndTime = Convert.ToDateTime(UserSettingsHelper.GetJobHistoryFetchEndTime(storageId));
                UserSettingsHelper.DocumentDBSetJobHistoryFetchStartTime(storageId, fetchEndTime);
                currentTime = DateTime.Now;
                UserSettingsHelper.SetJobHistoryFetchEndTime(storageId, currentTime);
            }

            //List<JobHistory> jobHistoryObjects = GetJobHistory();
            List <JobHistory> jobHistoryObjects = GetJobHistoryByDate(fetchEndTime, currentTime);

            if (jobHistoryObjects != null)
            {
                LogUtility.LogInfoFunction("Calling  storageType.SaveJobHistoryData(jobHistoryObjects, storageId);");
                storageType.SaveJobHistoryData(jobHistoryObjects, storageId);
            }
            else
            {
                LogUtility.LogInfoFunction("No JobHistory records found.");
            }
            LogUtility.LogInfoFunctionFinished();
        }
Пример #7
0
        /// <summary>
        /// Updates the configuration.xml
        /// </summary>
        /// <param name="endpointUrl"></param>
        /// <param name="authorizationKey"></param>
        public static void UpdateConfiguration(string endpointUrl, string authorizationKey)
        {
            try
            {
                LogUtility.LogInfoFunction("Entered UpdateConfiguration.");
                XmlDocument xmlDoc = new XmlDocument();
                string      path   = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
                //xmlDoc.Load(path + @"\Settings\Configuration.xml");
                xmlDoc.Load(@"Settings\Configuration.xml");
                var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("ns", "http://schemas.arcus.com/configuration");
                XmlNode documentDBCredentials = xmlDoc.SelectSingleNode("//ns:DataStores/ns:DocumentDB", nsmgr);

                LogUtility.LogInfoFunction("Updating the Endpoint Url and Authorization Key in Configuration.xml");
                documentDBCredentials.Attributes["EndPointUrl"].Value      = endpointUrl;
                documentDBCredentials.Attributes["AuthorizationKey"].Value = authorizationKey;

                //xmlDoc.Save(path + @"\Settings\Configuration.xml");
                xmlDoc.Save(@"Settings\Configuration.xml");

                LogUtility.LogInfoFunctionFinished();
            }
            catch (Exception)
            {
                LogUtility.LogInfoFunction("Configuration.xml is not updated.");
            }
        }
Пример #8
0
        /// <summary>
        /// Gets the database if exists or creates a new database with the given Id.
        /// </summary>
        /// <param name="databaseId">
        /// Id for the Database.
        /// </param>
        /// <returns>Database Instance.</returns>
        public static async Task <Database> GetOrCreateDatabase(string databaseId)
        {
            try
            {
                LogUtility.LogInfoFunction("Entered GetOrCreateDatabase.");

                // Check to verify a database with the id=ArcusRegistry does not exist
                Database database = client.CreateDatabaseQuery().
                                    Where(db => db.Id == databaseId).AsEnumerable().FirstOrDefault();

                // If the database does not exist, create a new database
                if (database == null)
                {
                    LogUtility.LogInfoFunction("Creating Database.");
                    database = await client.CreateDatabaseAsync(
                        new Database
                    {
                        Id = databaseId
                    });
                }
                LogUtility.LogInfoFunctionFinished();
                return(database);
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                LogUtility.LogInfoFunction("Error:" + e.Message + "Message:" + baseException.Message);
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
                return(null);
            }
        }
Пример #9
0
        /// <summary>
        /// Executes the stored procedure to delete Job Histories.
        /// </summary>
        /// <param name="documentDBName"></param>
        /// <returns></returns>
        public async Task Execute_spBulkDeleteJobHistories(string documentDBName)
        {
            LogUtility.LogInfoFunction("Entered Execute_spBulkDeleteJobHistories.");
            List <string> list = GetEndpointUrlAndAuthorizationKey(documentDBName);

            EndpointUrl      = list[0];
            AuthorizationKey = list[1];

            using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey))
            {
                //Change Indexing policy of JobHistoryCollection.
                DocumentCollection collection = client.CreateDocumentCollectionQuery("dbs/" + databaseId).
                                                Where(c => c.Id == jobHistoryCollectionId).AsEnumerable().FirstOrDefault();
                collection.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String)
                {
                    Precision = -1
                });
                await client.ReplaceDocumentCollectionAsync(collection);

                LogUtility.LogInfoFunction("Execute BulkDeleteJobHistories");
                DateTime now = DateTime.Now;
                //To get one month before Date
                DateTime date          = now.AddHours(-purgeDBInterval);
                var      thresholdDate = date.ToString("yyyy-MM-dd");

                // delete all documents that satisfy filter
                var sql = String.Format("Select * from JobHistoryCollection where JobHistoryCollection.EndTime<'{0}' and JobHistoryCollection.MediaServerName='{1}'", thresholdDate, currentMediaServer);

                var count = await Execute_spBulkDelete(client, sql, "spDeleteJobHistory", collection);

                LogUtility.LogInfoFunction(String.Format("Deleted documents; count: {0}", count));
                LogUtility.LogInfoFunctionFinished();
            }
        }
Пример #10
0
        ///<Summary>
        ///Fetches Alerts based on the FromTime and ToTime and the number of Alerts to be fetched.
        ///</Summary>
        public static List <Alert> GetAlertByDate(DateTime fromDate, DateTime toDate, int?number = null)
        {
            LogUtility.LogInfoFunction("Entered GetAlertByDate.");
            //For Loading the powershell scripts ( Main.ps1 )in memory.
            LogUtility.LogInfoFunction("Call to BemcliHelper.LoadPowerShellScript();");
            PowerShell powershell = BemcliHelper.LoadPowerShellScript();

            LogUtility.LogInfoFunction("Invoking PowerShell Command GetAlertsByDate");
            powershell.AddCommand("GetAlertsByDate");
            powershell.AddParameter("FromTime", fromDate);
            powershell.AddParameter("ToTime", toDate);
            powershell.AddParameter("Number", number);
            powershell.AddCommand("Out-String");
            var results = powershell.Invoke <string>();

            //check if the results string is empty
            if (String.IsNullOrWhiteSpace(results[0]))
            {
                LogUtility.LogInfoFunctionFinished();
                //If the string is empty, there were no records found. Threfore return null.
                return(null);
            }
            string mediaServerName = MediaServerController.GetMediaSever();
            //If records are found pass it to ConvertFromJson.
            var alertObjects = ConvertFromJson(results[0]);

            //To det the Media server name.
            foreach (Alert alert in alertObjects)
            {
                alert.MediaServerName = mediaServerName;
            }
            LogUtility.LogInfoFunctionFinished();
            return(alertObjects);
        }
Пример #11
0
        /// <summary>
        /// Saves the Media Server details into the DocumentDB Collection with Id: "MediaServerCollection"
        /// </summary>
        /// <param name="mediaServerObject"></param>
        /// <param name="documentDBName"></param>
        public async void SaveMediaServerData(MediaServer mediaServerObject, string documentDBName)
        {
            try
            {
                LogUtility.LogInfoFunction("Entered SaveMediaServerData.");
                List <string> list = GetEndpointUrlAndAuthorizationKey(documentDBName);
                EndpointUrl      = list[0];
                AuthorizationKey = list[1];

                DeleteMediaServer(documentDBName).Wait();

                using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey))
                {
                    //To get or create the documentDB database and MediaServer collection.
                    Init(databaseId, mediaServerCollectionId);
                    var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, mediaServerCollectionId);
                    LogUtility.LogInfoFunction("Pushing Job Histories into DocumentDB.");

                    //Push MediaServers to MediaServerCollection.
                    await client.CreateDocumentAsync(collectionLink, mediaServerObject);

                    LogUtility.LogInfoFunction("Media Server Data successfully stored in DocumentDB");
                }

                LogUtility.LogInfoFunctionFinished();
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                LogUtility.LogInfoFunction("Error:" + e.Message + "Message:" + baseException.Message);
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
            }
        }
Пример #12
0
        public async Task SaveJobHistory(List <JobHistory> jobHistoryObject, string documentDBName)
        {
            try
            {
                LogUtility.LogInfoFunction("Entered SaveJobHistory.");
                List <string> list = GetEndpointUrlAndAuthorizationKey(documentDBName);
                EndpointUrl      = list[0];
                AuthorizationKey = list[1];

                using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey))
                {
                    //To get or create the documentDB database and JobHistory collection.
                    Init(databaseId, jobHistoryCollectionId);
                    var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, jobHistoryCollectionId);
                    LogUtility.LogInfoFunction("Pushing Job Histories into DocumentDB.");
                    foreach (JobHistory jobHistory in jobHistoryObject)
                    {
                        //Push job to JobHistoryCollection.
                        await client.CreateDocumentAsync(collectionLink, jobHistory);
                    }
                    LogUtility.LogInfoFunction("Job Histories successfully stored in DocumentDB");
                }
                LogUtility.LogInfoFunction("Setting the Last Update time");
                UserSettingsHelper.SetJobHistoryLastUpdateTime(documentDBName, DateTime.Now);

                LogUtility.LogInfoFunctionFinished();
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                LogUtility.LogInfoFunction("Error:" + e.Message + "Message:" + baseException.Message);
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
            }
        }
Пример #13
0
 /// <summary>
 /// Calls the GetOrCreateDatabase() method and GetOrCreateCollection().
 /// </summary>
 /// <param name="databaseId">Database Id.</param>
 /// <param name="collectionId">Collection Id.</param>
 public static void Init(string databaseId, string collectionId)
 {
     LogUtility.LogInfoFunction("Entered Init.");
     GetOrCreateDatabase(databaseId).Wait();
     GetOrCreateCollection(databaseId, collectionId).Wait();
     LogUtility.LogInfoFunctionFinished();
 }
Пример #14
0
        /// <summary>
        /// Saves the Alerts into the DocumentDB Collection with Id: "AlertCollection"
        /// </summary>
        /// <param name="alertObject">
        /// Contains the Alert data.
        /// </param>
        /// <param name="documentDBName">
        /// The documentDB name to determine to which EndPointUrl the data is to be stored.
        /// </param>
        public void SaveAlertData(List <Alert> alertObject, string documentDBName)
        {
            try
            {
                LogUtility.LogInfoFunction("Entered SaveAlertData.");

                List <string> list = GetEndpointUrlAndAuthorizationKey(documentDBName);
                EndpointUrl      = list[0];
                AuthorizationKey = list[1];

                using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey))
                {
                    //To get or create the documentDB database and Alert collection.
                    Init(databaseId, alertCollectionId);
                    var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, alertCollectionId);
                    LogUtility.LogInfoFunction("Pushing Alerts into DocumentDB.");
                    foreach (Alert alert in alertObject)
                    {
                        //Push alert to AlertCollection.
                        client.CreateDocumentAsync(collectionLink, alert).Wait();
                    }
                    LogUtility.LogInfoFunction("Alerts successfully stored in DocumentDB");
                }
                LogUtility.LogInfoFunction("Setting the Last Update time");
                UserSettingsHelper.SetLastUpdateTime(documentDBName, DateTime.Now);
                LogUtility.LogInfoFunctionFinished();
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                LogUtility.LogInfoFunction("Error:" + e.Message + "Message:" + baseException.Message);
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
            }
        }
Пример #15
0
        /// <summary>
        /// Checks if the File system type and DocumentDB type is enabled
        /// and calls the respective handler methods.
        /// </summary>
        public static void Init()
        {
            try
            {
                LogUtility.CheckLogFileEnabled();

                //Get the file Systems that are enabled.
                IEnumerable <BEArcus.Agent.FileSystemType> fileSystems = Configuration.Instance.DataStores.FileSystem.
                                                                         Where(f => f.Enabled);
                LogUtility.LogInfoFunction("Storing data to enbled File Systems");
                IStorageService fileservice = new FileDataController();
                foreach (FileSystemType fileSystem in fileSystems)
                {
                    UserSettingsHelper.CreateFileSystemSettings(fileSystem.Name);
                    AlertController.SaveAlertData(fileservice, fileSystem.Name);
                    JobController.SaveJobData(fileservice, fileSystem.Name);
                    JobHistoryController.SaveJobHistoryData(fileservice, fileSystem.Name);
                    MediaServerController.SaveMediaServerData(fileservice, fileSystem.Name);
                }

                //Get the DocumentDB data store that are enabled.
                IEnumerable <BEArcus.Agent.DocumentDBType> documentDBStreams = Configuration.Instance.DataStores.DocumentDB.
                                                                               Where(d => d.Enabled);
                LogUtility.LogInfoFunction("Storing data to enbled DocumentDB accounts.");
                //IStorageService documentDBService = new DocumentDBDataController();
                foreach (DocumentDBType documentDB in documentDBStreams)
                {
                    UserSettingsHelper.CreateDocumentDBSettings(documentDB.Name);

                    //Decrypt the Authorization Key to check if it was encryped earlier
                    string decrypedAuthorizationKey = SecurityController.Decrypt(documentDB.AuthorizationKey);

                    //Decrypt method returns null if the Authorization key was not Encrypted earlier
                    if (string.IsNullOrEmpty(decrypedAuthorizationKey))
                    {
                        //Encrypt Authorization Key
                        string encryptedAuthorizationKey = SecurityController.Encrypt(documentDB.AuthorizationKey);
                        //Encrypt EndpointUrl
                        string encryptedEndpointUrl = SecurityController.Encrypt(documentDB.EndPointUrl);
                        //Save changes to Configuration.xml
                        SecurityController.UpdateConfiguration(encryptedEndpointUrl, encryptedAuthorizationKey);
                    }
                    IStorageService documentDBService = new DocumentDBDataController();
                    AlertController.SaveAlertData(documentDBService, documentDB.Name);
                    JobController.SaveJobData(documentDBService, documentDB.Name);
                    JobHistoryController.SaveJobHistoryData(documentDBService, documentDB.Name);
                    MediaServerController.SaveMediaServerData(documentDBService, documentDB.Name);
                    PurgeDataController.PurgeAlerts(documentDB.Name);
                    PurgeDataController.PurgeJobHistories(documentDB.Name);
                }
                LogUtility.LogInfoFunctionFinished();
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                LogUtility.LogInfoFunction("Error:" + e.Message + "Message:" + baseException.Message);
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
            }
        }
Пример #16
0
 /// <summary>
 /// Gets the DocumentDBType object for the provided documentDB Name.
 /// </summary>
 /// <param name="documentDBName">Unique Id for the documentDB.</param>
 /// <returns></returns>
 public DocumentDBType GetDocumentDBType(string documentDBName)
 {
     LogUtility.LogInfoFunction("Entered GetDocumentDBType.");
     LogUtility.LogInfoFunction("Getting DocumentDBType");
     LogUtility.LogInfoFunctionFinished();
     return(Configuration.Instance.DataStores.DocumentDB.
            Where(d => d.Name.Equals(documentDBName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault());
 }
Пример #17
0
 /// <summary>
 /// Gets the file system type object for the given file system name.
 /// </summary>
 /// <param name="fileSystemName">Id for the file system</param>
 /// <returns></returns>
 public FileSystemType GetFileSystemType(string fileSystemName)
 {
     LogUtility.LogInfoFunction("Entered GetFileSystemType.");
     LogUtility.LogInfoFunction("Getting FileSystemType");
     LogUtility.LogInfoFunctionFinished();
     return(Configuration.Instance.DataStores.FileSystem.
            Where(s => s.Name.Equals(fileSystemName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault());
 }
Пример #18
0
        public static MediaServer ConvertFromJson(string jsonString)
        {
            LogUtility.LogInfoFunction("Entered ConvertFromJson.");
            LogUtility.LogInfoFunction("Calling JsonHelper function  JsonHelper.JsonDeserialize<MediaServer>(jsonString); ");
            var mediaServerObject = JsonHelper.JsonDeserialize <MediaServer>(jsonString);

            LogUtility.LogInfoFunctionFinished();
            return(mediaServerObject);
        }
Пример #19
0
 ///<Summary>
 ///To display the Alerts on console
 ///</Summary>
 public static void ViewAlerts(List <Alert> alertObjects)
 {
     LogUtility.LogInfoFunction("Entered ViewAlerts.");
     foreach (Alert alertObject in alertObjects)
     {
         Console.WriteLine("\nNamg:\t {0} \n Id:\t {1} \n Datg:\t {2}\n\n",
                           alertObject.Name, alertObject.Id, alertObject.Date);
     }
     LogUtility.LogInfoFunctionFinished();
 }
Пример #20
0
        public void SaveMediaServerData(MediaServer mediaServerObject, string fileSystemName)
        {
            LogUtility.LogInfoFunction("Entered SaveMediaServerData.");
            string jsonstr      = JsonHelper.JsonSerializer <MediaServer>(mediaServerObject);
            string jsonFilePath = GetFileSystemType(fileSystemName).MediaServerPath;

            LogUtility.LogInfoFunction("MediaServer:Writing to Json file.");
            System.IO.File.WriteAllText(jsonFilePath, jsonstr);
            LogUtility.LogInfoFunction(string.Format("JobHistories in {0}.", jsonFilePath));
            LogUtility.LogInfoFunctionFinished();
        }
Пример #21
0
        ///<Summary>
        ///Saves the Alerts to a Json file.
        ///</Summary>
        public void SaveAlertData(List <Alert> alertObject, string fileSystemName)
        {
            LogUtility.LogInfoFunction("Entered SaveAlertData.");
            string jsonstr      = JsonHelper.JsonSerializer <List <Alert> >(alertObject);
            string jsonFilePath = GetFileSystemType(fileSystemName).AlertPath;

            LogUtility.LogInfoFunction("Alert:Writing to Json file.");
            System.IO.File.WriteAllText(jsonFilePath, jsonstr);
            UserSettingsHelper.FileSetAlertLastUpdateTime(fileSystemName, DateTime.Now);
            LogUtility.LogInfoFunction(string.Format("Alerts in {0}.", jsonFilePath));
            LogUtility.LogInfoFunctionFinished();
        }
Пример #22
0
        ///<Summary>
        ///Saves JobHistory to a Json file.
        ///</Summary>
        public void SaveJobHistoryData(List <JobHistory> jobHistoryObject, string fileSystemName)
        {
            LogUtility.LogInfoFunction("Entered SaveJobHistoryData.");
            string jsonstr      = JsonHelper.JsonSerializer <List <JobHistory> >(jobHistoryObject);
            string jsonFilePath = GetFileSystemType(fileSystemName).JobHistoryPath;

            LogUtility.LogInfoFunction("JobHistory:Writing to Json file.");
            System.IO.File.WriteAllText(jsonFilePath, jsonstr);
            UserSettingsHelper.FileSetJobHistoryLastUpdateTime(fileSystemName, DateTime.Now);

            LogUtility.LogInfoFunction(string.Format("JobHistories in {0}.", jsonFilePath));
            LogUtility.LogInfoFunctionFinished();
        }
Пример #23
0
        ///<summary>
        ///Calls SaveJobData() to save the data to a file , database or any other storage media based on  persistanceStorageDependency
        ///</summary>
        ///<param name="storageType">
        ///Storage type like file, DocumentDB database instance etc.
        /// </param>
        public static void SaveJobData(IStorageService storageType, string storageId)
        {
            LogUtility.LogInfoFunction("Entered SaveJobData.");
            List <Job> jobObjects = GetJob();

            if (jobObjects != null)
            {
                storageType.SaveJobData(jobObjects, storageId);
            }
            else
            {
                LogUtility.LogInfoFunction("No records found.");
            }
            LogUtility.LogInfoFunctionFinished();
        }
Пример #24
0
        /// <summary>
        /// Delete the existing Media server records from MediaServerCollection.
        /// </summary>
        /// <param name="documentDBName"></param>
        /// <returns></returns>
        public async Task DeleteMediaServer(string documentDBName)
        {
            LogUtility.LogInfoFunction("Entered DeleteMediaServer.");

            List <string> list = GetEndpointUrlAndAuthorizationKey(documentDBName);

            EndpointUrl      = list[0];
            AuthorizationKey = list[1];

            using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey))
            {
                try
                {
                    Database db = client.CreateDatabaseQuery().
                                  Where(o => o.Id == databaseId).AsEnumerable().FirstOrDefault();
                    var coll = client.CreateDocumentCollectionQuery(db.CollectionsLink).Where(c => c.Id == mediaServerCollectionId).ToList().First();

                    var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, mediaServerCollectionId);

                    var docs = client.CreateDocumentQuery(
                        collectionLink,
                        new SqlQuerySpec()
                    {
                        QueryText  = "SELECT * FROM MediaServerCollection c WHERE c.Name = @MediaServerName",
                        Parameters = new SqlParameterCollection()
                        {
                            new SqlParameter("@MediaServerName", MediaServerController.GetMediaSever())
                        }
                    });

                    LogUtility.LogInfoFunction("Deleting Existing Media Server.");
                    foreach (Document doc in docs)
                    {
                        await client.DeleteDocumentAsync(doc.SelfLink);
                    }
                    LogUtility.LogInfoFunctionFinished();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    LogUtility.LogExceptionFunction(e);
                }
            }
            LogUtility.LogInfoFunctionFinished();
        }
Пример #25
0
        private async static Task <int> Execute_spBulkDelete(DocumentClient client, string sql, string sprocId, DocumentCollection collection)
        {
            LogUtility.LogInfoFunction("Entered Execute_spBulkDelete.");
            var continuationFlag  = true;
            var totalDeletedCount = 0;

            while (continuationFlag)
            {
                var result = await ExecuteStoredProcedure <spBulkDeleteResponse>(client, sprocId, collection, sql);

                continuationFlag = result.ContinuationFlag;
                var deletedCount = result.Count;
                totalDeletedCount += deletedCount;

                LogUtility.LogInfoFunction(String.Format("Deleted {0} documents ({1} total, more: {2})", deletedCount, totalDeletedCount, continuationFlag));
            }
            LogUtility.LogInfoFunctionFinished();
            return(totalDeletedCount);
        }
Пример #26
0
        /// <summary>
        /// Gets the decrypted Endpoint url and Authorization Key.
        /// </summary>
        /// <param name="documentDBName"></param>
        /// <returns></returns>
        public List <string> GetEndpointUrlAndAuthorizationKey(string documentDBName)
        {
            LogUtility.LogInfoFunction("Entered GetEndpointUrlAndAuthorizationKey.");
            List <string> list = new List <string>();
            string        encryptedEndpointUrl      = GetDocumentDBType(documentDBName).EndPointUrl;
            string        decryptedEndpointUrl      = SecurityController.Decrypt(encryptedEndpointUrl);
            string        encryptedAuthorizationKey = GetDocumentDBType(documentDBName).AuthorizationKey;
            string        decryptedAuthorizationKey = SecurityController.Decrypt(encryptedAuthorizationKey);

            if (string.IsNullOrEmpty(decryptedEndpointUrl))
            {
                list.Add(encryptedEndpointUrl);
                list.Add(encryptedAuthorizationKey);
                return(list);
            }
            list.Add(decryptedEndpointUrl);
            list.Add(decryptedAuthorizationKey);
            LogUtility.LogInfoFunctionFinished();
            return(list);
        }
Пример #27
0
        private async static Task <T> ExecuteStoredProcedure <T>(DocumentClient client, string sprocId, DocumentCollection collection, params dynamic[] sprocParams)
        {
            LogUtility.LogInfoFunction("Entered ExecuteStoredProcedure.");
            var query = new SqlQuerySpec
            {
                QueryText  = "SELECT * FROM c WHERE c.id = @id",
                Parameters = new SqlParameterCollection {
                    new SqlParameter {
                        Name = "@id", Value = sprocId
                    }
                }
            };


            StoredProcedure sproc = client
                                    .CreateStoredProcedureQuery(collection.StoredProceduresLink, query)
                                    .AsEnumerable()
                                    .First();

            while (true)
            {
                try
                {
                    var result = await client.ExecuteStoredProcedureAsync <T>(sproc.SelfLink, sprocParams);

                    LogUtility.LogInfoFunction(String.Format("Executed stored procedure: {0}", sprocId));
                    LogUtility.LogInfoFunctionFinished();
                    return(result);
                }
                catch (DocumentClientException ex)
                {
                    if ((int)ex.StatusCode == 429)
                    {
                        LogUtility.LogInfoFunction(String.Format("  ...retry in {0}", ex.RetryAfter));
                        Thread.Sleep(ex.RetryAfter);
                        continue;
                    }
                    Console.WriteLine(ex);
                }
            }
        }
Пример #28
0
        /// <summary>
        /// Encrypts the text using Current user.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Encrypt(string text)
        {
            try
            {
                LogUtility.LogInfoFunction("Entered Encrypt.");
                // first, convert the text to byte array
                byte[] originalText = Encoding.Unicode.GetBytes(text);

                // then use Protect() to encrypt your data
                byte[] encryptedText = ProtectedData.Protect(originalText, entropy, DataProtectionScope.CurrentUser);

                LogUtility.LogInfoFunctionFinished();
                //and return the encrypted message
                return(Convert.ToBase64String(encryptedText));
            }
            catch (Exception)
            {
                LogUtility.LogInfoFunction("Data was not Encrypted.");
                return(null);
            }
        }
Пример #29
0
        /// <summary>
        /// Creates stored procedure to delete Alerts.
        /// </summary>
        /// <param name="documentDBName"></param>
        /// <returns></returns>
        public async Task <StoredProcedure> CreateAlertStoredProcedure(string documentDBName)
        {
            LogUtility.LogInfoFunction("Entered CreateAlertStoredProcedure.");
            List <string> list = GetEndpointUrlAndAuthorizationKey(documentDBName);

            EndpointUrl      = list[0];
            AuthorizationKey = list[1];

            using (client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey))
            {
                // Get database
                //Database database = client.CreateDatabaseQuery().
                //                Where(db => db.Id == databaseId).AsEnumerable().FirstOrDefault();

                // Get collection (Alert)
                DocumentCollection collection = client.CreateDocumentCollectionQuery("dbs/" + databaseId).
                                                Where(c => c.Id == alertCollectionId).AsEnumerable().FirstOrDefault();

                //Check if the Stored Procedure exists.
                StoredProcedure storedProcedure = client.CreateStoredProcedureQuery(collection.SelfLink).Where(c => c.Id == "spDeleteAlert").AsEnumerable().FirstOrDefault();
                if (storedProcedure == null)
                {
                    // Create stored procedure
                    var sprocBody = File.ReadAllText(@".\Server\PurgeData.js");

                    var sprocDefinition = new StoredProcedure
                    {
                        Id   = "spDeleteAlert",
                        Body = sprocBody
                    };

                    StoredProcedure sproc = await client.CreateStoredProcedureAsync(collection.SelfLink, sprocDefinition);

                    return(sproc);
                }
                LogUtility.LogInfoFunctionFinished();
                return(storedProcedure);
            }
        }
Пример #30
0
        ///<Summary>
        ///Checks if the Json string contains an array or a single object and returns a List of Alert Object/s
        ///</Summary>
        public static List <Alert> ConvertFromJson(string jsonString)
        {
            LogUtility.LogInfoFunction("Entered ConvertFromJson.");
            //To check if the JsonString contains an array of objects / a single object.
            var token = JToken.Parse(jsonString);

            if (token is JArray)
            {
                LogUtility.LogInfoFunction("Calling JsonHelper function JsonDeserialize<List<Alert>>(JsonString); ");
                var alertObjects = JsonHelper.JsonDeserialize <List <Alert> >(jsonString);
                LogUtility.LogInfoFunctionFinished();
                return(alertObjects);
            }
            else
            {
                LogUtility.LogInfoFunction("Calling JsonHelper function JsonDeserialize<List<Alert>>(JsonString); ");
                var          alertObjects = JsonHelper.JsonDeserialize <Alert>(jsonString);
                List <Alert> result       = new List <Alert>();
                result.Add(alertObjects);
                LogUtility.LogInfoFunctionFinished();
                return(result);
            }
        }