// Shared initialization code
		void Initialize ()
		{
			SaveSuccessful = false;
			if (RelyingPartyDto == null)
				RelyingPartyDto = new RelyingPartyDto ();
			RelyingPartyDto.SignatureAlgorithms = new List<SignatureAlgorithmDto> ();
			RelyingPartyDto.AssertionConsumerServices = new List<AssertionConsumerServiceDto> ();
			RelyingPartyDto.AttributeConsumerServices = new List<AttributeConsumerServiceDto> ();
			RelyingPartyDto.SingleLogoutServices = new List<ServiceEndpointDto> ();
		}
 public bool Delete(ServerDto serverDto, string tenant, RelyingPartyDto relyingParty, Token token)
 {
     tenant = Uri.EscapeDataString(tenant);
     var rp = Uri.EscapeDataString(relyingParty.Name);
     var url = string.Format(ServiceConfigManager.RelyingPartyEndPoint, serverDto.Protocol, serverDto.ServerName, serverDto.Port, tenant,rp);
     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
     var requestConfig = new RequestSettings
                             {
                                 Method = HttpMethod.Delete,
                             };
     var headers = ServiceHelper.AddHeaders(ServiceConfigManager.JsonContentType);
     var json = "access_token=" + token.AccessToken + "&token_type=" + token.TokenType.ToString().ToLower();
     var response = _webRequestManager.GetResponse(url, requestConfig, headers, null, json);
     return string.IsNullOrEmpty(response);
 }
		public void DeleteRelyingParty(RelyingPartyDto dto)
		{
			ActionHelper.Execute (delegate() {
				var serverDto = GetServerDto ();
				var tenant = GetTenant ();
				var auth = SnapInContext.Instance.AuthTokenManager.GetAuthToken (serverDto.ServerName);
				var success = SnapInContext.Instance.ServiceGateway.RelyingParty.Delete (serverDto, tenant, dto, auth.Token);
				if (success) {
					UIErrorHelper.ShowAlert ("Relying party " + dto.Name + " deleted successfully", "Information");
				} else {

					UIErrorHelper.ShowAlert ("Failed to delete relying party " + dto.Name, "Information");
				}
				Refresh (this, EventArgs.Empty);
			});
		}
        public RelyingPartyDto Create(ServerDto server, string tenant, RelyingPartyDto relyingParty, Token token)
        {
            tenant = Uri.EscapeDataString(tenant);
            var url = string.Format(ServiceConfigManager.RelyingPartysEndPoint, server.Protocol, server.ServerName, server.Port, tenant);
            var json = JsonConvert.Serialize(relyingParty);
			json = SerializationJsonHelper.Cleanup (json);
			ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            var requestConfig = new RequestSettings
            {
                Method = HttpMethod.Post,
            };
            var headers = ServiceHelper.AddHeaders(ServiceConfigManager.JsonContentType);
            json = "access_token=" + token.AccessToken + "&token_type=" + token.TokenType.ToString().ToLower() + "&" + json;
            var response = _webRequestManager.GetResponse(url, requestConfig, headers, null, json);
            return JsonConvert.Deserialize<RelyingPartyDto>(response);
        }
		public override void AwakeFromNib ()
		{
			base.AwakeFromNib ();
			RelyingPartyDto = RelyingPartyDtoOriginal.DeepCopy ();
			TxtRpName.StringValue = string.IsNullOrEmpty(RelyingPartyDto.Name) ? string.Empty : 
				RelyingPartyDto.Name.Length > 10 ? RelyingPartyDto.Name.Substring(0,10) + "..." : 
				RelyingPartyDto.Name;
			TxtUrl.StringValue = string.IsNullOrEmpty (RelyingPartyDto.Url) ? string.Empty : RelyingPartyDto.Url;
			TxtCertificate.StringValue = "Certificate";
			_certificate = new X509Certificate2 (Encoding.ASCII.GetBytes(RelyingPartyDtoOriginal.Certificate.Encoded));
			this.BtnAddSignAlgo.Activated += OnAddSignatureAlgorithm;
			this.BtnAddAssertServices.Activated += OnAddAssertServices;
			this.BtnAddAttributeService.Activated += OnAddAttributeServices;
			this.BtnAddSloService.Activated += OnAddSloServices;

			this.BtnRemoveSignAlgo.Activated += OnRemoveSignatureAlgorithm;
			this.BtnRemoveAssertService.Activated += OnRemoveAssertServices;
			this.BtnRemoveAttributeService.Activated += OnRemoveAttributeServices;
			this.BtnRemoveSloService.Activated += OnRemoveSloServices;

			this.SignAlgorithmTableView.DoubleClick += OnSignatureAlgorithmUpdate;
			this.SloServicesTableView.DoubleClick += OnSloUpdate;
			this.AttributeTableView.DoubleClick += OnAttributeUpdate;
			this.AssertTableView.DoubleClick += OnAssertUpdate;

			this.BtnApply.Activated += OnClickSaveButton;
			this.BtnBrowseCertificate.Activated += OnBrowseCertificate;
			this.BtnViewCertificate.Activated += (object sender, EventArgs e) => 
			{
				ActionHelper.Execute (delegate() {
					var cert = new X509Certificate2 (Encoding.ASCII.GetBytes(RelyingPartyDtoOriginal.Certificate.Encoded));
					CertificateService.DisplayX509Certificate2(this, cert);
				});
			};

			InitializeSignatureAlgorithm ();
			InitializeAssertionConsumerServices ();
			InitializeAttributeConsumerServices ();
			InitializeSloServices ();

		}
		public void OnClickSaveButton (object sender, EventArgs e)
		{
			ActionHelper.Execute (delegate() {
				if (string.IsNullOrEmpty (TxtUrl.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid Url", "Alert");
				} else if (string.IsNullOrEmpty (TxtCertificate.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid Certificate path", "Alert");
				} /*else if (RelyingPartyDto.SignatureAlgorithms.Count == 0) {
					UIErrorHelper.ShowAlert ("Please add atleast one signature algorithm", "Alert");
				} else if (RelyingPartyDto.AssertionConsumerServices.Count == 0) {
					UIErrorHelper.ShowAlert ("Please add atleast one assertion consumer service", "Alert");
				} else if (RelyingPartyDto.AttributeConsumerServices.Count == 0) {
					UIErrorHelper.ShowAlert ("Please add atleast one attribute consumer service", "Alert");
				} else if (RelyingPartyDto.SingleLogoutServices.Count == 0) {
					UIErrorHelper.ShowAlert ("Please add atleast one single logout service", "Alert");
				}*/ else if (!string.IsNullOrEmpty (TxtCertificate.StringValue) && TxtCertificate.StringValue != "Certificate"  
					&& !System.IO.File.Exists (TxtCertificate.StringValue.Replace ("file://", string.Empty))) {
					UIErrorHelper.ShowAlert ("Certificate path is not valid", "Alert");
				} else {
					var encoded = string.Empty;
					var cert = new X509Certificate2 ();
					ActionHelper.Execute (delegate() {
						if(TxtCertificate.StringValue == "Certificate")
						{
							encoded = _certificate.ToPem ();
						}
						else 
						{	
							cert.Import (TxtCertificate.StringValue.Replace ("file://", string.Empty));
							encoded = cert.ToPem ();
						}
					
						RelyingPartyDto.Name = RelyingPartyDtoOriginal.Name;
						RelyingPartyDto.Certificate = new CertificateDto { Encoded =  encoded};
						RelyingPartyDto.Url = TxtUrl.StringValue;

						var auth = SnapInContext.Instance.AuthTokenManager.GetAuthToken (ServerDto.ServerName);
						RelyingPartyDto = SnapInContext.Instance.ServiceGateway.RelyingParty.Update (ServerDto, TenantName, RelyingPartyDto, auth.Token);

						NSNotificationCenter.DefaultCenter.PostNotificationName ("RefreshTableView", this);
					});
				}
			});
		}