Share via


프로그래밍 방식 액세스

알림 허브 원격 분석 데이터에 프로그래밍 방식으로 액세스할 수 있으며, Microsoft Azure Service Bus 메트릭과 유사합니다(이전 테이블에 제공된 REST 식별자를 사용하여 각 메트릭에 액세스).

1단계: 인증서 만들기

먼저 Azure 구독 리소스에 액세스하는 데 사용할 인증서를 만듭니다. Windows에서 다음을 수행합니다.

  1. Visual Studio 관리자 명령 프롬프트를 열고 다음 명령을 입력합니다.

    makecert -sky exchange -r -n "CN=<CertificateName>" -pe -a sha1 -len 2048 -ss My "<CertificateName>.cer"
    
  2. Certmgr.msc를 실행하고 왼쪽에서 개인을 클릭한 후에 만든 인증서를 마우스 오른쪽 단추로 클릭하고 모든 작업, 내보내기를 차례로 클릭합니다.

    Portal

  3. 마법사의 지시에 따라 개인 키를 내보내지 않는 옵션을 선택합니다. CER 인증서를 내보내는 옵션을 선택하고 .cer로 끝나는 파일 이름을 입력합니다.

    Portal

  4. 내보내기 프로세스를 반복합니다. 이번에는 PFX 파일로 개인 키를 내보내도록 선택하고 .PFX로 끝나는 이름을 선택합니다.

2단계: Azure에 인증서 업로드

이제 인증서를 사용해 Azure 리소스에 대한 작업을 수행할 수 있도록 .CER 파일을 업로드합니다.

  1. Azure 관리 포털에서 왼쪽의 설정을 클릭한 다음 관리 인증서를 클릭합니다.

  2. 화면 아래쪽의 업로드를 클릭하고 .CER 파일을 선택합니다.

  3. 관리할 구독 ID를 적어 둡니다.

    참고

    알림 허브가 포함된 구독의 ID를 적어 두어야 합니다.

    Portal

3단계: REST 인터페이스를 통해 메트릭에 액세스

원격 분석을 읽으려면 Microsoft Azure Service Bus 메트릭에 지정된 규칙에 따라 생성된 URL에 대한 REST 호출을 실행해야 합니다(이전 섹션에서 보고된 메트릭 이름 사용).

다음 코드는 2013-08-06T21:30:00Z 이후 5분 간격으로 집계된 성공한 푸시 수를 검색하는 샘플입니다. 구독 ID, 네임스페이스 이름, 알림 허브 이름 및 pfx 인증서 경로는 실제 값으로 바꾸세요.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Syndication;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace telemetry1
{
    class Program
    {
        [DataContract(Name = "properties", Namespace = "https://schemas.microsoft.com/ado/2007/08/dataservices")]
        public class MetricValue
        {
            [DataMember(Name = "Timestamp")]
            public DateTime Timestamp { get; set; }

            [DataMember(Name = "Min")]
            public long Min { get; set; }

            [DataMember(Name = "Max")]
            public long Max { get; set; }

            [DataMember(Name = "Total")]
            public long Total { get; set; }

            [DataMember(Name = "Average")]
            public float Average { get; set; }
        }

        static void Main(string[] args)
        {
            string uri = @"https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespaceName}/NotificationHubs/{hubName}/metrics/outgoing.allpns.success/rollups/PT5M/Values?$filter=Timestamp%20gt%20datetime'2014-08-06T21:30:00Z'";
            HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(uri);
            sendNotificationRequest.Method = "GET";
            sendNotificationRequest.ContentType = "application/xml";
            sendNotificationRequest.Headers.Add("x-ms-version", "2015-01");
            X509Certificate2 certificate = new X509Certificate2(@"{pathToPfxCert}", "{certPassword}");
            sendNotificationRequest.ClientCertificates.Add(certificate);


            try
            {
                HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();

                using (XmlReader reader = XmlReader.Create(response.GetResponseStream(), new XmlReaderSettings { CloseInput = true }))
                {
                    SyndicationFeed feed = SyndicationFeed.Load<SyndicationFeed>(reader);

                    foreach (SyndicationItem item in feed.Items)
                    {
                        XmlSyndicationContent syndicationContent = item.Content as XmlSyndicationContent;
                        MetricValue value = syndicationContent.ReadContent<MetricValue>();
                        Console.WriteLine(value.Total);
                    }
                }
            }
            catch (WebException exception)
            {
                string error = new StreamReader(exception.Response.GetResponseStream()).ReadToEnd();
                Console.WriteLine(error);
            }
        }


    }
}