internal static IList <ChangeNotificationData> NotifyChange(Task task, UnifiedPolicyStorageBase policyStorageObject, IEnumerable <UnifiedPolicyStorageBase> relatedStorageObjects, IConfigurationSession dataSession, ExecutionLog logger) { Exception exception = null; string text = string.Empty; string empty = string.Empty; ChangeNotificationData changeNotificationData = IntuneCompliancePolicySyncNotificationClient.CreateChangeData(Workload.Intune, policyStorageObject); List <ChangeNotificationData> list = new List <ChangeNotificationData> { changeNotificationData }; List <SyncChangeInfo> list2 = new List <SyncChangeInfo>(); foreach (UnifiedPolicyStorageBase policyStorageObject2 in relatedStorageObjects) { list.Add(IntuneCompliancePolicySyncNotificationClient.CreateChangeData(Workload.Intune, policyStorageObject2)); } foreach (ChangeNotificationData changeNotificationData2 in list) { SyncChangeInfo syncChangeInfo = changeNotificationData2.ShouldNotify ? changeNotificationData2.CreateSyncChangeInfo(true) : null; if (syncChangeInfo == null) { logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Warning, string.Format("We did not notify workload '{0}' for changes to objectId {1}", Workload.Intune, changeNotificationData2.Id), exception); } list2.Add(syncChangeInfo); } try { if (list2.Any <SyncChangeInfo>()) { text = IntuneCompliancePolicySyncNotificationClient.MakeNotificationCall(task, list2, changeNotificationData.UseFullSync, changeNotificationData.ShouldNotify, dataSession, logger); } } catch (Exception ex) { text = Strings.ErrorMessageForNotificationFailure(Workload.Intune.ToString(), ex.Message); exception = ex; } if (!string.IsNullOrEmpty(text)) { task.WriteWarning(Strings.WarningNotifyWorkloadFailed(changeNotificationData.ToString())); logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Warning, string.Format("We failed to notify workload '{0}' with error message '{1}'", Workload.Intune, text), exception); MonitoringItemErrorPublisher.Instance.PublishEvent("UnifiedPolicySync.SendNotificationError", UnifiedPolicyConfiguration.GetInstance().GetOrganizationIdKey(dataSession), string.Format("Workload={0};Timestamp={1}", Workload.Intune, DateTime.UtcNow), exception); } else { logger.LogOneEntry(ExecutionLog.EventType.Verbose, task.GetType().Name, empty, "Notification '{0}' was sent to workload '{1}' with sync change info: '{2}'", new object[] { empty, Workload.Intune, list2.First <SyncChangeInfo>().ToString() }); } AggregatedNotificationClients.SetNotificationResults(list, text); return(list); }
private static string MakeNotificationCall(Task task, List <SyncChangeInfo> syncChangeInfos, bool useFullSync, bool syncNow, IConfigurationSession dataSession, ExecutionLog logger) { string text = dataSession.GetOrgContainer().OrganizationId.ToExternalDirectoryOrganizationId(); Guid tenantId; if (!Guid.TryParse(text, out tenantId)) { task.WriteWarning(Strings.WarningInvalidTenant(text)); return("Error ExternalID not a guid"); } string url = string.Format("{0}(guid'{1}')", UnifiedPolicyConfiguration.GetInstance().GetIntuneEndpointUrl(dataSession), text); string body = IntuneCompliancePolicySyncNotificationClient.CreateJsonNotificationBody(tenantId, useFullSync, syncNow, syncChangeInfos); string result = null; try { result = IntuneCompliancePolicySyncNotificationClient.Send(url, body, dataSession.GetOrgContainer().OrganizationId, dataSession, logger, task); } catch (WebException ex) { logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Warning, string.Format("We failed to notify workload '{0}'", Workload.Intune), ex); task.WriteVerbose(ex.ToString()); result = ex.ToString(); } return(result); }
internal static string NotifyChangesByWorkload(Task task, IConfigurationSession configurationSession, Workload workload, IEnumerable <SyncChangeInfo> syncChangeInfos, bool fullSync, bool syncNow, ExecutionLog logger, Type client, out string notificationIdentifier) { Exception exception = null; notificationIdentifier = string.Empty; string text = string.Empty; try { CompliancePolicySyncNotificationClient compliancePolicySyncNotificationClient = AggregatedNotificationClients.workloadToNotificationClientsGetter[workload](configurationSession, new WriteVerboseDelegate(task.WriteVerbose)); if (compliancePolicySyncNotificationClient != null) { task.WriteVerbose(Strings.VerboseNotifyWorkloadWithChanges(workload.ToString(), string.Concat(from syncChangeInfo in syncChangeInfos select syncChangeInfo.ToString()))); notificationIdentifier = compliancePolicySyncNotificationClient.NotifyPolicyConfigChanges(syncChangeInfos, fullSync, syncNow); task.WriteVerbose(Strings.VerboseNotifyWorkloadWithChangesSuccess(workload.ToString(), notificationIdentifier)); } else { text = Strings.WarningNotificationClientIsMissing(workload.ToString()); } } catch (CompliancePolicySyncNotificationClientException ex) { text = Strings.ErrorMessageForNotificationFailure(workload.ToString(), ex.Message); exception = ex; } if (!string.IsNullOrEmpty(text)) { logger.LogOneEntry(client.Name, string.Empty, ExecutionLog.EventType.Warning, string.Format("We failed to notify workload '{0}' with error message '{1}'", workload, text), exception); MonitoringItemErrorPublisher.Instance.PublishEvent("UnifiedPolicySync.SendNotificationError", UnifiedPolicyConfiguration.GetInstance().GetOrganizationIdKey(configurationSession), string.Format("Workload={0};Timestamp={1}", workload, DateTime.UtcNow), exception); } else { ExecutionLog.EventType eventType = ExecutionLog.EventType.Verbose; string name = client.Name; string correlationId = notificationIdentifier; string format = "Notification '{0}' was sent to workload '{1}' with sync change info: '{2}'"; object[] array = new object[3]; array[0] = notificationIdentifier; array[1] = workload; array[2] = string.Join(",", from x in syncChangeInfos select x.ToString()); logger.LogOneEntry(eventType, name, correlationId, format, array); } return(text); }
private static string Send(string url, string body, OrganizationId tenantid, IConfigurationSession dataSession, ExecutionLog logger, Task task) { HttpClientHandler handler = new HttpClientHandler { PreAuthenticate = true }; string acstoken = IntuneCompliancePolicySyncNotificationClient.GetACSToken(tenantid, dataSession, logger, task); string result; using (HttpClient httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Add("Authorization", acstoken); httpClient.DefaultRequestHeaders.Add("api-version", "1.0"); StringContent content = new StringContent(body, Encoding.UTF8, "application/json"); HttpResponseMessage httpResponseMessage = null; HttpWebResponse httpWebResponse = null; try { httpResponseMessage = httpClient.PutAsync(url, content).Result; } catch (WebException ex) { httpWebResponse = (HttpWebResponse)ex.Response; Stream responseStream = httpWebResponse.GetResponseStream(); Encoding encoding = Encoding.GetEncoding("utf-8"); string text = "Fail to notify: "; if (responseStream != null) { StreamReader streamReader = new StreamReader(responseStream, encoding); char[] array = new char[256]; for (int i = streamReader.Read(array, 0, 256); i > 0; i = streamReader.Read(array, 0, 256)) { text += new string(array, 0, i); } } logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, text, ex); } string text2; if (httpResponseMessage != null) { text2 = ((httpResponseMessage.StatusCode == HttpStatusCode.OK) ? string.Empty : (httpResponseMessage.StatusCode + " " + httpResponseMessage.Content.ReadAsStringAsync().Result)); } else if (httpWebResponse != null) { text2 = httpWebResponse.StatusDescription; } else { text2 = "Failed"; } result = text2; } return(result); }
private static string GetACSToken(OrganizationId tenantID, IConfigurationSession dataSession, ExecutionLog logger, Task task) { string result = null; LocalTokenIssuer localTokenIssuer = new LocalTokenIssuer(tenantID); LocalConfiguration configuration = ConfigProvider.Instance.Configuration; Uri uri = null; string text = null; string applicationId = configuration.ApplicationId; string text2 = null; foreach (PartnerApplication partnerApplication in configuration.PartnerApplications) { if (partnerApplication.Enabled && partnerApplication.Name.Contains("Intune")) { text2 = partnerApplication.ApplicationIdentifier; break; } } foreach (AuthServer authServer in configuration.AuthServers) { if (authServer.Enabled && authServer.Type == AuthServerType.MicrosoftACS) { text = authServer.IssuerIdentifier; uri = new Uri(authServer.TokenIssuingEndpoint); break; } } if (localTokenIssuer.SigningCert == null) { logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No certificate found.", null); } if (text2 == null) { logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No partnerId found.", null); } if (uri == null) { logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No authorizationEndpoint found.", null); } if (string.IsNullOrEmpty(text)) { logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No issuerIdentifier found.", null); } if (localTokenIssuer.SigningCert != null && text2 != null && uri != null && !string.IsNullOrEmpty(text)) { string arg = applicationId; string arg2 = text2; string intuneResourceUrl = UnifiedPolicyConfiguration.GetInstance().GetIntuneResourceUrl(dataSession); string arg3 = text; string authority = uri.Authority; string text3 = string.Format("{0}@{1}", arg, tenantID.ToExternalDirectoryOrganizationId()); string text4 = string.Format("{0}/{1}@{2}", arg3, authority, tenantID.ToExternalDirectoryOrganizationId()); string text5 = string.Format("{0}/{1}@{2}", arg2, intuneResourceUrl, tenantID.ToExternalDirectoryOrganizationId()); X509SigningCredentials x509SigningCredentials = new X509SigningCredentials(localTokenIssuer.SigningCert, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); JsonWebSecurityToken jsonWebSecurityToken = new JsonWebSecurityToken(text3, text4, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(5.0), new List <JsonWebTokenClaim>(), x509SigningCredentials); OAuth2AccessTokenRequest oauth2AccessTokenRequest = OAuth2MessageFactory.CreateAccessTokenRequestWithAssertion(jsonWebSecurityToken, text5); OAuth2S2SClient oauth2S2SClient = new OAuth2S2SClient(); try { OAuth2AccessTokenResponse oauth2AccessTokenResponse = (OAuth2AccessTokenResponse)oauth2S2SClient.Issue(uri.AbsoluteUri, oauth2AccessTokenRequest); if (oauth2AccessTokenResponse != null) { result = "Bearer " + oauth2AccessTokenResponse.AccessToken; } } catch (RequestFailedException ex) { ex.ToString(); WebException ex2 = (WebException)ex.InnerException; HttpWebResponse httpWebResponse = (HttpWebResponse)ex2.Response; Stream responseStream = httpWebResponse.GetResponseStream(); Encoding encoding = Encoding.GetEncoding("utf-8"); string text6 = "Auth service call failed: "; if (responseStream != null) { StreamReader streamReader = new StreamReader(responseStream, encoding); char[] array = new char[256]; for (int k = streamReader.Read(array, 0, 256); k > 0; k = streamReader.Read(array, 0, 256)) { text6 += new string(array, 0, k); } } logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, text6, ex); } } return(result); }