public void SetExtractionStatus(List <SchemaDetails> schemaDetailsList, List <SchemaMigrationItemViewModel> schemaItems)
 {
     try
     {
         foreach (var item in schemaDetailsList)
         {
             TraceProvider.WriteLine(string.Format("Extracting Schema {0}", item.fullNameOfSchemaToUpload));
             if (item.isSchemaExtractedFromDb)
             {
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ImportStatus     = MigrationStatus.Succeeded;
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ImportStatusText = string.Format("Schema {0} extracted succesfully", item.fullNameOfSchemaToUpload);
                 TraceProvider.WriteLine(string.Format("Schema {0} succesfully extracted with name {1}", item.fullNameOfSchemaToUpload, item.fullNameOfSchemaToUpload));
                 TraceProvider.WriteLine(string.Format("Schema {0} extracted succesfully", item.fullNameOfSchemaToUpload));
             }
             else
             {
                 string error = string.IsNullOrEmpty(item.errorDetailsForExtraction) ? "Unknown" : item.errorDetailsForExtraction;
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ImportStatus     = MigrationStatus.Failed;
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ImportStatusText = string.Format("Schema {0} extraction failed. Reason : {1}", item.fullNameOfSchemaToUpload, item.errorDetailsForExtraction);
                 TraceProvider.WriteLine(string.Format("Schema {0} extraction failed. Reason:{1} ", item.fullNameOfSchemaToUpload, error));
             }
             TraceProvider.WriteLine();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #2
0
        public static string GetAcsToken(string acsNamespace, string issuerName, string issuerKey, string appliesToAddress)
        {
            using (WebClient client = new WebClient())
            {
                client.BaseAddress = string.Format(CultureInfo.InvariantCulture, @"https://{0}.{1}", acsNamespace, AcsBaseAddress);
                NameValueCollection values = new NameValueCollection();
                values.Add("wrap_name", issuerName);
                values.Add("wrap_password", issuerKey);
                values.Add("wrap_scope", appliesToAddress);
                try
                {
                    byte[] responseBytes = client.UploadValues("WRAPv0.9/", "POST", values);
                    string response      = Encoding.UTF8.GetString(responseBytes);

                    // Extract the SWT token and return it.
                    return(response
                           .Split('&')
                           .Single(value => value.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase))
                           .Split('=')[1]);
                }
                catch (WebException ex)
                {
                    TraceProvider.WriteLine(Resources.ErrorGettingACSToken, ex);
                    throw new TpmMigrationException(Resources.ErrorGettingACSToken, ex);
                }
            }
        }
Example #3
0
        protected override Task <IEnumerable <Server.Partner> > GetEntitiesAsync()
        {
            PartnerDataGridEnabled = false;
            var bizTalkTpmContext = this.ApplicationContext.GetBizTalkServerTpmContext();

            return(Task.Factory.StartNew <IEnumerable <Server.Partner> >(() =>
            {
                try
                {
                    //var partnerships = bizTalkTpmContext.Partners.Where(X => X.Name.Contains("PC Connect")).First<Server.Partner>().GetPartnerships();
                    // var str = partnerships.First().GetAgreements();
                    if (!string.IsNullOrEmpty(PartnerFilter))
                    {
                        string filter = partnerFilter.ToString();
                        return bizTalkTpmContext.Partners.Where(x => x.Name.ToLower().Contains(filter.ToLower())).OrderBy(x => x.Name).ToList();
                    }
                    else
                    {
                        return bizTalkTpmContext.Partners.OrderBy(x => x.Name).ToList();
                    }
                }

                catch (Exception ex)
                {
                    TraceProvider.WriteLine(string.Format(CultureInfo.InvariantCulture, "Not able to retrieve partners. {0}", ExceptionHelper.GetExceptionMessage(ex)));
                    var statusBarViewModel = this.ApplicationContext.GetService <StatusBarViewModel>();
                    statusBarViewModel.StatusInfoType = StatusInfoType.Error;
                    statusBarViewModel.ShowError("Error. Failed to retrieve partners from Biztalk Server. Reason: " + ExceptionHelper.GetExceptionMessage(ex));
                    return new List <Server.Partner>();
                }
            }));
        }
 public void SetMigrationStatus(List <SchemaDetails> schemaDetailsList, List <SchemaMigrationItemViewModel> schemaItems)
 {
     try
     {
         foreach (var item in schemaDetailsList)
         {
             TraceProvider.WriteLine(string.Format("Migrating Schema {0}", item.fullNameOfSchemaToUpload));
             if (item.schemaUploadToIAStatus == SchemaUploadToIAStatus.Success)
             {
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ExportStatus     = MigrationStatus.Succeeded;
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ExportStatusText = string.Format("Schema {0} migrated succesfully", item.fullNameOfSchemaToUpload);
                 TraceProvider.WriteLine(string.Format("Schema {0} Migration Successfull", item.fullNameOfSchemaToUpload));
             }
             else if (item.schemaUploadToIAStatus == SchemaUploadToIAStatus.Partial)
             {
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ExportStatus     = MigrationStatus.Partial;
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ExportStatusText = string.Format("Schema {0} already exists in IA. Since overwrite was disabled, it was not overwritten.", item.fullNameOfSchemaToUpload);
                 TraceProvider.WriteLine(string.Format("Schema {0} Not Migrated", item.fullNameOfSchemaToUpload));
             }
             else
             {
                 string error = string.IsNullOrEmpty(item.errorDetailsForMigration) ? "Unknown" : item.errorDetailsForMigration;
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ExportStatus     = MigrationStatus.Failed;
                 schemaItems.Where(x => x.MigrationEntity.schemaName == item.schemaName && x.MigrationEntity.assemblyFullyQualifiedName == item.assemblyFullyQualifiedName).First().ExportStatusText = string.Format("Schema {0} migration failed.Reason : {1}", item.fullNameOfSchemaToUpload, item.errorDetailsForMigration);
                 TraceProvider.WriteLine(string.Format("Schema {0} Migration Failed.Reason : {1} ", item.fullNameOfSchemaToUpload, error));
             }
             TraceProvider.WriteLine();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 public override async Task ImportAsync(SchemaMigrationItemViewModel serverSchemaItem)
 {
     try
     {
         var serverSchema = serverSchemaItem.MigrationEntity;
         TraceProvider.WriteLine();
         TraceProvider.WriteLine("Exporting Schema to Json: {0}", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload);
         serverSchemaItem.ImportStatus     = MigrationStatus.NotStarted;
         serverSchemaItem.ExportStatus     = MigrationStatus.NotStarted;
         serverSchemaItem.ImportStatusText = null;
         serverSchemaItem.ExportStatusText = null;
         await Task.Factory.StartNew(() =>
         {
             try
             {
                 CreateSchemas(serverSchemaItem);
                 serverSchemaItem.ImportStatus    = MigrationStatus.Succeeded;
                 StringBuilder successMessageText = new StringBuilder();
                 successMessageText.Append(string.Format(Resources.ImportSuccessMessageText, serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload));
                 serverSchemaItem.ImportStatusText = successMessageText.ToString();
                 TraceProvider.WriteLine(string.Format("Schema {0} exported to Json with Name {1}", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload, FileOperations.GetFileName(serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload)));
                 TraceProvider.WriteLine(string.Format("Schema Export to Json Successfull: {0}", serverSchemaItem.Name));
                 TraceProvider.WriteLine();
             }
             catch (Exception)
             {
                 //throw ex;
             }
         });
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public async Task MigrateToCloudIA(List <SchemaMigrationItemViewModel> schemaItems, IntegrationAccountDetails iaDetails)
        {
            this.iaDetails = iaDetails;
            ActionOnSchemas      action = new ActionOnSchemas();
            var                  schemasToBeUploaded        = thisApplicationContext.GetProperty("SchemasToUploadOrder") as List <SchemaDetails>;
            AuthenticationResult authresult                 = thisApplicationContext.GetProperty("IntegrationAccountAuthorization") as AuthenticationResult;
            bool                 overwriteExistingArtifacts = Convert.ToBoolean(thisApplicationContext.GetProperty("OverwriteEnabled"));
            List <SchemaDetails> schemaDetailsList          = new List <SchemaDetails>();

            foreach (var schemaItem in schemaItems)
            {
                schemaItem.MigrationEntity.schemaUploadToIAStatus   = SchemaUploadToIAStatus.NotYetStarted;
                schemaItem.MigrationEntity.errorDetailsForMigration = "";
                schemaDetailsList.Add(schemaItem.MigrationEntity);
            }
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    action.UploadToIntegrationAccount(schemasToBeUploaded, ref schemaDetailsList, Resources.JsonSchemaFilesLocalPath, overwriteExistingArtifacts, iaDetails.SubscriptionId, iaDetails.ResourceGroupName, iaDetails.IntegrationAccountName, authresult);
                    SetMigrationStatus(schemaDetailsList, schemaItems);
                }
                catch (Exception ex)
                {
                    SetMigrationStatus(schemaDetailsList, schemaItems);
                    TraceProvider.WriteLine(string.Format("Schemas Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                    TraceProvider.WriteLine();
                    throw new Exception(string.Format("Schemas Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                }
            });
        }
 private void AzureLoginButtonClick(object sender)
 {
     try
     {
         IntegrationAccountContext iaContext = new IntegrationAccountContext();
         var authresult = iaContext.GetAccessTokenFromAAD();
         AuthenticationResult integrationAccountResult = authresult[AuthenticationAccessToken.IntegrationAccount];
         AuthenticationResult keyVaultResult           = authresult[AuthenticationAccessToken.KeyVault];
         this.ApplicationContext.SetProperty("IntegrationAccountAuthorization", integrationAccountResult);
         this.ApplicationContext.SetProperty("KeyVaultAuthorization", keyVaultResult);
         string iaToken = integrationAccountResult?.AccessToken;
         string kvToken = keyVaultResult?.AccessToken;
         statusBarViewModel.Clear();
         try
         {
             HttpResponseMessage response = iaContext.SendSyncGetRequestToIA(UrlHelper.GetSubscriptionsUrl(), integrationAccountResult);
             var reponseObj = JObject.Parse(response.Content.ReadAsStringAsync().Result);
             if (reponseObj.GetValue("value") != null)
             {
                 UserSubscriptions = JsonConvert.DeserializeObject <ObservableCollection <Subscription.RootObject> >(reponseObj["value"].ToString());
                 if (userSubscriptions.Count != 0)
                 {
                     SubscriptionVisible   = true;
                     IsLoginButttonEnabled = false;
                 }
                 else
                 {
                     TraceProvider.WriteLine("No Subscriptions are available for the user. Please login as different user");
                     statusBarViewModel.ShowError("No Subscriptions are available for the user. Please login as different user");
                     IsLoginButttonEnabled = true;
                     SubscriptionVisible   = false;
                 }
             }
             else
             {
                 TraceProvider.WriteLine("No Subscriptions are available for the user. Please login as different user");
                 statusBarViewModel.ShowError("No Subscriptions are available for the user. Please login as different user");
                 IsLoginButttonEnabled = true;
                 SubscriptionVisible   = false;
             }
         }
         catch (Exception ex)
         {
             TraceProvider.WriteLine(string.Format("Error reading user subscriptions from Portal. Reason: {0}{1}", ExceptionHelper.GetExceptionMessage(ex), "Please Login again or as different user."));
             statusBarViewModel.ShowError(string.Format("Error reading user subscriptions from Portal. Reason: {0}{1}", ExceptionHelper.GetExceptionMessage(ex), "Please Login again or as different user."));
             IsLoginButttonEnabled = true;
             SubscriptionVisible   = false;
         }
     }
     catch (Exception ex)
     {
         TraceProvider.WriteLine(string.Format("Error getting the Access Tokens. Reason: {0}", ExceptionHelper.GetExceptionMessage(ex)));
         statusBarViewModel.ShowError(string.Format("Error getting the Access Tokens. Reason: {0}", ExceptionHelper.GetExceptionMessage(ex)));
         IsLoginButttonEnabled = true;
         SubscriptionVisible   = false;
     }
 }
 public override async Task ExportToIA(PartnerMigrationItemViewModel serverPartnerItem, IntegrationAccountDetails iaDetails)
 {
     this.iaDetails = iaDetails;
     try
     {
         TraceProvider.WriteLine("Migrating partner : {0}", serverPartnerItem.MigrationEntity.Name);
         await Task.Factory.StartNew(() =>
         {
             try
             {
                 AuthenticationResult authresult = thisApplicationContext.GetProperty("IntegrationAccountAuthorization") as AuthenticationResult;
                 bool overwrite = Convert.ToBoolean(thisApplicationContext.GetProperty("OverwriteEnabled"));
                 if (!overwrite)
                 {
                     bool exists = CheckIfArtifactExists(serverPartnerItem.MigrationEntity.Name, "Partner", this.iaDetails, authresult).Result;
                     if (exists)
                     {
                         serverPartnerItem.ExportStatus     = MigrationStatus.Partial;
                         serverPartnerItem.ExportStatusText = string.Format("The Partner {0} already exists on IA with name {1}. Since the Overwrite option was disabled, the partner was not overwritten.", serverPartnerItem.MigrationEntity.Name, FileOperations.GetFileName(serverPartnerItem.MigrationEntity.Name));
                         TraceProvider.WriteLine(serverPartnerItem.ExportStatusText);
                         TraceProvider.WriteLine();
                     }
                     else
                     {
                         MigrateToCloudIAPartner(FileOperations.GetPartnerJsonFilePath(serverPartnerItem.MigrationEntity.Name), FileOperations.GetFileName(serverPartnerItem.MigrationEntity.Name), serverPartnerItem, iaDetails, authresult).Wait();
                         serverPartnerItem.ExportStatus   = MigrationStatus.Succeeded;
                         StringBuilder successMessageText = new StringBuilder();
                         successMessageText.Append(string.Format(Resources.ExportSuccessMessageText, serverPartnerItem.MigrationEntity.Name));
                         serverPartnerItem.ExportStatusText = successMessageText.ToString();
                         TraceProvider.WriteLine(string.Format("Partner Migration Successfull: {0}", serverPartnerItem.MigrationEntity.Name));
                         TraceProvider.WriteLine();
                     }
                 }
                 else
                 {
                     MigrateToCloudIAPartner(FileOperations.GetPartnerJsonFilePath(serverPartnerItem.MigrationEntity.Name), FileOperations.GetFileName(serverPartnerItem.MigrationEntity.Name), serverPartnerItem, iaDetails, authresult).Wait();
                     serverPartnerItem.ExportStatus   = MigrationStatus.Succeeded;
                     StringBuilder successMessageText = new StringBuilder();
                     successMessageText.Append(string.Format(Resources.ExportSuccessMessageText, serverPartnerItem.MigrationEntity.Name));
                     serverPartnerItem.ExportStatusText = successMessageText.ToString();
                     TraceProvider.WriteLine(string.Format("Partner Migration Successfull: {0}", serverPartnerItem.MigrationEntity.Name));
                     TraceProvider.WriteLine();
                 }
             }
             catch (Exception)
             {
                 //throw ex;
             }
         });
     }
     catch (Exception)
     {
         //throw ex;
     }
 }
 private static bool TryGetCloudBusinessIdentity(
     Services.BusinessProfile cloudBusinessProfile,
     Server.QualifierIdentity serverBusinessIdentity,
     out Services.BusinessIdentity cloudBusinessIdentity)
 {
     TraceProvider.WriteLine("Profile={0}, Identity:({1}, {2})",
                             cloudBusinessProfile.Name,
                             serverBusinessIdentity.Qualifier,
                             serverBusinessIdentity.Value);
     cloudBusinessIdentity = cloudBusinessProfile.BusinessIdentities.SingleOrDefault(id => AreBusinessIdentitiesEquivalent(id, serverBusinessIdentity));
     return(cloudBusinessIdentity != null);
 }
Example #10
0
        protected override Task <IEnumerable <Server.Agreement> > GetEntitiesAsync()
        {
            var                       bizTalkTpmContext    = this.ApplicationContext.GetBizTalkServerTpmContext();
            var                       selectedPartners     = this.ApplicationContext.GetProperty("SelectedPartners") as IEnumerable <PartnerMigrationItemViewModel>;
            List <string>             selectedPartnersName = new List <string>();
            List <Server.Agreement>   agreements           = new List <BizTalk.B2B.PartnerManagement.Agreement>();
            List <Server.Partnership> partnerships         = new List <Server.Partnership>();

            if (selectedPartners != null)
            {
                foreach (var partner in selectedPartners)
                {
                    if (partner.ImportStatus == MigrationStatus.Succeeded)
                    {
                        selectedPartnersName.Add(partner.Name);
                    }
                }
            }

            return(Task.Factory.StartNew <IEnumerable <Server.Agreement> >(() =>
            {
                try
                {
                    if (selectedPartnersName.Count != 0)
                    {
                        var partners = bizTalkTpmContext.Partners.Where(X => selectedPartnersName.Contains(X.Name));
                        foreach (var partner in partners)
                        {
                            partnerships.AddRange(partner.GetPartnerships());
                        }
                        foreach (var partnership in partnerships)
                        {
                            agreements.AddRange(partnership.GetAgreements());
                        }
                    }
                    else
                    {
                        agreements.AddRange(bizTalkTpmContext.Agreements.Where(x => x.Protocol == "x12" || x.Protocol == "as2" || x.Protocol == "edifact").Take(10).OrderBy(x => x.Name).ToList());
                    }

                    agreements = agreements.Distinct().ToList();
                }
                catch (Exception ex)
                {
                    TraceProvider.WriteLine(string.Format(CultureInfo.InvariantCulture, "Not able to retrieve agreements. {0}", ExceptionHelper.GetExceptionMessage(ex)));
                    var statusBarViewModel = this.ApplicationContext.GetService <StatusBarViewModel>();
                    statusBarViewModel.StatusInfoType = StatusInfoType.Error;
                    statusBarViewModel.ShowError("Error. Failed to retrieve agreements from Biztalk Server. Reason: " + ExceptionHelper.GetExceptionMessage(ex));
                }
                return agreements;
            }));
        }
 public override async Task ExportToIA(SchemaMigrationItemViewModel serverSchemaItem, IntegrationAccountDetails iaDetails)
 {
     this.iaDetails = iaDetails;
     try
     {
         TraceProvider.WriteLine("Migrating schema : {0}", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload);
         await Task.Factory.StartNew(() =>
         {
             try
             {
                 AuthenticationResult authresult = thisApplicationContext.GetProperty("IntegrationAccountAuthorization") as AuthenticationResult;
                 bool overwrite = Convert.ToBoolean(thisApplicationContext.GetProperty("OverwriteEnabled"));
                 if (!overwrite)
                 {
                     bool exists = CheckIfArtifactExists(serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload, "Schema", this.iaDetails, authresult).Result;
                     if (exists)
                     {
                         serverSchemaItem.ExportStatus     = MigrationStatus.Partial;
                         serverSchemaItem.ExportStatusText = string.Format("The Schema {0} already exists on IA with name {1}. Since the Overwrite option was disabled, the certificate was not overwritten.", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload, FileOperations.GetFileName(serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload));
                         TraceProvider.WriteLine(serverSchemaItem.ExportStatusText);
                         TraceProvider.WriteLine();
                     }
                     else
                     {
                         MigrateToCloudIA(FileOperations.GetSchemaJsonFilePath(serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload), FileOperations.GetFileName(serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload), serverSchemaItem, iaDetails, authresult).Wait();
                         serverSchemaItem.ExportStatus     = MigrationStatus.Succeeded;
                         serverSchemaItem.ExportStatusText = string.Format("Schema {0} migrated succesfully", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload);
                         TraceProvider.WriteLine(string.Format("Schema Migration Successfull: {0}", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload));
                         TraceProvider.WriteLine();
                     }
                 }
                 else
                 {
                     MigrateToCloudIA(FileOperations.GetSchemaJsonFilePath(serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload), FileOperations.GetFileName(serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload), serverSchemaItem, iaDetails, authresult).Wait();
                     serverSchemaItem.ExportStatus     = MigrationStatus.Succeeded;
                     serverSchemaItem.ExportStatusText = string.Format("Schema {0} migrated succesfully", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload);
                     TraceProvider.WriteLine(string.Format("Schema Migration Successfull: {0}", serverSchemaItem.MigrationEntity.fullNameOfSchemaToUpload));
                     TraceProvider.WriteLine();
                 }
             }
             catch (Exception)
             {
                 //throw ex;
             }
         });
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        protected override Task <IEnumerable <MapDetails> > GetEntitiesAsync()
        {
            return(Task.Factory.StartNew <IEnumerable <MapDetails> >(() =>
            {
                try
                {
                    var appDetails = ApplicationContext.GetProperty("SelectedApps") as ObservableCollection <ApplicationDetails>;
                    string parameter = "";
                    foreach (var item in appDetails)
                    {
                        if (item.isSelected)
                        {
                            parameter += "'" + item.nID + "',";
                        }
                    }
                    parameter = parameter.Remove(parameter.Length - 1);

                    var maps = this.ApplicationContext.GetProperty(AppConstants.AllMapsContextPropertyName) as ObservableCollection <MapSelectionItemViewModel>;
                    List <MapDetails> mapsList = new List <MapDetails>();
                    if (maps != null && maps.Count != 0)
                    {
                        foreach (var mapItem in maps)
                        {
                            mapsList.Add(mapItem.MigrationEntity);
                        }
                        return mapsList;
                    }
                    else
                    {
                        ActionsOnMaps action = new ActionsOnMaps();
                        string connectionString = this.ApplicationContext.GetProperty("DatabaseConnectionString") as string;
                        mapsList = action.GetListOfMaps(connectionString, Resources.JsonMapFilesLocalPath, parameter);
                        this.ApplicationContext.SetProperty(AppConstants.MapNamespaceVersionList, action.mapNamespaceVersionDict);
                        return mapsList;
                    }
                }

                catch (Exception ex)
                {
                    TraceProvider.WriteLine(string.Format(CultureInfo.InvariantCulture, "Not able to retrieve maps. {0}", ExceptionHelper.GetExceptionMessage(ex)));
                    var statusBarViewModel = this.ApplicationContext.GetService <StatusBarViewModel>();
                    statusBarViewModel.StatusInfoType = StatusInfoType.Error;
                    statusBarViewModel.ShowError("Error. Failed to retrieve maps from Biztalk Server. Reason: " + ExceptionHelper.GetExceptionMessage(ex));
                    return new List <MapDetails>();
                }
            }));
        }
        private void ResourceGroupSelectionChanged()
        {
            IntegrationAccountContext iaContext = new IntegrationAccountContext();
            var authResult = this.ApplicationContext.GetProperty("IntegrationAccountAuthorization") as AuthenticationResult;

            statusBarViewModel.Clear();
            try
            {
                HttpResponseMessage IAresponse = iaContext.SendSyncGetRequestToIA(UrlHelper.GetIntegrationAccountsUrl(SelectedSubscription.SubscriptionId, SelectedResourceGroup.Name), authResult);
                var IAreponseObj = JObject.Parse(IAresponse.Content.ReadAsStringAsync().Result);
                HttpResponseMessage KVresponse = iaContext.SendSyncGetRequestToIA(UrlHelper.GetKeyVaultsUrl(SelectedSubscription.SubscriptionId, SelectedResourceGroup.Name), authResult);
                var KVreponseObj = JObject.Parse(KVresponse.Content.ReadAsStringAsync().Result);
                if (IAreponseObj.GetValue("value") != null && KVreponseObj.GetValue("value") != null)
                {
                    UserIntegrationAccounts = JsonConvert.DeserializeObject <ObservableCollection <IntegrationAccount.RootObject> >(IAreponseObj["value"].ToString());
                    UserKeyVaults           = JsonConvert.DeserializeObject <ObservableCollection <KeyVault.RootObject> >(KVreponseObj["value"].ToString());
                    if (UserIntegrationAccounts.Count != 0)
                    {
                        IsLoginButttonEnabled = false;
                    }
                    else
                    {
                        TraceProvider.WriteLine("No Integration Accounts are available for the user. Please login as different user or select a different ResourceGroup/Subscription");
                        statusBarViewModel.ShowError("No Integration Accounts are available for the user. Please login as different user or select a different ResourceGroup/Subscription");
                        IsLoginButttonEnabled = true;
                    }
                    if (UserKeyVaults.Count == 0)
                    {
                        TraceProvider.WriteLine("No Key Vaults are available for the user in the current RG. If you wish to migrate any Private cerificate to IA, please login as different user or select a different ResourceGroup/Subscription");
                        statusBarViewModel.ShowError("No Key Vaults are available for the user in the current RG. If you wish to migrate any Private cerificate to IA, please login as different user or select a different ResourceGroup/Subscription");
                        IsLoginButttonEnabled = true;
                    }
                }
                else
                {
                    TraceProvider.WriteLine("No Integration Accounts are available for the user. Please login as different user or select a different ResourceGroup/Subscription");
                    statusBarViewModel.ShowError("No Integration Accounts are available for the user. Please login as different user or select a different ResourceGroup/Subscription");
                    IsLoginButttonEnabled = true;
                }
            }
            catch (Exception ex)
            {
                TraceProvider.WriteLine(string.Format("Error reading user IA's from Portal. Reason: {0}{1}", ExceptionHelper.GetExceptionMessage(ex), "Please Login again or as different user."));
                statusBarViewModel.ShowError(string.Format("Error reading user IA's  from Portal. Reason: {0}{1}", ExceptionHelper.GetExceptionMessage(ex), "Please Login again or as different user."));
                IsLoginButttonEnabled = true;
            }
        }
Example #14
0
        public async Task <HttpResponseMessage> MigrateToCloudIA(string filePath, string name, TEntity item, IntegrationAccountDetails iaDetails, AuthenticationResult authResult)
        {
            try
            {
                IntegrationAccountContext sclient = new IntegrationAccountContext();
                var x = await sclient.LAIntegrationFromFile(UrlHelper.GetCertificateUrl(name, iaDetails), filePath, authResult);

                return(x);
            }
            catch (Exception ex)
            {
                SetStatus(item, MigrationStatus.Failed, string.Format("Certificate Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine(string.Format("Certificate Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine();
                throw ex;
            }
        }
Example #15
0
        private async Task ExportPartners()
        {
            try
            {
                if (importedPartners != null)
                {
                    foreach (var partner in importedPartners)
                    {
                        try
                        {
                            await pMigrator.ExportToIA(partner, this.ApplicationContext.GetService <IntegrationAccountDetails>());
                        }
                        catch (Exception ex)
                        {
                            partner.ExportStatus     = MigrationStatus.Failed;
                            partner.ExportStatusText = ex.Message;
                            TraceProvider.WriteLine(string.Format("An exception occured:{0}", ex.Message));
                        }
                        finally
                        {
                            ExportedItems.Where(item => item.ArtifactName == partner.MigrationEntity.Name).First().ExportStatus     = partner.ExportStatus;
                            ExportedItems.Where(item => item.ArtifactName == partner.MigrationEntity.Name).First().ExportStatusText = partner.ExportStatusText;
                            countArtifactsMigrated++;
                            UpdateProgress();
                        }
                    }

                    foreach (var item in importedPartners)
                    {
                        if (item.ExportStatus == MigrationStatus.Failed)
                        {
                            StatusBarViewModel.StatusInfoType = StatusInfoType.Error;
                            StatusBarViewModel.ShowError("Error(s) were encountered. Please refer the Status Tool Tip / Log File for more details.");
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                StatusBarViewModel.StatusInfoType = StatusInfoType.Error;
                StatusBarViewModel.ShowError("Error was encountered. Reason: " + ex.Message);
                TraceProvider.WriteLine("Error was encountered. Reason: " + ex.InnerException.StackTrace);
            }
        }
        public async Task <HttpResponseMessage> MigrateToCloudIA(string filePath, string name, SchemaMigrationItemViewModel serverSchemaItem, IntegrationAccountDetails iaDetails, AuthenticationResult authResult)
        {
            try
            {
                IntegrationAccountContext sclient = new IntegrationAccountContext();
                var x = await sclient.LAIntegrationFromFile(UrlHelper.GetSchemaUrl(name, iaDetails), filePath, authResult);

                return(x);
            }
            catch (Exception ex)
            {
                serverSchemaItem.ExportStatus     = MigrationStatus.Failed;
                serverSchemaItem.ExportStatusText = ex.Message;
                TraceProvider.WriteLine(string.Format("Schema Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine();
                throw ex;
            }
        }
        private void OpenLink()
        {
            var filePath = Resources.DocumentationLink;

            try
            {
                if (File.Exists(filePath))
                {
                    Process.Start(filePath);
                }
            }
            catch (Exception ex)
            {
                TraceProvider.WriteLine("Error. Failed to open the Documentation. Reason: " + ExceptionHelper.GetExceptionMessage(ex));
                var statusBarViewModel = this.ApplicationContext.GetService <StatusBarViewModel>();
                statusBarViewModel.StatusInfoType = StatusInfoType.Error;
                statusBarViewModel.ShowError("Error. Failed to open the Documentation. Reason: " + ExceptionHelper.GetExceptionMessage(ex));
            }
        }
        public static Dictionary <string, string> FindAgreementsToBeConsolidated(string sqlConnectionString, List <string> guestPartnerTpmIds)
        {
            Dictionary <string, string> originalAndTpmIdMapping = new Dictionary <string, string>();

            using (SqlConnection cn = new SqlConnection(sqlConnectionString))
            {
                try
                {
                    var query = ConfigurationManager.AppSettings["PartnerQuery"];
                    query = string.Format(query, string.Join(",", guestPartnerTpmIds));
                    using (var cmd = new SqlCommand(query, cn))
                    {
                        if (cn.State == System.Data.ConnectionState.Closed)
                        {
                            try { cn.Open(); }
                            catch (Exception e)
                            {
                                string message = $"ERROR! Unable to establish connection to the ebisDB database. \nErrorMessage:{e.Message}";
                                TraceProvider.WriteLine($"{message} \nStackTrace:{e.StackTrace}");
                                throw new Exception(message);
                            }
                        }
                        using (var rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                if (!originalAndTpmIdMapping.ContainsKey(rdr["TPMPartnerID"].ToString()))
                                {
                                    originalAndTpmIdMapping.Add(rdr["TPMPartnerID"].ToString(), rdr["PartnerID"].ToString());
                                }
                            }
                        }
                        return(originalAndTpmIdMapping);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
 public override async Task ImportAsync(PartnerMigrationItemViewModel serverPartnerItem)
 {
     try
     {
         var serverPartner = serverPartnerItem.MigrationEntity;
         TraceProvider.WriteLine();
         TraceProvider.WriteLine("Exporting Partner to Json: {0}", serverPartnerItem.MigrationEntity.Name);
         serverPartnerItem.ImportStatus            = MigrationStatus.NotStarted;
         serverPartnerItem.ExportStatus            = MigrationStatus.NotStarted;
         serverPartnerItem.ImportStatusText        = null;
         serverPartnerItem.ExportStatusText        = null;
         serverPartnerItem.CertificationRequired   = false;
         serverPartnerItem.CertificateImportStatus = MigrationStatus.NotStarted;
         serverPartnerItem.CertificateExportStatus = MigrationStatus.NotStarted;
         serverPartnerItem.ExportStatusText        = null;
         await Task.Factory.StartNew(() =>
         {
             try
             {
                 CreatePartners(serverPartnerItem);
                 serverPartnerItem.ImportStatus   = MigrationStatus.Succeeded;
                 StringBuilder successMessageText = new StringBuilder();
                 successMessageText.Append(string.Format(Resources.ImportSuccessMessageText, serverPartnerItem.MigrationEntity.Name));
                 serverPartnerItem.ImportStatusText        = successMessageText.ToString();
                 serverPartnerItem.CertificationRequired   = certificateRequired;
                 serverPartnerItem.CertificateImportStatus = succesfullCertificateImport;
                 TraceProvider.WriteLine(string.Format("Partner {0} exported to Json with Name {1}", serverPartnerItem.MigrationEntity.Name, FileOperations.GetFileName(serverPartnerItem.MigrationEntity.Name)));
                 TraceProvider.WriteLine(string.Format("Partner Export to Json Successfull: {0}", serverPartner.Name));
                 TraceProvider.WriteLine();
             }
             catch (Exception)
             {
                 //throw ex;
             }
         });
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public void UpdateStatus(string agreementName, out MigrationStatus migrationStatus)
        {
            migrationStatus = MigrationStatus.Succeeded;
            var statusBarViewModel = this.applicationContext.GetService <StatusBarViewModel>();

            Debug.Assert(statusBarViewModel != null, "StatusBarViewModel has not been initialized in application context");

            string statusBarMessage = string.Empty;

            if (this.isMessageEncrypted == true)
            {
                statusBarMessage += string.Format(CultureInfo.InvariantCulture, "Message Encryption settings are not migrated for sender {0}", senderProfileName) + Environment.NewLine;
                migrationStatus   = MigrationStatus.Partial;
            }

            if (this.signingThumbprintMissing != null && this.signingThumbprintMissing.Length > 0)
            {
                statusBarMessage += string.Format(CultureInfo.InvariantCulture, "Certificate with thumbprint {0} missing in the Sender's {1} profile ", this.signingThumbprintMissing, senderProfileName);
                migrationStatus   = MigrationStatus.Partial;
            }

            if (statusBarMessage.Length > 0)
            {
                if (agreementName != currentAgreementName)
                {
                    statusBarViewModel.ShowWarning(Environment.NewLine + agreementName + " (Warning) : " + Environment.NewLine + statusBarMessage);
                    currentAgreementName = agreementName;
                    TraceProvider.WriteLine(statusBarMessage);
                }
                else
                {
                    statusBarViewModel.ShowWarning(Environment.NewLine + statusBarMessage);
                    TraceProvider.WriteLine(statusBarMessage);
                }
            }

            this.isMessageEncrypted       = false;
            this.signingThumbprintMissing = string.Empty;
        }
        private void SubscriptionSelectionChanged()
        {
            IntegrationAccountContext iaContext = new IntegrationAccountContext();
            var authResult = this.ApplicationContext.GetProperty("IntegrationAccountAuthorization") as AuthenticationResult;

            statusBarViewModel.Clear();
            try
            {
                HttpResponseMessage response = iaContext.SendSyncGetRequestToIA(UrlHelper.GetResourceGroupsUrl(SelectedSubscription.SubscriptionId), authResult);
                var reponseObj = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                if (reponseObj.GetValue("value") != null)
                {
                    UserResourceGroups = JsonConvert.DeserializeObject <ObservableCollection <ResourceGroup.RootObject> >(reponseObj["value"].ToString());
                    if (userResourceGroups.Count != 0)
                    {
                        IsLoginButttonEnabled = false;
                    }
                    else
                    {
                        TraceProvider.WriteLine("No Resource Groups are available for the user. Please login as different user or select different Subscription");
                        statusBarViewModel.ShowError("No Resource Groups are available for the user. Please login as different user or select different Subscription");
                        IsLoginButttonEnabled = true;
                    }
                }
                else
                {
                    TraceProvider.WriteLine("No Resource Groups are available for the user. Please login as different user or select different Subscription");
                    statusBarViewModel.ShowError("No Resource Groups are available for the user. Please login as different user or select different Subscription");
                    IsLoginButttonEnabled = true;
                }
            }
            catch (Exception ex)
            {
                TraceProvider.WriteLine(string.Format("Error reading user RG's from Portal. Reason: {0}{1}", ExceptionHelper.GetExceptionMessage(ex), "Please Login again or as different user."));
                statusBarViewModel.ShowError(string.Format("Error reading user RG's from Portal. Reason: {0}{1}", ExceptionHelper.GetExceptionMessage(ex), "Please Login again or as different user."));
                IsLoginButttonEnabled = true;
            }
        }
Example #22
0
        public void CheckIfCertificateIsprivate(TEntity item, string certificateName, IntegrationAccountDetails iaDetails)
        {
            try
            {
                string filepath    = FileOperations.GetCertificateJsonFilePath(certificateName);
                string content     = File.ReadAllText(filepath);
                var    certificate = JsonConvert.DeserializeObject <JsonCertificate.Rootobject>(content);
                if (certificate.properties.key != null)
                {
                    string keyvaultname = iaDetails.KeyVaultName;
                    if (string.IsNullOrEmpty(keyvaultname))
                    {
                        throw new Exception("Couldn't find the name of the Key Vault to upload the Private key for the Private Certificate. Make sure you selected a Key Vault at the Integration Account Details Screen");
                    }
                    string certName                      = FileOperations.GetFileName(certificateName);
                    string keyvaultfilepath              = FileOperations.GetKeyVaultJsonFilePath(certName + "Privatekey");
                    IntegrationAccountContext sclient    = new IntegrationAccountContext();
                    AuthenticationResult      authresult = thisApplicationContext.GetProperty("KeyVaultAuthorization") as AuthenticationResult;
                    string kid = sclient.UploadCertificatePrivateKeyToKeyVault(StringOperations.RemoveAllSpecialCharacters(certName) + "Privatekey", keyvaultname, keyvaultfilepath, authresult);
                    certificate.properties.key.keyName     = StringOperations.RemoveAllSpecialCharacters(certName) + "Privatekey";
                    certificate.properties.key.keyVersion  = kid;
                    certificate.properties.key.keyVault.id = string.Format(ConfigurationManager.AppSettings["KeyVaultResourceIdTemplate"], iaDetails.SubscriptionId, iaDetails.ResourceGroupName, keyvaultname);
                    //certificate.properties.key.keyVault.name = certName + "Privatekey";

                    string fileName = FileOperations.GetCertificateJsonFilePath(certName);
                    string partnerJsonFileContent = JsonConvert.SerializeObject(certificate);
                    File.WriteAllText(fileName, partnerJsonFileContent);
                }
            }
            catch (Exception ex)
            {
                SetStatus(item, MigrationStatus.Failed, string.Format("Certificate Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine(string.Format("Certificate Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine();
                throw ex;
            }
        }
        public async Task CreateSchemas(List <SchemaMigrationItemViewModel> schemaItems)
        {
            ActionOnSchemas      action            = new ActionOnSchemas();
            List <SchemaDetails> schemaDetailsList = new List <SchemaDetails>();
            List <SchemaDetails> response          = new List <SchemaDetails>();
            ObservableCollection <SchemaSelectionItemViewModel> originalCollection = this.thisApplicationContext.GetProperty(AppConstants.AllSchemasContextPropertyName) as ObservableCollection <SchemaSelectionItemViewModel>;
            List <SchemaSelectionItemViewModel> orignalList = originalCollection.ToList();
            List <SchemaDetails> originalSchemaDetailsList  = new List <SchemaDetails>();

            foreach (var schemaItem in schemaItems)
            {
                schemaItem.MigrationEntity.isSchemaExtractedFromDb   = false;
                schemaItem.MigrationEntity.errorDetailsForExtraction = "";
                schemaDetailsList.Add(schemaItem.MigrationEntity);
            }
            foreach (var schemaItem in orignalList)
            {
                originalSchemaDetailsList.Add(schemaItem.MigrationEntity);
            }
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    response = action.ExtractSchemasFromDlls(ref schemaDetailsList, Resources.JsonSchemaFilesLocalPath, originalSchemaDetailsList);
                    thisApplicationContext.SetProperty("SchemasToUploadOrder", response);
                    SetExtractionStatus(schemaDetailsList, schemaItems);
                }
                catch (Exception ex)
                {
                    SetExtractionStatus(schemaDetailsList, schemaItems);
                    TraceProvider.WriteLine(string.Format("Schemas Extraction Failed:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                    TraceProvider.WriteLine();
                    throw new Exception(string.Format("Schemas Extraction Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                }
            });
        }
        public JsonSchema.RootObject CreateSchemas(SchemaMigrationItemViewModel schemaItem)
        {
            var    schema     = schemaItem.MigrationEntity;
            string schemaName = schema.fullNameOfSchemaToUpload;

            JsonSchema.RootObject schemaRootObject = new JsonSchema.RootObject();
            try
            {
                string directroyPathForJsonFiles = Resources.JsonSchemaFilesLocalPath;
                string fileName = string.Format(directroyPathForJsonFiles, FileOperations.GetFileName(schemaName), ".json");
                string schemaJsonFileContent = Newtonsoft.Json.JsonConvert.SerializeObject(schemaRootObject);
                FileOperations.CreateFolder(fileName);
                System.IO.File.WriteAllText(fileName, schemaJsonFileContent);
                return(schemaRootObject);
            }
            catch (Exception ex)
            {
                schemaItem.ImportStatus     = MigrationStatus.Failed;
                schemaItem.ImportStatusText = ex.Message;
                TraceProvider.WriteLine(string.Format("Schema Export to Json Failed:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine();
                throw ex;
            }
        }
Example #25
0
        public override void Initialize(IApplicationContext applicationContext)
        {
            base.Initialize(applicationContext);
            pMigrator  = new PartnerMigrator(this.ApplicationContext);
            aMigrator  = new AgreementMigrator(this.ApplicationContext);
            sMigrator  = new SchemaMigrator(this.ApplicationContext);
            mMigrator  = new MapMigrator(this.ApplicationContext);
            c1Migrator = new CerificateMigrator <PartnerMigrationItemViewModel>(this.ApplicationContext);
            c2Migrator = new CerificateMigrator <Certificate>(this.ApplicationContext);

            ExportedItems = new ObservableCollection <ExportedArtifact>();

            selectedSchemas = this.ApplicationContext.GetProperty(AppConstants.SelectedSchemasContextPropertyName) as IEnumerable <SchemaMigrationItemViewModel>;
            importedSchemas = selectedSchemas.Where(item => item.ImportStatus == MigrationStatus.Succeeded);

            selectedMaps = this.ApplicationContext.GetProperty(AppConstants.SelectedMapsContextPropertyName) as IEnumerable <MapMigrationItemViewModel>;
            importedMaps = selectedMaps.Where(item => item.ImportStatus == MigrationStatus.Succeeded);

            selectedPartners = this.ApplicationContext.GetProperty(AppConstants.SelectedPartnersContextPropertyName) as IEnumerable <PartnerMigrationItemViewModel>;
            if (applicationContext.GetProperty("MigrationCriteria").ToString() == "Partner")
            {
                importedPartners = selectedPartners.Where(item => item.ImportStatus == MigrationStatus.Succeeded);
            }
            if (applicationContext.GetProperty("MigrationCriteria").ToString() == "Partner")
            {
                importedPartnersWithCertificates = selectedPartners.Where(item => item.CertificationRequired == true && item.CertificateImportStatus == MigrationStatus.Succeeded);
            }

            selectedAgreements = this.ApplicationContext.GetProperty(AppConstants.SelectedAgreementsContextPropertyName) as IEnumerable <AgreementMigrationItemViewModel>;
            if (applicationContext.GetProperty("MigrationCriteria").ToString() == "Partner")
            {
                importedAgreements = selectedAgreements.Where(item => item.ImportStatus == MigrationStatus.Succeeded);
            }

            otherCerts = this.ApplicationContext.GetProperty("OtherCertificates") as List <Certificate>;

            ExportSchemasFlag      = Convert.ToBoolean(this.ApplicationContext.GetProperty("ExportSchemas"));
            ExportMapsFlag         = Convert.ToBoolean(this.ApplicationContext.GetProperty("ExportMaps"));
            ExportCertificatesFlag = Convert.ToBoolean(this.ApplicationContext.GetProperty("ExportCertificates"));
            ExportPartnersFlag     = Convert.ToBoolean(this.ApplicationContext.GetProperty("ExportPartners"));
            ExportAgreementsFlag   = Convert.ToBoolean(this.ApplicationContext.GetProperty("ExportAgreements"));

            bool consolidateAgreements   = Convert.ToBoolean(this.ApplicationContext.GetProperty(AppConstants.ConsolidationEnabled));
            bool generateMetadataContext = Convert.ToBoolean(this.ApplicationContext.GetProperty(AppConstants.ContextGenerationEnabled));

            if (ExportSchemasFlag || ExportCertificatesFlag || ExportPartnersFlag || ExportAgreementsFlag || ExportMapsFlag)
            {
                if (ExportSchemasFlag)
                {
                    foreach (var item in importedSchemas)
                    {
                        ExportedItems.Add(new ExportedArtifact
                        {
                            ArtifactName     = item.MigrationEntity.fullNameOfSchemaToUpload,
                            ArtifactType     = ArtifactTypes.Schema,
                            ExportStatus     = MigrationStatus.NotStarted,
                            ExportStatusText = null
                        });
                    }
                }
                if (ExportMapsFlag)
                {
                    foreach (var item in importedMaps)
                    {
                        ExportedItems.Add(new ExportedArtifact
                        {
                            ArtifactName     = item.MigrationEntity.fullNameOfMapToUpload,
                            ArtifactType     = ArtifactTypes.Map,
                            ExportStatus     = MigrationStatus.NotStarted,
                            ExportStatusText = null
                        });
                    }
                }
                if (ExportCertificatesFlag)
                {
                    foreach (var item in importedPartnersWithCertificates)
                    {
                        ExportedItems.Add(new ExportedArtifact
                        {
                            ArtifactName     = item.MigrationEntity.CertificateName,
                            ArtifactType     = ArtifactTypes.Certificate,
                            ExportStatus     = MigrationStatus.NotStarted,
                            ExportStatusText = null
                        });
                    }
                    if (otherCerts != null)
                    {
                        otherExtractedCerts = otherCerts.Where(item => item.ImportStatus == MigrationStatus.Succeeded);
                        foreach (var item in otherExtractedCerts)
                        {
                            ExportedItems.Add(new ExportedArtifact
                            {
                                ArtifactName     = item.certificateName,
                                ArtifactType     = ArtifactTypes.Certificate,
                                ExportStatus     = MigrationStatus.NotStarted,
                                ExportStatusText = null
                            });
                        }
                    }
                }
                if (ExportPartnersFlag)
                {
                    foreach (var item in importedPartners)
                    {
                        ExportedItems.Add(new ExportedArtifact
                        {
                            ArtifactName     = item.MigrationEntity.Name,
                            ArtifactType     = ArtifactTypes.Partner,
                            ExportStatus     = MigrationStatus.NotStarted,
                            ExportStatusText = null
                        });
                    }
                }

                if (ExportAgreementsFlag)
                {
                    if (consolidateAgreements)
                    {
                        AuthenticationResult authresult = this.ApplicationContext.GetProperty("IntegrationAccountAuthorization") as AuthenticationResult;
                        List <X12AgreementJson.Rootobject> x12AgreementsInIA = AgreementMigrator.GetAllX12AgreementsInIA(this.ApplicationContext.GetService <IntegrationAccountDetails>(), authresult).Result;
                        this.ApplicationContext.SetProperty("X12AgreementsInIntegrationAccount", x12AgreementsInIA);

                        List <EDIFACTAgreementJson.Rootobject> edifactAgreementsInIA = AgreementMigrator.GetAllEdifactAgreementsInIA(this.ApplicationContext.GetService <IntegrationAccountDetails>(), authresult).Result;
                        this.ApplicationContext.SetProperty("EdifactAgreementsInIntegrationAccount", edifactAgreementsInIA);
                    }
                    foreach (var item in importedAgreements)
                    {
                        if (consolidateAgreements)
                        {
                            TraceProvider.WriteLine(string.Format("Checking {0} for Agreement consolidation..", item.Name));
                            AgreementMigrator agmtMigrator = new AgreementMigrator(this.ApplicationContext);
                            try
                            {
                                agmtMigrator.CheckIfAgreementHasToBeConsolidated(item);
                            }
                            catch (Exception ex)
                            {
                                StatusBarViewModel.StatusInfoType = StatusInfoType.Error;
                                StatusBarViewModel.ShowError(string.Format("Error was encountered during the check for consolidating agreement {0} with IA agreements. Reason: {1}. The agreement will be migrated as such", item.Name, ExceptionHelper.GetExceptionMessage(ex)));
                                TraceProvider.WriteLine(string.Format("Error was encountered during the check for consolidating agreement {0} with IA agreements. Reason: {1}. The agreement will be migrated as such", item.Name, ExceptionHelper.GetExceptionMessage(ex)));
                                TraceProvider.WriteLine();
                            }
                        }
                        ExportedItems.Add(new ExportedArtifact
                        {
                            ArtifactName     = item.Name,
                            ArtifactType     = ArtifactTypes.Agreement,
                            ExportStatus     = MigrationStatus.NotStarted,
                            ExportStatusText = null
                        });
                    }
                }
                countArtifactsMigrated       = 0;
                countTotalArtifactsToMigrate = ExportedItems.Count();
                TotalArtifacts  = countTotalArtifactsToMigrate;
                ProgressVisible = false;
                UpdateProgress();
                ExportArtifacts();
            }
            else
            {
                var lastNavigation = this.ApplicationContext.LastNavigation;
                if (lastNavigation == NavigateAction.Next)
                {
                    this.ApplicationContext.GetService <WizardNavigationViewModel>().MoveToNextStep();
                }
                else if (lastNavigation == NavigateAction.Previous)
                {
                    this.ApplicationContext.GetService <WizardNavigationViewModel>().MoveToPreviousStep();
                }
            }
        }
Example #26
0
        public void CreateCertificates(string certName, string certThumbprint)
        {
            try
            {
                X509Certificate2           partnerCert;
                string                     partnerCertBase64String;
                bool                       certFound  = false;
                X509Certificate2Collection collection = new X509Certificate2Collection();
                //BiztalkServerDetails BizTalkServerDetails = this.thisApplicationContext.GetService<BiztalkServerDetails>();
                //string serverName = BizTalkServerDetails.RemoteServerName;
                //if (BizTalkServerDetails.UseDifferentAccount)
                //{
                //    string domain = BizTalkServerDetails.RemoteDomainName;
                //    string username = BizTalkServerDetails.RemoteUserName;
                //    string password = BizTalkServerDetails.RemoteUserPassword;
                //    using (UserImpersonation user = new UserImpersonation(username, domain, password))
                //    {
                //        if (user.ImpersonateValidUser())
                //        {
                //collection = GetCertificate(certThumbprint, serverName);
                //if (collection.Count == 0)
                //{
                //    certFound = false;
                //}
                //else
                //{
                //    certFound = true;
                //}
                //}
                //else
                //{
                //    throw new Exception(string.Format(@"Failed to read Certificates from the Server {0}\{1}. Invalid Credentails used to read Certificates.", domain, username));
                //}
                // }
                // }
                //else
                //{
                string serverName = System.Environment.MachineName;
                collection = GetCertificate(certThumbprint, serverName);
                if (collection.Count == 0)
                {
                    certFound = false;
                }
                else
                {
                    certFound = true;
                }
                // }
                if (certFound)
                {
                    partnerCert             = collection[0];
                    partnerCertBase64String = Convert.ToBase64String(partnerCert.GetRawCertData());
                    JsonCertificate.Rootobject certificateRootObject = new JsonCertificate.Rootobject()
                    {
                        name       = FileOperations.GetFileName(certName),
                        properties = new JsonCertificate.Properties()
                        {
                            publicCertificate = partnerCertBase64String,
                            metadata          = GenerateMetadata(certName)
                        }
                    };

                    if (partnerCert.HasPrivateKey)
                    {
                        //CHECK IF IT's EXPORTABLE, and ensure you write traces
                        certificateRootObject.properties.key = new JsonCertificate.Key()
                        {
                            keyName    = "<KeyNameHere>",
                            keyVersion = "<KeyVersionHere>",
                            keyVault   = new JsonCertificate.KeyVault()
                            {
                                id = "<ResourceUriHere>"
                            }
                        };

                        //TODO: Create KeyVault Secret JSON.
                        string keyvaultjson     = this.GetKeyVaultSecretJsonForPrivateKey(partnerCert);
                        string keyvaultfilename = FileOperations.GetKeyVaultJsonFilePath(certName + "Privatekey");
                        FileOperations.CreateFolder(keyvaultfilename);
                        System.IO.File.WriteAllText(keyvaultfilename, keyvaultjson);
                    }
                    string fileName = FileOperations.GetCertificateJsonFilePath(certName);
                    string partnerJsonFileContent = Newtonsoft.Json.JsonConvert.SerializeObject(certificateRootObject);
                    FileOperations.CreateFolder(fileName);
                    System.IO.File.WriteAllText(fileName, partnerJsonFileContent);
                    TraceProvider.WriteLine(string.Format("Certificate {0} for partner has been succesfully exported to Json with Name {1}", certName, FileOperations.GetFileName(certName)));
                }
                else
                {
                    TraceProvider.WriteLine(string.Format("Certificate Export to Json Failed. Reason : Certificate {0} Not Found in LocalCertificate store in Server {1}", certName, serverName));
                    throw new Exception(string.Format("Certificate {0} Not Found in LocalCertificate store in Server {1}", certName, serverName));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #27
0
        public async Task ExportToIA(TEntity item, IntegrationAccountDetails iaDetails)
        {
            this.iaDetails = iaDetails;
            var    serverPartnerItem = item as PartnerMigrationItemViewModel;
            var    certItem          = item as Certificate;
            string certName          = string.Empty;

            if (serverPartnerItem != null)
            {
                certName = serverPartnerItem.MigrationEntity.CertificateName;
            }
            else if (certItem != null)
            {
                certName = certItem.certificateName;
            }
            try
            {
                TraceProvider.WriteLine("Migrating certificate : {0}", certName);
                await Task.Factory.StartNew(() =>
                {
                    try
                    {
                        AuthenticationResult authresult = thisApplicationContext.GetProperty("IntegrationAccountAuthorization") as AuthenticationResult;
                        bool overwrite = Convert.ToBoolean(thisApplicationContext.GetProperty("OverwriteEnabled"));
                        if (!overwrite)
                        {
                            bool exists = CheckIfCertificateExists(certName, this.iaDetails, authresult).Result;
                            if (exists)
                            {
                                SetStatus(item, MigrationStatus.Partial, string.Format("The Certificate {0} already exists on IA with name {1}. Since the Overwrite option was disabled, the certificate was not overwritten.", certName, FileOperations.GetFileName(certName)));
                                TraceProvider.WriteLine(string.Format("The Certificate {0} already exists on IA with name {1}. Since the Overwrite option was disabled, the certificate was not overwritten.", certName, FileOperations.GetFileName(certName)));
                                TraceProvider.WriteLine();
                            }
                            else
                            {
                                CheckIfCertificateIsprivate(item, certName, iaDetails);
                                MigrateToCloudIA(FileOperations.GetCertificateJsonFilePath(certName), FileOperations.GetFileName(certName), item, iaDetails, authresult).Wait();
                                SetStatus(item, MigrationStatus.Succeeded, string.Format("Certificate {0} migrated succesfully", certName));
                                TraceProvider.WriteLine(string.Format("Certificate Migration Successfull: {0}", certName));
                                TraceProvider.WriteLine();
                            }
                        }
                        else
                        {
                            CheckIfCertificateIsprivate(item, certName, iaDetails);
                            MigrateToCloudIA(FileOperations.GetCertificateJsonFilePath(certName), FileOperations.GetFileName(certName), item, iaDetails, authresult).Wait();
                            SetStatus(item, MigrationStatus.Succeeded, string.Format("Certificate {0} migrated succesfully", certName));
                            TraceProvider.WriteLine(string.Format("Certificate Migration Successfull: {0}", certName));
                            TraceProvider.WriteLine();
                        }
                    }
                    catch (Exception)
                    {
                        //throw ex;
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool Validate()
        {
            var statusBarViewModel = this.ApplicationContext.GetService <StatusBarViewModel>();

            Debug.Assert(statusBarViewModel != null, "StatusBarViewModel has not been initialized in application context");
            if (string.IsNullOrWhiteSpace(this.ServerName))
            {
                statusBarViewModel.ShowError(Resources.ServerNameValidationError);
                return(false);
            }
            else if (string.IsNullOrWhiteSpace(this.DatabaseName))
            {
                statusBarViewModel.ShowError(Resources.DatabaseNameValidationError);
                return(false);
            }
            else if (!this.IsIntegratedSecurity)
            {
                if (string.IsNullOrWhiteSpace(this.UserName))
                {
                    statusBarViewModel.ShowError(Resources.UserIdValidationError);
                    return(false);
                }
                else if (string.IsNullOrWhiteSpace(this.Password))
                {
                    statusBarViewModel.ShowError(Resources.PasswordValidationError);
                    return(false);
                }
            }
            //else if (string.IsNullOrWhiteSpace(this.RemoteServerName))
            //{
            //    statusBarViewModel.ShowError(string.Format(Resources.RemoteValidationError, "Biztalk Server Name"));
            //    return false;
            //}
            //else if (UseDifferentAccount)
            //{
            //    if (string.IsNullOrWhiteSpace(this.RemoteDomainName))
            //    {
            //        statusBarViewModel.ShowError(string.Format(Resources.RemoteValidationError, "Domain"));
            //        return false;
            //    }
            //    else if (string.IsNullOrWhiteSpace(this.RemoteUserName))
            //    {
            //        statusBarViewModel.ShowError(string.Format(Resources.RemoteValidationError, "Biztalk Server"));
            //        return false;
            //    }
            //    else if (string.IsNullOrWhiteSpace(this.RemoteUserPassword))
            //    {
            //        statusBarViewModel.ShowError(string.Format(Resources.RemoteValidationError, "Biztalk Server"));
            //        return false;
            //    }
            //}
            var bizTalkManagementDbDetails = ApplicationContext.GetService <BizTalkManagementDBDetails>();
            SqlConnectionStringBuilder builder;

            if (this.IsIntegratedSecurity)
            {
                builder = new SqlConnectionStringBuilder
                {
                    InitialCatalog = bizTalkManagementDbDetails.DatabaseName,
                    //MultipleActiveResultSets = true,
                    DataSource         = bizTalkManagementDbDetails.ServerName,
                    IntegratedSecurity = bizTalkManagementDbDetails.IsIntegratedSecurity,
                };
            }
            else
            {
                builder = new SqlConnectionStringBuilder
                {
                    InitialCatalog = bizTalkManagementDbDetails.DatabaseName,
                    //MultipleActiveResultSets = true,
                    DataSource = bizTalkManagementDbDetails.ServerName,
                    UserID     = bizTalkManagementDbDetails.UserName,
                    Password   = bizTalkManagementDbDetails.Password
                };
            }

            using (SqlConnection conn = new SqlConnection(builder.ConnectionString))
            {
                try
                {
                    conn.Open();
                    this.ApplicationContext.SetProperty("DatabaseConnectionString", builder.ConnectionString);
                }
                catch (SqlException ex)
                {
                    TraceProvider.WriteLine(ExceptionHelper.GetExceptionMessage(ex));
                    statusBarViewModel.ShowError(ExceptionHelper.GetExceptionMessage(ex));
                    return(false);
                }
            }
            if (!string.IsNullOrWhiteSpace(this.DatabaseName))
            {
                Microsoft.Windows.Azure.BizTalkService.ClientTools.TpmMigration.Properties.Settings.Default.DatabaseName = this.DatabaseName;
            }
            if (!string.IsNullOrWhiteSpace(this.ServerName))
            {
                Microsoft.Windows.Azure.BizTalkService.ClientTools.TpmMigration.Properties.Settings.Default.ServerName = this.ServerName;
            }
            if (!string.IsNullOrWhiteSpace(this.DatabaseName))
            {
                Microsoft.Windows.Azure.BizTalkService.ClientTools.TpmMigration.Properties.Settings.Default.DatabaseName = this.DatabaseName;
            }
            //if (!string.IsNullOrWhiteSpace(this.RemoteServerName))
            //{
            //    Microsoft.Windows.Azure.BizTalkService.ClientTools.TpmMigration.Properties.Settings.Default.RemoteServerName = this.RemoteServerName;
            //}
            //if (!string.IsNullOrWhiteSpace(this.RemoteDomainName))
            //{
            //    Microsoft.Windows.Azure.BizTalkService.ClientTools.TpmMigration.Properties.Settings.Default.RemoteDomainName = this.RemoteDomainName;

            //}
            //if (!string.IsNullOrWhiteSpace(this.RemoteUserName))
            //{
            //    Microsoft.Windows.Azure.BizTalkService.ClientTools.TpmMigration.Properties.Settings.Default.RemoteUserName = this.RemoteUserName;
            //}
            Microsoft.Windows.Azure.BizTalkService.ClientTools.TpmMigration.Properties.Settings.Default.Save();
            return(true);
        }
        public JsonPartner.Rootobject CreatePartners(PartnerMigrationItemViewModel partnerItem)
        {
            var    partner     = partnerItem.MigrationEntity;
            string partnerName = partner.Name;

            JsonPartner.Rootobject partnerRootObject = new JsonPartner.Rootobject();
            #region Certificates
            try
            {
                if (partner.CertificateName != null && partner.CertificateThumbprint != null)
                {
                    try
                    {
                        certificateRequired = true;
                        CerificateMigrator <PartnerMigrationItemViewModel> cMigrator = new CerificateMigrator <PartnerMigrationItemViewModel>(thisApplicationContext);
                        cMigrator.CreateCertificates(partner.CertificateName, partner.CertificateThumbprint);
                        succesfullCertificateImport = MigrationStatus.Succeeded;
                    }
                    catch (Exception)
                    {
                        certificateRequired         = true;
                        succesfullCertificateImport = MigrationStatus.Failed;
                    }
                }
                else
                {
                    certificateRequired         = false;
                    succesfullCertificateImport = MigrationStatus.NotStarted;
                    TraceProvider.WriteLine(string.Format("No certificate is configured with the Partner"));
                }
            }
            catch (Exception ex)
            {
                certificateRequired         = true;
                succesfullCertificateImport = MigrationStatus.Failed;
                TraceProvider.WriteLine(string.Format("Certificate Export to Json Failed:{0}", ExceptionHelper.GetExceptionMessage(ex)));
            }
            #endregion

            #region Partner
            try
            {
                var businessProfile = partner.GetBusinessProfiles().ToList <Server.BusinessProfile>();
                List <Microsoft.BizTalk.B2B.PartnerManagement.BusinessIdentity> businessIdentities = new List <Microsoft.BizTalk.B2B.PartnerManagement.BusinessIdentity>();

                foreach (var item in businessProfile)
                {
                    businessIdentities.AddRange(item.GetBusinessIdentities().ToList());
                }

                partnerRootObject = new JsonPartner.Rootobject()
                {
                    id         = "",
                    name       = FileOperations.GetFileName(partnerName),
                    type       = Resources.JsonPartnerType,
                    properties = new JsonPartner.Properties()
                    {
                        partnerType = Resources.JsonPartnerTypeB2B,
                        content     = new JsonPartner.Content()
                        {
                            b2b = new JsonPartner.B2b()
                            {
                                businessIdentities = (businessIdentities.Select(delegate(BizTalk.B2B.PartnerManagement.BusinessIdentity bi)
                                {
                                    return(new JsonPartner.Businessidentity()
                                    {
                                        qualifier = ((Microsoft.BizTalk.B2B.PartnerManagement.QualifierIdentity)bi).Qualifier,
                                        value = ((Microsoft.BizTalk.B2B.PartnerManagement.QualifierIdentity)bi).Value
                                    });
                                }
                                                                                )).ToArray()
                            }
                        },
                        createdTime = DateTime.Now,
                        changedTime = DateTime.Now,
                        metadata    = GenerateMetadata(partnerName)
                    }
                };
                string directroyPathForJsonFiles = Resources.JsonPartnerFilesLocalPath;
                string fileName = string.Format(directroyPathForJsonFiles, FileOperations.GetFileName(partnerName), ".json");
                string partnerJsonFileContent = Newtonsoft.Json.JsonConvert.SerializeObject(partnerRootObject);
                FileOperations.CreateFolder(fileName);
                System.IO.File.WriteAllText(fileName, partnerJsonFileContent);
                return(partnerRootObject);
            }
            catch (Exception ex)
            {
                partnerItem.ImportStatus     = MigrationStatus.Failed;
                partnerItem.ImportStatusText = ex.Message;
                TraceProvider.WriteLine(string.Format("Partner Export to Json Failed:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine();
                throw ex;
            }
            #endregion
        }
        public async Task <HttpResponseMessage> MigrateToCloudIAPartner(string filePath, string name, PartnerMigrationItemViewModel serverPartnerItem, IntegrationAccountDetails iaDetails, AuthenticationResult authResult)
        {
            try
            {
                IntegrationAccountContext sclient = new IntegrationAccountContext();
                try
                {
                    List <KeyValuePair <string, string> > partnerIdentities = new List <KeyValuePair <string, string> >();
                    var    partnerInIA      = sclient.GetArtifactsFromIA(UrlHelper.GetPartnerUrl(name, iaDetails), authResult);
                    string responseAsString = await partnerInIA.Content.ReadAsStringAsync();

                    JObject responseAsJObject = JsonConvert.DeserializeObject <JObject>(responseAsString);
                    var     partner           = responseAsJObject;
                    if (partner["properties"] != null && partner["properties"]["content"] != null && partner["properties"]["content"]["b2b"] != null && partner["properties"]["content"]["b2b"]["businessIdentities"] != null)
                    {
                        foreach (var identity in partner["properties"]["content"]["b2b"]["businessIdentities"])
                        {
                            if (identity["qualifier"] != null && identity["value"] != null)
                            {
                                KeyValuePair <string, string> kvpair = new KeyValuePair <string, string>(identity["qualifier"].ToString(), identity["value"].ToString());
                                if (!partnerIdentities.Contains(kvpair))
                                {
                                    partnerIdentities.Add(kvpair);
                                }
                            }
                        }
                    }
                    var partnersFromLocalFile = File.ReadAllText(filePath);
                    var partnerContent        = JsonConvert.DeserializeObject <JsonPartner.Rootobject>(partnersFromLocalFile);
                    var partnerIdentityDict   = partnerContent.properties.content.b2b.businessIdentities.ToDictionary(xc => new KeyValuePair <string, string>(xc.qualifier, xc.value), xc => xc.value);
                    var partnerIdentityList   = partnerContent.properties.content.b2b.businessIdentities.ToList();
                    foreach (var identity in partnerIdentities)
                    {
                        if (!partnerIdentityDict.ContainsKey(identity))
                        {
                            partnerIdentityDict.Add(identity, identity.Value);
                            partnerIdentityList.Add(new JsonPartner.Businessidentity {
                                qualifier = identity.Key, value = identity.Value
                            });
                        }
                    }
                    partnerContent.properties.content.b2b.businessIdentities = partnerIdentityList.ToArray();
                    var finalcontent = JsonConvert.SerializeObject(partnerContent);
                    File.WriteAllText(filePath, finalcontent);
                }
                catch (Exception)
                {
                    //do nothing
                }
                var x = await sclient.LAIntegrationFromFile(UrlHelper.GetPartnerUrl(name, iaDetails), filePath, authResult);

                return(x);
            }
            catch (Exception ex)
            {
                serverPartnerItem.ExportStatus     = MigrationStatus.Failed;
                serverPartnerItem.ExportStatusText = ex.Message;
                TraceProvider.WriteLine(string.Format("Partner Migration Failed. Reason:{0}", ExceptionHelper.GetExceptionMessage(ex)));
                TraceProvider.WriteLine();
                throw ex;
            }
        }