public static bool PostToSiteimproveServer(TreeNode node, PushType pushType) { var pp = new PushParameters(); pp.url = GetFullUrl(node); // if it is a full site recrawl, get the root if (pushType == PushType.recrawl) { pp.url = GetSiteRoot(node.Site); } pp.token = GetAuthToken(node.Site); pp.type = pushType.ToString(); var paramaters = new System.Collections.Specialized.NameValueCollection(); // TODO: Map it automatically paramaters.Add("url", pp.url); paramaters.Add("token", pp.token); paramaters.Add("type", pp.type); // TODO: Error handling var response = CommonUtility.Post(ApiUrl + "/cms-recheck", paramaters); if (response == @"{ ""ordered"": true }") { return(true); } else { throw new Exception("Siteimprove Error: " + response); } }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public IFSContainer CreateDirectory(FSDirectory dir, PushType pushType, PushConfig pushConfig) { List <BH.oM.Adapters.File.IFSContainer> createdDirs = new List <oM.Adapters.File.IFSContainer>(); bool clearfile = pushType == PushType.DeleteThenCreate ? true : false; string dirFullPath = dir.IFullPath(); bool existed = System.IO.Directory.Exists(dirFullPath); bool directoryCreated = true; try { if (pushType == PushType.DeleteThenCreate) // Deletes and recreates the directory. { if (existed) { System.IO.Directory.Delete(dirFullPath, true); // Deletes the directory and all contents. To make things safer, a Warning is exposed in the Push before proceeding. } System.IO.Directory.CreateDirectory(dirFullPath); } else if (pushType == PushType.CreateOnly || pushType == PushType.CreateNonExisting || pushType == PushType.UpdateOrCreateOnly || pushType == PushType.UpdateOnly) { // Create only directories that didn't exist. if (pushType != PushType.UpdateOnly) { if (!existed) { System.IO.Directory.CreateDirectory(dirFullPath); } else { BH.Engine.Base.Compute.RecordNote($"Directory {dirFullPath} was not created as it existed already (Pushtype {pushType.ToString()} was specified)."); directoryCreated = false; } } if (dir.Content != null && dir.Content.Any()) { for (int i = 0; i < dir.Content.Count; i++) { ILocatableResource item = (dir.Content[i] as ILocatableResource).DeepClone(); if (item == null) { BH.Engine.Base.Compute.RecordWarning($"Cannot push Directory content {dir.Content[i].GetType().Name}."); } string itemFullPath = item.IFullPath(); if (string.IsNullOrWhiteSpace(itemFullPath) && !string.IsNullOrWhiteSpace(item.Name)) { itemFullPath = Path.Combine(dirFullPath, item.Name); // Default to Container Directory path. item.Location = Path.GetDirectoryName(itemFullPath); } if (item.Location == dirFullPath) { Create(item, pushType, pushConfig); } else { BH.Engine.Base.Compute.RecordWarning($"The content of the Directory {dirFullPath} can't be Pushed because the content Path {itemFullPath} does not match the container Directory path."); } } } } else { BH.Engine.Base.Compute.RecordWarning($"The specified Pushtype of {pushType.ToString()} is not supported for {nameof(BH.oM.Adapters.File.FSDirectory)} objects."); directoryCreated = false; } } catch (Exception e) { BH.Engine.Base.Compute.RecordError(e.Message); } if (directoryCreated || existed) { System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(dirFullPath); oM.Adapters.File.FSDirectory createdDir = dirInfo.ToFiling(); return(createdDir); } BH.Engine.Base.Compute.RecordError($"Could not create the Directory {dir.ToString()}."); return(null); }
///<summary>Only call this method from SendPushBackground() or SendPushAlert(). See summary of those methods for documentation. ///If runAsync==true then spawns a worker thread and makes the web call. This method is passive and returns void so no reason to wait for return.</summary> private static void SendPush(PushType pushType, bool isAlert, long mobileAppDeviceNum = 0, long clinicNum = 0, long userNum = 0, List <long> listPrimaryKeys = null, List <string> listTags = null, string alertTitle = null, string alertMessage = null, bool runAsync = true) { void execute() { eServiceCode eService = eServiceCode.EClipboard; switch (pushType) { case PushType.CI_CheckinPatient: case PushType.CI_AddSheet: case PushType.CI_RemoveSheet: case PushType.CI_GoToCheckin: case PushType.CI_NewEClipboardPrefs: case PushType.CI_IsAllowedChanged: case PushType.CI_TreatmentPlan: case PushType.CI_RemoveTreatmentPlan: eService = eServiceCode.EClipboard; break; case PushType.ODM_NewTextMessage: case PushType.ODM_LogoutODUser: eService = eServiceCode.MobileWeb; break; case PushType.None: default: throw new Exception("Unsupported PushType: " + pushType.ToString()); } PushNotificationPayload payload = new PushNotificationPayload { IsAlert = isAlert, AlertMessage = alertMessage ?? "", AlertTitle = alertTitle ?? "", UserNum = userNum, PushNotificationActionJSON = JsonConvert.SerializeObject(new PushNotificationAction() { TypeOfPush = pushType, ListPrimaryKeys = listPrimaryKeys ?? new List <long>(), ListTags = listTags ?? new List <string>() }, typeof(PushNotificationAction), new JsonSerializerSettings()) }; if (mobileAppDeviceNum > 0) //Send to one exact device. { MobileAppDevice mad = MobileAppDevices.GetOne(mobileAppDeviceNum); if (mad == null) { throw new Exception("MobileAppDeviceNum not found: " + mobileAppDeviceNum.ToString()); } payload.DeviceId = mad.UniqueID; payload.ClinicNum = mad.ClinicNum; } else { payload.ClinicNum = clinicNum; } //Validate that this clinic is signed up for eClipboard if the push is related to eClipboard if (eService == eServiceCode.EClipboard && !MobileAppDevices.IsClinicSignedUpForEClipboard(payload.ClinicNum)) { throw new Exception($"ClinicNum {payload.ClinicNum} is not signed up for eClipboard."); } //Validate that this clinic is signed up for MobileWeb if the push is related to ODMobile else if (eService == eServiceCode.MobileWeb && !MobileAppDevices.IsClinicSignedUpForMobileWeb(payload.ClinicNum)) { if (clinicNum > -1 || pushType != PushType.ODM_LogoutODUser) //Logout is allowed to be sent to non-specific clinicNum. All others are not. { throw new Exception($"ClinicNum {payload.ClinicNum} is not signed up for ODMobile."); } } string jsonPayload = JsonConvert.SerializeObject(payload, typeof(PushNotificationPayload), new JsonSerializerSettings()); string result = WebServiceMainHQProxy.GetWebServiceMainHQInstance().SendPushNotification(PayloadHelper.CreatePayload("", eService), jsonPayload); if (result.ToLower() != "success") { throw new Exception(result); } } ODThread th = new ODThread(new ODThread.WorkerDelegate((o) => { execute(); })); th.AddExceptionHandler((e) => { if (MockExceptionHandler != null) { MockExceptionHandler(e); } else { Logger.WriteException(e, "PushNotifications"); } }); th.Name = "SendPush_" + pushType.ToString() + "_ClinicNum_" + clinicNum.ToString() + "_UserNum_" + userNum.ToString(); th.Start(); if (MockExceptionHandler != null || !runAsync) //Join back to main thread to cause this to be a blocking call. Unit tests will always block. { th.Join(Timeout.Infinite); } }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public FSFile CreateJson(FSFile file, PushType pushType, PushConfig pushConfig) { string fullPath = file.IFullPath(); bool fileExisted = System.IO.File.Exists(fullPath); // Put together all of the file content. List <string> allLines = new List <string>(); string json = ""; // Process file content, only if there is any. if (file.Content != null && file.Content.Count != 0) { if (file.Content.All(o => o is Dataset)) { pushConfig.UseDatasetSerialization = true; } if (!pushConfig.UseDatasetSerialization) { allLines.AddRange(file.Content.Where(c => c != null).Select(obj => obj.ToJson() + ",")); // Remove the trailing comma if there is only one element. allLines[allLines.Count - 1] = allLines[allLines.Count - 1].Remove(allLines[allLines.Count - 1].Length - 1); // Join all between square brackets to make a valid JSON array. json = String.Join(Environment.NewLine, allLines); json = "[" + json + "]"; } else { // Use the non-JSON compliant "Dataset" serialization style. // This is a newline-separated concatenation of individual JSON-serialized objects. allLines.AddRange(file.Content.Where(c => c != null).Select(obj => obj.ToJson())); json = String.Join(Environment.NewLine, allLines); } if (pushConfig.BeautifyJson) { try { json = BeautifyJson(json); } catch (Exception e) { BH.Engine.Base.Compute.RecordWarning($"Beautify json failed. File will be created with non-beautified json. Error:\n{e.Message}"); } } } bool filecreated = true; try { // Clarify if we are considering the Push in terms of content or of Files. if (string.IsNullOrWhiteSpace(m_defaultFilePath)) // We are talking about Files/Directories. { if (pushType == PushType.DeleteThenCreate) { if (fileExisted) { System.IO.File.Delete(fullPath); } WriteJsonFile(fullPath, json, true); } else if (pushType == PushType.UpdateOnly) { // Overwrite existing file. if (fileExisted) { WriteJsonFile(fullPath, json, true); } else { BH.Engine.Base.Compute.RecordNote($"File {fullPath} was not updated as no file existed at that location."); } } else if (pushType == PushType.UpdateOrCreateOnly) { // Overwrite existing file. If it doesn't exist, create it. WriteJsonFile(fullPath, json, true); } else if (pushType == PushType.CreateOnly || pushType == PushType.CreateNonExisting) { // Create only if file didn't exist. Do not touch existing ones. if (!fileExisted) { WriteJsonFile(fullPath, json, true); } else { BH.Engine.Base.Compute.RecordNote($"File {fullPath} was not created as it existed already (Pushtype {pushType.ToString()} was specified)."); } } else { BH.Engine.Base.Compute.RecordWarning($"The specified Pushtype of {pushType.ToString()} is not supported for .json files."); filecreated = false; } } else // We are talking about File content. { if (pushType == PushType.DeleteThenCreate) { BH.Engine.Base.Compute.RecordNote($"Replacing entire content of file `{fullPath}`."); // Replace all content. WriteJsonFile(fullPath, json, true); } else if (pushType == PushType.CreateOnly || pushType == PushType.CreateNonExisting || pushType == PushType.UpdateOnly || pushType == PushType.UpdateOrCreateOnly) { // Should be refactored to cover distinct use cases for CreateNonExisting, UpdateOnly, UpdateOrCreateOnly if (fileExisted) { BH.Engine.Base.Compute.RecordNote($"Appending content to file `{fullPath}`."); } WriteJsonFile(fullPath, json, false); } else if (pushType == PushType.CreateNonExisting) { // Currently captured by CreateOnly. // The following ideally should be the default behaviour of the IDiffing method. //IEnumerable<object> allReadContent = ReadContent(fullPath); //IEnumerable<IBHoMObject> bHoMObjects_read = allReadContent.OfType<IBHoMObject>(); //IEnumerable<object> genericObjs_read = allReadContent.Except(bHoMObjects_read); //IEnumerable<IBHoMObject> readBhomObjects_hashAssigned = BH.Engine.Diffing.Modify.SetHashFragment(bHoMObjects_read); //IEnumerable<IBHoMObject> bHoMObjects_create = file.Content.OfType<IBHoMObject>(); //IEnumerable<object> genericObjs_create = file.Content.Except(bHoMObjects_create); //Diff diffGeneric = BH.Engine.Diffing.Compute.DiffGenericObjects(genericObjs_read, genericObjs_create, null, true); // Then combine the two diffs in one. // For old objects (= already in file) do not create. // Create only those that are "new". } else if (pushType == PushType.UpdateOnly || pushType == PushType.UpdateOrCreateOnly) { // Currently captured by CreateOnly. See above. // For old objects (= already in file) Update Them. // For those who are "new": create them only if `UpdateOrCreateOnly` is used. } else { BH.Engine.Base.Compute.RecordWarning($"The specified Pushtype of {pushType.ToString()} is not supported for .json files."); filecreated = false; } } } catch (Exception e) { BH.Engine.Base.Compute.RecordError(e.Message); } if (filecreated) { System.IO.FileInfo fileinfo = new System.IO.FileInfo(fullPath); oM.Adapters.File.FSFile createdFile = fileinfo.ToFiling(); createdFile.Content = file.Content; return(createdFile); } BH.Engine.Base.Compute.RecordError($"Could not create {file.ToString()}"); return(null); }