static void Main(string[] args) { // Determine the system connectivity mode based on the command line // arguments: -http, -tcp or -auto (defaults to auto) ServiceBusEnvironment.SystemConnectivity.Mode = GetConnectivityMode(args); string serviceNamespace = ConfigurationManager.AppSettings["General.SBServiceNameSpace"]; string issuerName = ConfigurationManager.AppSettings["General.SBIssuerName"]; string issuerSecret = EncryptionUtility.Decrypt(ConfigurationManager.AppSettings["General.SBIssuerSecret"], ConfigurationManager.AppSettings["General.EncryptionThumbPrint"]); // create the service URI based on the service namespace Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SharePointProvisioning"); // create the credentials object for the endpoint TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior(); sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret); // create the service host reading the configuration ServiceHost host = new ServiceHost(typeof(SharePointProvisioning), address); // create the ServiceRegistrySettings behavior for the endpoint IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public); // add the Service Bus credentials to all endpoints specified in configuration foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { endpoint.Behaviors.Add(serviceRegistrySettings); endpoint.Behaviors.Add(sharedSecretServiceBusCredential); } // open the service host.OpenTimeout = TimeSpan.FromMinutes(15); host.CloseTimeout = TimeSpan.FromMinutes(15); host.Open(); Console.WriteLine("Service address: " + address); Console.WriteLine("Press [Enter] to exit"); Console.ReadLine(); // close the service host.Close(); }
public void OnBuildCreated(NukeBuild build, IReadOnlyCollection <ExecutableTarget> executableTargets) { // TODO: probably remove if (!Directory.Exists(Constants.GetNukeDirectory(NukeBuild.RootDirectory))) { return; } var parameterMembers = ValueInjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: true); var passwords = new Dictionary <string, string>(); IEnumerable <string> ConvertToArguments(string profile, string name, string[] values) { var member = parameterMembers.SingleOrDefault(x => ParameterService.GetParameterMemberName(x).EqualsOrdinalIgnoreCase(name)); var scalarType = member?.GetMemberType().GetScalarType(); var mustDecrypt = (member?.HasCustomAttribute <SecretAttribute>() ?? false) && !BuildServerConfigurationGeneration.IsActive; var decryptedValues = values.Select(x => mustDecrypt ? DecryptValue(profile, name, x) : x); var convertedValues = decryptedValues.Select(x => ConvertValue(scalarType, x)).ToList(); Log.Verbose("Passing value for {Member} ({Value})", member?.GetDisplayName() ?? "<unresolved>", !mustDecrypt ? convertedValues.JoinComma() : "secret"); return(new[] { $"--{ParameterService.GetParameterDashedName(name)}" }.Concat(convertedValues)); } string DecryptValue(string profile, string name, string value) => EncryptionUtility.Decrypt( value, passwords[profile] = passwords.GetValueOrDefault(profile) ?? EncryptionUtility.GetPassword(profile), name); // TODO: Abstract AbsolutePath/Solution/Project etc. string ConvertValue(Type scalarType, string value) => scalarType == typeof(AbsolutePath) || typeof(Solution).IsAssignableFrom(scalarType) || scalarType == typeof(Project) ? EnvironmentInfo.WorkingDirectory.GetUnixRelativePathTo(NukeBuild.RootDirectory / value) : value; var arguments = GetParameters().SelectMany(x => ConvertToArguments(x.Profile, x.Name, x.Values)).ToArray(); ParameterService.Instance.ArgumentsFromFilesService = new ParameterService(() => arguments, () => throw new NotSupportedException()); }
public void Encrypt_Then_Decrypt_Result_Matches_Input() { var value = "This is some text that should be encrypted then decrypted and still come out the same."; var certificate = EncryptionUtility .FindCertificates(x => HasPrivateKey(x) && HasPublicKey(x)) .FirstOrDefault(); if (certificate == null) { Assert.Inconclusive("Unable to find a certificate suitable to preform the test."); } var encrypted = EncryptionUtility.Encrypt(value, certificate); var decrypted = EncryptionUtility.Decrypt(encrypted); Assert.AreEqual(value, decrypted); }
private ComposerCookieDto UnprotectV1(string base64) { ComposerCookieDto dto; try { var json = EncryptionUtility.Decrypt(base64); dto = JsonConvert.DeserializeObject <ComposerCookieDto>(json, _jsonSettings); } catch (Exception ex) { var errorMessage = "Either someone tampered with his cookie or the encryption method changed (machine key changed?) or the Deserialize changed"; Log.ErrorException(errorMessage, ex); dto = JsonConvert.DeserializeObject <ComposerCookieDto>("{}"); } return(dto); }
public void Encrypt_With_No_Private_Key_Then_Decrypt_Throws_InvalidOperationException() { var value = "This is some text that should be encrypted then decrypted and still come out the same."; var certificate = EncryptionUtility .FindCertificates(x => !HasPrivateKey(x) && HasPublicKey(x)) // Make sure there is no other certificate with this public key and a private key as well .FirstOrDefault(x => !HasPrivateKey(EncryptionUtility.FindCertificateByPublicKey(x.GetPublicKey()))); if (certificate == null) { Assert.Inconclusive("Unable to find a certificate suitable to preform the test."); } var encrypted = EncryptionUtility.Encrypt(value, certificate); var decrypted = EncryptionUtility.Decrypt(encrypted); Assert.AreEqual(value, decrypted); }
public void OnBuildCreated(NukeBuild build, IReadOnlyCollection <ExecutableTarget> executableTargets) { // TODO: probably remove if (!Directory.Exists(Constants.GetNukeDirectory(NukeBuild.RootDirectory))) { return; } var parameterMembers = ValueInjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: true); var passwords = new Dictionary <string, byte[]>(); IEnumerable <string> ConvertToArguments(string profile, string name, string[] values) { var member = parameterMembers.SingleOrDefault(x => x.Name.EqualsOrdinalIgnoreCase(name)); var scalarType = member?.GetMemberType().GetScalarType(); var mustDecrypt = (member?.HasCustomAttribute <SecretAttribute>() ?? false) && !GenerationMode; var decryptedValues = values.Select(x => mustDecrypt ? DecryptValue(profile, name, x) : x); var convertedValues = decryptedValues.Select(x => ConvertValue(scalarType, x)); Logger.Trace($"Passing argument for '{name}'{(member != null ? $" on '{member.DeclaringType.NotNull().Name}'" : string.Empty)}."); return(new[] { $"--{ParameterService.GetParameterDashedName(name)}" }.Concat(convertedValues)); } string DecryptValue(string profile, string name, string value) => EncryptionUtility.Decrypt( value, passwords[profile] = passwords.GetValueOrDefault(profile) ?? Encoding.UTF8.GetBytes(EncryptionUtility.GetPassword(profile)), name); // TODO: Abstract AbsolutePath/Solution/Project etc. string ConvertValue(Type scalarType, string value) => scalarType == typeof(AbsolutePath) || typeof(Solution).IsAssignableFrom(scalarType) || scalarType == typeof(Project) ? EnvironmentInfo.WorkingDirectory.GetUnixRelativePathTo(NukeBuild.RootDirectory / value) : value; var arguments = GetParameters().SelectMany(x => ConvertToArguments(x.Profile, x.Name, x.Values)).ToArray(); ParameterService.Instance.ArgumentsFromFilesService = new ParameterService(() => arguments, () => throw new NotSupportedException()); }
public void CreateSiteCollectionOnPremises(Contract.SharePointProvisioningData sharePointProvisioningData) { //On-Prem settings string generalOnPremUserName = GetConfiguration("General.OnPremUserName"); string generalOnPremUserPassword = EncryptionUtility.Decrypt(GetConfiguration("General.OnPremUserPassword"), GetConfiguration("General.EncryptionThumbPrint")); string generalOnPremUserDomain = GetConfiguration("General.OnPremUserDomain"); string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication"); SiteManager.SiteData siteData = new SiteManager.SiteData(); siteData.Url = sharePointProvisioningData.Url.Substring(sharePointProvisioningData.Url.IndexOf("/sites")); siteData.Title = sharePointProvisioningData.Title; siteData.LcId = sharePointProvisioningData.Lcid.ToString(); siteData.OwnerLogin = GetOwnerLogin(sharePointProvisioningData, generalOnPremUserDomain); siteData.SecondaryContactLogin = string.Format(@"{0}\{1}", generalOnPremUserDomain, generalOnPremUserName); siteData.WebTemplate = sharePointProvisioningData.Template; using (SiteManager.SiteManagerClient siteManager = GetSiteManagerClient(generalOnPremWebApplication, generalOnPremUserName, generalOnPremUserPassword, generalOnPremUserDomain)) { siteManager.CreateSiteCollection(siteData); } }
private TestCookieDto UnprotectV1(string base64) { TestCookieDto dto; try { var json = EncryptionUtility.Decrypt(base64); //Deserialize dto = JsonConvert.DeserializeObject <TestCookieDto>(json, _jsonSettings); } catch (Exception) { //Eiher someone tampered with his cookie //Or the Encryption method changed (machine key changed?) //Or the Deserialize changed dto = JsonConvert.DeserializeObject <TestCookieDto>("{}"); } return(dto); }
public ActionResult ConfirmEmail(string validateToken) { EmailConfirmation emailconf = new EmailConfirmation(); try { if (Request.IsAuthenticated) { var username = User.Identity.Name; string decryptedEmail = EncryptionUtility.Decrypt(validateToken); emailconf.Email = decryptedEmail; using (PnPTestAutomationEntities dbContext = new PnPTestAutomationEntities()) { var user = dbContext.UsersSets.FirstOrDefault( u => u.Email.Equals(decryptedEmail, StringComparison.InvariantCultureIgnoreCase) && u.UPN.Equals(username, StringComparison.InvariantCultureIgnoreCase)); if (user != null) { user.IsEmailVerified = true; user.SendTestResults = true; dbContext.SaveChanges(); emailconf.IsEmailVerified = true; } } } else { HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/Usersettings/ConfirmEmail/" + validateToken }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } catch (Exception ex) { throw; } return(View(emailconf)); }
/// <summary> /// Gets the original token data. /// </summary> /// <param name="token">Encrypted token.</param> /// <returns></returns> public static SharedWishListToken DecryptToken(string token) { if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentException(ArgumentNullMessageFormatter.FormatErrorMessage("token"), "token"); } if (!token.IsBase64String()) { return(null); } var tokenAsBytes = Convert.FromBase64String(token); var encryptedToken = System.Text.Encoding.ASCII.GetString(tokenAsBytes); var decryptor = new EncryptionUtility(); var rawToken = decryptor.Decrypt(encryptedToken); var splittedTokens = rawToken.Split(new[] { TokenSeparator }, 2, StringSplitOptions.None); //Invalid token. if (splittedTokens.Length != 2) { return(null); } Guid customerId; if (Guid.TryParse(splittedTokens[0], out customerId)) { return(new SharedWishListToken { CustomerId = customerId, Scope = splittedTokens[1] }); } return(null); }
public string GetNextSiteCollectionUrl(ClientContext cc, Web web, string siteDirectoryUrl, string siteDirectoryListName, string baseSiteUrl) { int lastNumber = GetLastSiteCollectionNumber(cc, web, siteDirectoryUrl, siteDirectoryListName); lastNumber++; string nextSiteName = DateTime.Now.ToString("yyyy") + String.Format("{0:0000}", lastNumber); string nextUrl = String.Format("{0}/sites/{1}", baseSiteUrl, nextSiteName); string generalOnPremUserName = GetConfiguration("General.OnPremUserName"); string generalOnPremUserPassword = EncryptionUtility.Decrypt(GetConfiguration("General.OnPremUserPassword"), GetConfiguration("General.EncryptionThumbPrint")); string generalOnPremUserDomain = GetConfiguration("General.OnPremUserDomain"); string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication"); SiteManager.SiteData[] onPremSiteCollectionList = null; using (SiteManager.SiteManagerClient siteManager = GetSiteManagerClient(generalOnPremWebApplication, generalOnPremUserName, generalOnPremUserPassword, generalOnPremUserDomain)) { onPremSiteCollectionList = siteManager.ListSiteCollections(); } bool validUrl = false; while (!validUrl) { if (!IsSiteExisted(nextUrl, onPremSiteCollectionList)) { validUrl = true; } else { Thread.Sleep(500); lastNumber++; nextSiteName = DateTime.Now.ToString("yyyy") + String.Format("{0:0000}", lastNumber); nextUrl = String.Format("{0}/sites/{1}", baseSiteUrl, nextSiteName); } } return(nextUrl); }
/// <summary> /// Initializes the customer identifier. /// </summary> private void InitializeCustomerId() { if (!_customerId.HasValue) { //First attempt, lazy load from cookie var dto = CookieAccessor.Read(); if (dto.EncryptedCustomerId != null) { _customerId = new Guid(EncryptionUtility.Decrypt(dto.EncryptedCustomerId)); } else { //Second attempt, create a new customerId _customerId = Guid.NewGuid(); _isGuest = true; //Store it in cookie for later dto.EncryptedCustomerId = EncryptionUtility.Encrypt(_customerId.ToString()); dto.IsGuest = _isGuest; CookieAccessor.Write(dto); } } }
private Response Refresh(XDocument configDoc, string tableName) { Response response = new Response(); try { _dataDictionary = new library.DataDictionary(); XElement config = configDoc.Element("configuration"); SQLBuilder sqlBuilder; // // Parse project assignments // Dictionary <string, string> projectAssignments = new Dictionary <string, string>(); IEnumerable <XElement> projectAssignmentElts = config.Element("assignments").Elements("assignment"); if (projectAssignmentElts != null && projectAssignmentElts.Count() > 0) { foreach (XElement assignment in projectAssignmentElts) { string name = assignment.Attribute("name").Value; string value = assignment.Attribute("value").Value; if (name.StartsWith("@") && value.Length > 0) { projectAssignments[name] = value; } } } // // Parse project text replacements // Dictionary <string, string> projectReplacements = new Dictionary <string, string>(); IEnumerable <XElement> projectReplacementElts = config.Element("replacements").Elements("replacement"); if (projectReplacementElts != null && projectReplacementElts.Count() > 0) { foreach (XElement replacement in projectReplacementElts) { string placeHolder = replacement.Attribute("placeHolder").Value; string name = replacement.Attribute("name").Value; string value = replacement.Attribute("value").Value; if (placeHolder == string.Empty || name == string.Empty || value == string.Empty) { continue; } projectReplacements[placeHolder[0] + name + placeHolder[1]] = value; } } // // Get query elements // IEnumerable <XElement> queryElts = config.Elements("query"); DBType siteDbType = Utility.GetDBType(_siteConnStr); DataTable siteSchemaResult = DBManager.Instance.ExecuteQuery(_siteConnStr, Constants.ORACLE_GET_CURRENT_SCHEMA); string siteSchema = siteSchemaResult.Rows[0][0].ToString(); // // Process !SiteData query // XElement siteQueryElt = (from query in queryElts where query.Attribute("name").Value == Constants.SITE_DATA_QUERY select query).First(); Dictionary <string, string> siteSchemaMap = new Dictionary <string, string>(); siteSchemaMap["SITE"] = siteSchema; sqlBuilder = new SQLBuilder(siteDbType, siteQueryElt, siteSchemaMap, projectAssignments, projectReplacements); string siteSelectQuery = sqlBuilder.Build(SQLCommand.SELECT); DataTable siteInfo = DBManager.Instance.ExecuteQuery(_siteConnStr, siteSelectQuery); // // Get actual schemas from !SiteData query // Dictionary <string, string> schemaMap = new Dictionary <string, string>(); if (siteInfo != null && siteInfo.Rows.Count > 0) { foreach (DataRow row in siteInfo.Rows) { schemaMap[row["SP_SCHEMA_TYPE"].ToString()] = row["USERNAME"].ToString(); } } // // Process other queries // if (string.IsNullOrEmpty(tableName)) { queryElts = from query in queryElts where query.Attribute("name").Value != Constants.TEMPLATE_QUERY && query.Attribute("name").Value != Constants.SITE_DATA_QUERY select query; } else { queryElts = from query in queryElts where query.Attribute("name").Value != Constants.TEMPLATE_QUERY && query.Attribute("name").Value != Constants.SITE_DATA_QUERY && query.Attribute("destination").Value.ToUpper() == tableName.ToUpper() select query; } DBType stagingDbType = Utility.GetDBType(_stagingConnStr); // NOTE - although it is possible to make use of an INTO clause to create a selection query that will // also automatically create the destination table, this has limitations, the most serious of which is // it is not safe to assume that the Source DB and Staging DB have the same security requirements. Instead, // we will always assume that security is separate for these two databases and that the connection strings for the // Source and Staging connections provide this information for each individual location. We also cannot assume that // the specified credentials have the power to create a Linked Server connection or that both SQL Server instances // allow ad hoc (OpenDataSource) queries. Instead, the provided credentials are used to copy the data to the // local machine and then bulk copied out to the staging server, bypassing the need for a more sophisticated security // check/edit) DBType plantDbType = Utility.GetDBType(_plantSchemaConnStr); if (plantDbType == DBType.ORACLE) { string plantDictConnStr = _settings[Constants.SPPID_PLANT_DICTIONARY]; if (Utility.IsBase64Encoded(plantDictConnStr)) { plantDictConnStr = EncryptionUtility.Decrypt(plantDictConnStr); } string pidSchemaConnStr = _settings[Constants.SPPID_PID_SCHEMA]; if (Utility.IsBase64Encoded(pidSchemaConnStr)) { pidSchemaConnStr = EncryptionUtility.Decrypt(pidSchemaConnStr); } string pidDictConnStr = _settings[Constants.SPPID_PID_DICTIONARY]; if (Utility.IsBase64Encoded(pidDictConnStr)) { pidDictConnStr = EncryptionUtility.Decrypt(pidDictConnStr); } _workingSet = new WorkingSet(_plantSchemaConnStr, plantDictConnStr, pidSchemaConnStr, pidDictConnStr); } else if (plantDbType == DBType.SQLServer) { _workingSet = new WorkingSet(_plantSchemaConnStr); } else { throw new Exception("SPPID DB type not supported."); } _workingSet.GrantPrivilege("SELECT"); foreach (XElement queryElt in queryElts) { sqlBuilder = new SQLBuilder(stagingDbType, queryElt, schemaMap, projectAssignments, projectReplacements, true); response.StatusList.Add(new Status() { Messages = new Messages() { "Query [" + queryElt.Attribute("name").Value + "] processed." } }); // // Delete existing staging table // string stagingTableName = queryElt.Attribute("destination").Value; string deleteQuery = string.Format(Constants.SQLSERVER_DELETE_TEMPLATE, stagingTableName); DBManager.Instance.ExecuteNonQuery(_stagingConnStr, deleteQuery); // // Create new staging table // string createQuery = sqlBuilder.Build(SQLCommand.CREATE); DBManager.Instance.ExecuteNonQuery(_stagingConnStr, createQuery); response.StatusList.Add(new Status() { Messages = new Messages() { "Staging table [" + stagingTableName + "] created." } }); // // Fetch data // string selectQuery = sqlBuilder.Build(SQLCommand.SELECT); DataTable result = DBManager.Instance.ExecuteQuery(_plantSchemaConnStr, selectQuery); response.StatusList.Add(new Status() { Messages = new Messages() { "New data fetched." } }); // // Bulk copy data to staging table // SqlBulkCopy bulkCopy = new SqlBulkCopy(_stagingConnStr); bulkCopy.DestinationTableName = stagingTableName; bulkCopy.WriteToServer(result); response.StatusList.Add(new Status() { Messages = new Messages() { "Data copied to staging table." } }); // // Add to data dictionary // DataObject objDef = new DataObject() { tableName = stagingTableName, objectNamespace = "SPPID", objectName = stagingTableName }; foreach (var pair in sqlBuilder.Keys) { objDef.keyProperties.Add(new KeyProperty() { keyPropertyName = pair.Key }); } foreach (DBField field in sqlBuilder.Fields) { DataProperty dataProperty = new DataProperty() { propertyName = field.Name, columnName = field.Name, dataType = Utility.ResolveDataType(field.DataType), isNullable = field.Nullable, }; if (sqlBuilder.Keys.ContainsKey(field.Name)) { dataProperty.keyType = (sqlBuilder.Keys[field.Name] == KeyType.AUTO) ? library.KeyType.unassigned : library.KeyType.assigned; } objDef.dataProperties.Add(dataProperty); } _dataDictionary.dataObjects.Add(objDef); } _workingSet.RevokePrivilege("SELECT"); } catch (Exception ex) { string error = "Error refreshing [" + tableName + "]: " + ex.Message; response.Level = StatusLevel.Error; response.Messages = new Messages() { error }; _logger.Error(error); } return(response); }
public override bool Execute() { bool processed = false; string generalSiteDirectoryUrl = GetConfiguration("General.SiteDirectoryUrl"); string generalSiteDirectoryListName = GetConfiguration("General.SiteDirectoryListName"); string generalSiteCollectionUrl = GetConfiguration("General.SiteCollectionUrl"); string generalMailSMTPServer = GetConfiguration("General.MailSMTPServer"); string generalMailUser = GetConfiguration("General.MailUser"); string generalMailUserPassword = GetConfiguration("General.MailUserPassword"); string generalMailSiteAvailable = GetConfiguration("General.MailSiteAvailable"); string generalEncryptionThumbPrint = GetConfiguration("General.EncryptionThumbPrint"); //Decrypt mail password generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint); string contosoCollaborationPromotedSiteName = GetConfiguration("ContosoCollaboration.PromotedSiteName"); string contosoCollaborationPromotedSiteUrl = GetConfiguration("ContosoCollaboration.PromotedSiteUrl"); string contosoCollaborationThemeName = GetConfiguration("ContosoCollaboration.ThemeName"); //On-Prem settings string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication"); try { SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager(); //FeatureManager featureManager = new FeatureManager(); //ListManager listManager = new ListManager(); //PageManager pageManager = new PageManager(); //SecurityManager securityManager = new SecurityManager(); //NavigationManager navigationManager = new NavigationManager(); //BrandingManager brandingManager = new BrandingManager(); string tempSharePointUrl = this.SharePointProvisioningData.Url; string siteCollectionUrl = this.CreateOnPremises ? generalOnPremWebApplication : generalSiteCollectionUrl; // issue the final SharePoint url SharePointProvisioningData.Url = this.GetNextSiteCollectionUrl(generalSiteDirectoryUrl, generalSiteDirectoryListName, siteCollectionUrl); //update site directory status siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, tempSharePointUrl, this.SharePointProvisioningData.Url, "Provisioning"); //complete the site data this.SharePointProvisioningData.Template = "STS#0"; this.SharePointProvisioningData.SiteOwner = this.SharePointProvisioningData.Owners[0]; this.SharePointProvisioningData.Lcid = 1033; this.SharePointProvisioningData.TimeZoneId = 3; this.SharePointProvisioningData.StorageMaximumLevel = 100; this.SharePointProvisioningData.StorageWarningLevel = 80; //create the site collection this.AddSiteCollection(this.SharePointProvisioningData); //enable features // Document ID Service (DocID) site collection feature this.CreatedSiteContext.Site.ActivateFeature(new Guid("b50e3104-6812-424f-a011-cc90e6327318")); // Search Server Web Parts and Templates (SearchMaster) site collection feature this.CreatedSiteContext.Site.ActivateFeature(new Guid("9c0834e1-ba47-4d49-812b-7d4fb6fea211")); // Workflows (Workflows) site collection feature this.CreatedSiteContext.Site.ActivateFeature(new Guid("0af5989a-3aea-4519-8ab0-85d91abe39ff")); // Metadata Navigation and Filtering (MetaDataNav) site feature this.CreatedSiteContext.Web.ActivateFeature(new Guid("7201d6a4-a5d3-49a1-8c19-19c4bac6e668")); // Community Site Feature (CommunitySite) site feature this.CreatedSiteContext.Web.ActivateFeature(new Guid("961d6a9c-4388-4cf2-9733-38ee8c89afd4")); // Project Functionality (ProjectFunctionality) site feature this.CreatedSiteContext.Web.ActivateFeature(new Guid("e2f2bb18-891d-4812-97df-c265afdba297")); // Picture library called Media this.CreatedSiteContext.Web.CreateList(Microsoft.SharePoint.Client.ListTemplateType.PictureLibrary, "Media", false); // Promoted Links library called Links this.CreatedSiteContext.Web.CreateList(new Guid("192efa95-e50c-475e-87ab-361cede5dd7f"), 170, "Links", false); // Update existing list settings for the documents library and the blog post library this.CreatedSiteContext.Web.UpdateListVersioning("Documents", true); //Remove the "Project Summary" web part this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Project Summary", "home.aspx"); //Remove the "Get started with your site" web part this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Get started with your site", "home.aspx"); //Remove the "Documents" web part this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Documents", "home.aspx"); //Add links web part to the home page Guid linksID = this.CreatedSiteContext.Web.GetListID("Links"); WebPartEntity promotedLinksWP = new WebPartEntity(); promotedLinksWP.WebPartXml = WpPromotedLinks(linksID, string.Format("{0}{1}/Lists/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "Links"), string.Format("{0}{1}/SitePages/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "home.aspx"), "$Resources:core,linksList"); promotedLinksWP.WebPartIndex = 2; promotedLinksWP.WebPartTitle = "Links"; this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", promotedLinksWP, "home.aspx", 2, 2, false); //Add html to the home page wiki this.CreatedSiteContext.Web.AddHtmlToWikiPage("SitePages", "Hello <strong>SharePoint Conference</strong> from spc403<br/><br/><br/>", "home.aspx", 1, 1); //add additional pages string siteMembersPage = "site members.aspx"; string siteMembersUrl = this.CreatedSiteContext.Web.AddWikiPage("Site Pages", siteMembersPage); this.CreatedSiteContext.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.TwoColumns, siteMembersPage); //Add site members web parts WebPartEntity wpSiteUsers = new WebPartEntity(); wpSiteUsers.WebPartXml = WpSiteUsers("Site owners", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Owners"))); wpSiteUsers.WebPartIndex = 0; wpSiteUsers.WebPartTitle = "Site owners"; this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, false); wpSiteUsers.WebPartXml = WpSiteUsers("Site visitors", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Visitors"))); wpSiteUsers.WebPartIndex = 1; wpSiteUsers.WebPartTitle = "Site visitors"; this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, true); wpSiteUsers.WebPartXml = WpSiteUsers("Site members", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Members"))); wpSiteUsers.WebPartIndex = 0; wpSiteUsers.WebPartTitle = "Site members"; this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 2, false); //Update the quick launch navigation //First delete all quicklaunch entries this.CreatedSiteContext.Web.DeleteAllQuickLaunchNodes(); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,nav_Home", null, "", NavigationType.QuickLaunch); //csomService.AddNavigationNode(this.SiteToProvision, "$Resources:core,BlogQuickLaunchTitle", new Uri(this.BlogSite.Url), "News & Trending", true); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,DiscussionsTab", new Uri(string.Format("{0}/Lists/Community%20Discussion/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch); string notebookPath = string.Format("{0}/SiteAssets/{1} Notebook", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Title); notebookPath = HttpUtility.UrlPathEncode(notebookPath, false).Replace("/", "%2F"); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,SiteNotebookLink", new Uri(string.Format("{0}/_layouts/15/WopiFrame.aspx?sourcedoc={1}&action=editnew", this.SharePointProvisioningData.Url, notebookPath)), "", NavigationType.QuickLaunch); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,taskList", new Uri(string.Format("{0}/Lists/Tasks/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,calendarList", new Uri(string.Format("{0}/Lists/Calendar/calendar.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,shareddocuments_Title_15", new Uri(string.Format("{0}/Shared Documents/Forms/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,linksList", new Uri(string.Format("{0}/Lists/Links/Tiles.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,GrpMedia", new Uri(string.Format("{0}/Media/Forms/Thumbnails.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,Members_QuickLaunch", new Uri(string.Format("{0}/{1}", this.SharePointProvisioningData.Url, siteMembersUrl)), "", NavigationType.QuickLaunch); this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,category_SiteContents", new Uri(string.Format("{0}/_layouts/15/viewlsts.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch); // Insert demo promoted links list item if (contosoCollaborationPromotedSiteName.Length > 0 || contosoCollaborationPromotedSiteUrl.Length > 0) { AddPromotedSiteLink(this.CreatedSiteContext, this.CreatedSiteContext.Web, "Links", contosoCollaborationPromotedSiteName, contosoCollaborationPromotedSiteUrl); } if (!this.CreateOnPremises) { // add owners to site collection administrators List <UserEntity> adminLogins = new List <UserEntity>(); int i = 0; foreach (SharePointUser owner in this.SharePointProvisioningData.Owners) { adminLogins.Add(new UserEntity() { Email = owner.Email, LoginName = owner.Login, Title = owner.Name, }); i++; } Tenant tenant = new Tenant(this.AppOnlyClientContext); tenant.AddAdministrators(adminLogins, new Uri(this.SharePointProvisioningData.Url), true); // Everyone reader this.CreatedSiteContext.Web.AddReaderAccess(); } // Apply themes string themeRoot = Path.Combine(this.AppRootPath, String.Format(@"Themes\{0}", contosoCollaborationThemeName)); string spColorFile = Path.Combine(themeRoot, string.Format("{0}.spcolor", contosoCollaborationThemeName)); string spFontFile = Path.Combine(themeRoot, string.Format("{0}.spfont", contosoCollaborationThemeName)); string backgroundFile = Path.Combine(themeRoot, string.Format("{0}bg.jpg", contosoCollaborationThemeName)); string logoFile = Path.Combine(themeRoot, string.Format("{0}logo.png", contosoCollaborationThemeName)); // Deploy theme files to root web, if they are not there and set it as active theme for the site string themeColorFileString = ""; string themeFontFileString = ""; string themeBackgroundImageString = ""; if (!String.IsNullOrEmpty(themeRoot)) { themeColorFileString = this.CreatedSiteContext.Web.UploadThemeFile(themeRoot).ServerRelativeUrl; } if (!String.IsNullOrEmpty(spColorFile)) { themeFontFileString = this.CreatedSiteContext.Web.UploadThemeFile(spColorFile).ServerRelativeUrl; } if (!String.IsNullOrWhiteSpace(backgroundFile)) { themeBackgroundImageString = this.CreatedSiteContext.Web.UploadThemeFile(backgroundFile).ServerRelativeUrl; } this.CreatedSiteContext.Web.CreateComposedLookByUrl(contosoCollaborationThemeName, themeColorFileString, themeFontFileString, themeBackgroundImageString, String.Empty); this.CreatedSiteContext.Web.SetComposedLookByUrl(contosoCollaborationThemeName); //Seems to be broken at the moment...to be investigated //brandingManager.SetSiteLogo(this.CreatedSiteContext, this.CreatedSiteContext.Web, logoFile); // Update status siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Available"); // Send mail to owners List <String> mailTo = new List <string>(); string ownerNames = ""; string ownerAccounts = ""; foreach (SharePointUser owner in this.SharePointProvisioningData.Owners) { mailTo.Add(owner.Email); if (ownerNames.Length > 0) { ownerNames = ownerNames + ", "; ownerAccounts = ownerAccounts + ", "; } ownerNames = ownerNames + owner.Name; ownerAccounts = ownerAccounts + owner.Login; } // send email to notify the use of successful provisioning string mailBody = String.Format(generalMailSiteAvailable, this.SharePointProvisioningData.Title, this.SharePointProvisioningData.Url, ownerNames, ownerAccounts); MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site is ready to be used", mailBody); } catch (Exception ex) { //log error new SiteDirectoryManager().UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Error during provisioning", ex); } return(processed); }
/// <summary> /// Processes a message from the oauth queue /// </summary> /// <param name="message">Message retrieved from the queue</param> /// <returns>true if ok</returns> private bool ProcessMessageOAuth(string message) { bool processed = true; // first part contains the title, second the site to apply the title on string[] messageParts = message.Split(new string[] { "|" }, StringSplitOptions.None); if (messageParts[0].Length > 0) { ClientContext cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(messageParts[1], RoleEnvironment.GetConfigurationSettingValue("Realm"), RoleEnvironment.GetConfigurationSettingValue("AppId"), EncryptionUtility.Decrypt(RoleEnvironment.GetConfigurationSettingValue("AppSecret"), RoleEnvironment.GetConfigurationSettingValue("ThumbPrint"))); //Update the site title cc.Web.Title = messageParts[0]; cc.Web.Update(); cc.ExecuteQuery(); } return(processed); }
public ActionResult Download(string fileName) { bool isPublished = false; if (db.Articles.SingleOrDefault(a => a.FileName == fileName).StateId == 4) { isPublished = true; } bool advancedUser = false; if (User.IsInRole("Author") || User.IsInRole("MediaManager")) { advancedUser = true; } if (advancedUser == false && isPublished == false) { return(RedirectToAction("Missing")); } else { try { EncryptionUtility utility = new EncryptionUtility(); SymmetricParameters parameters = new SymmetricParameters(); string userId = db.Articles.SingleOrDefault(a => a.FileName == fileName).UserId; // Public and private keys are generated during user registration, stored in UserKey table string publicKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PublicKey; string privateKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PrivateKey; string signature = db.Articles.SingleOrDefault(a => a.FileName == fileName).Signature; // Retrieval Process string filePath = Server.MapPath(@"\Files" + @"\" + fileName); string encryptedFile = utility.ReadFromFile(filePath); // Decryption Process string[] splitString = encryptedFile.Split(new string[] { "#CONTENT#" }, StringSplitOptions.None); string[] keyiv = splitString[0].Split(new string[] { "$KEY$" }, StringSplitOptions.None); string SK = keyiv[0]; string IV = keyiv[1]; string encryptedContent = splitString[1]; parameters.SecretKey = utility.Decrypt(SK, privateKey); parameters.IV = utility.Decrypt(IV, privateKey); //Decrypt file using Secret key and IV byte[] decryptedFile = utility.Decrypt(encryptedContent, parameters); bool verify = utility.VerifySignature(decryptedFile, publicKey, signature); ViewBag.isValid = verify.ToString(); return(File(decryptedFile, System.Net.Mime.MediaTypeNames.Application.Octet, "Article")); } catch { return(RedirectToAction("Missing")); } } }
private void btnDecrypt_Click(object sender, EventArgs e) { txtEncryptedContent.Text = EncryptionUtility.Decrypt(txtTextToEncrypt.Text, txtThumbPrint.Text); }
public override string Transform(string value, string valueName, ICustomAttributeProvider property) { return(value == null ? null : EncryptionUtility.Decrypt(value)); }
private void ProcessSiteRequest() { try { string generalSiteDirectoryUrl = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryUrl"); string generalSiteDirectoryListName = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryListName"); string generalSiteDirectoryProvisioningPage = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryProvisioningPage"); string generalSiteCollectionUrl = RoleEnvironment.GetConfigurationSettingValue("General.SiteCollectionUrl"); string generalMailSMTPServer = RoleEnvironment.GetConfigurationSettingValue("General.MailSMTPServer"); string generalMailUser = RoleEnvironment.GetConfigurationSettingValue("General.MailUser"); string generalMailUserPassword = RoleEnvironment.GetConfigurationSettingValue("General.MailUserPassword"); string generalMailSiteRequested = RoleEnvironment.GetConfigurationSettingValue("General.MailSiteRequested"); string generalEncryptionThumbPrint = RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint"); //Manager initiation SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager(); //Decrypt mail password generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint); // SharePoint context for the host web var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); ClientContext hostWebClientContext = spContext.CreateAppOnlyClientContextForSPHost(); // Object that contains data about the site collection we're gonna provision SharePointProvisioningData siteData = new SharePointProvisioningData(); siteData.Url = String.Format("{0}{1}", generalSiteCollectionUrl, Guid.NewGuid().ToString()); // Deal with the Title siteData.Title = txtTitle.Text; // Deal with the template siteData.Template = drlTemplate.SelectedItem.Value; // Deal with the data classification siteData.DataClassification = drlClassification.SelectedItem.Value; // Deal with the site name (empty for root) siteData.Name = ""; // Deal with the site owners List <SharePointUser> ownersList = JsonUtility.Deserialize <List <SharePointUser> >(hdnAdministrators.Value); SharePointUser[] owners = new SharePointUser[ownersList.Count]; List <String> mailTo = new List <string>(ownersList.Count); string ownerNames = ""; string ownerAccounts = ""; int i = 0; foreach (SharePointUser owner in ownersList) { owner.Login = StripUPN(owner.Login); owners[i] = owner; mailTo.Add(owner.Email); if (ownerNames.Length > 0) { ownerNames = ownerNames + ", "; ownerAccounts = ownerAccounts + ", "; } ownerNames = ownerNames + owner.Name; ownerAccounts = ownerAccounts + owner.Login; i++; } siteData.Owners = owners; #if (DEBUG) //In debug mode have the WCF call ignore certificate errors System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => { return(true); }; #endif // Provision site collection on the using (SharePointProvisioning.SharePointProvisioningServiceClient service = new SharePointProvisioning.SharePointProvisioningServiceClient()) { if (service.ProvisionSiteCollection(siteData)) { string[] ownerLogins = new string[owners.Length]; int j = 0; foreach (SharePointUser owner in owners) { ownerLogins[j] = owner.Login; j++; } siteDirectoryManager.AddSiteDirectoryEntry(hostWebClientContext, hostWebClientContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryProvisioningPage, generalSiteDirectoryListName, siteData.Title, siteData.Url, siteData.Template, ownerLogins); string mailBody = String.Format(generalMailSiteRequested, siteData.Title, ownerNames, ownerAccounts); MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site request has been registered", mailBody); } } if (Page.Request["IsDlg"].Equals("0", StringComparison.InvariantCultureIgnoreCase)) { // redirect to host web home page Response.Redirect(Page.Request["SPHostUrl"]); } else { // refresh the page from which the dialog was opened. Normally this is always the SPHostUrl ClientScript.RegisterStartupScript(typeof(Default), "RedirectToSite", "navigateParent('" + Page.Request["SPHostUrl"] + "');", true); } } catch (Exception ex) { lblErrors.Text = String.Format("Error: {0} \n\r Stacktrace: {1}", ex.Message, ex.StackTrace); } }
private bool Initialize() { _logger.Debug("Initialize ..."); NameValueCollection settings; try { //connect to database and setup config object settings = ConfigurationManager.AppSettings; _agentConnStr = settings.Get("iRINGAgentConnStr"); _agentConnStr = EncryptionUtility.Decrypt(_agentConnStr); _configList.Clear(); string sSql = "select a.job_id,a.is_exchange,a.scope,a.app,a.dataobject,a.xid,a.exchange_url,a.cache_page_size, " + " b.sso_url,b.client_id,b.client_secret,b.access_token,b.app_key,b.grant_type,b.request_timeout, " + " c.schedule_id,c.occurance,c.start_datetime,c.end_datetime,c.status, " + " d.next_start_datetime,d.last_start_datetime,d.active " + " from job a, job_client_info b, schedule c, jobschedule d " + " where a.job_id = b.job_id and a.job_id = d.job_id and c.schedule_id = d.schedule_id "; DataTable agentConfig = DBManager.Instance.ExecuteQuery(_agentConnStr, sSql); if (agentConfig != null && agentConfig.Rows.Count > 0) { foreach (DataRow dataRow in agentConfig.Rows) { try { _configList.Add(new AgentConfig { JobId = dataRow["Job_Id"].ToString(), IsExchange = Convert.ToInt32(dataRow["is_exchange"]), Scope = dataRow["Scope"].ToString(), App = dataRow["App"].ToString(), DataObject = dataRow["DataObject"].ToString(), ExchangeId = dataRow["xid"].ToString(), ExchangeUrl = dataRow["exchange_url"].ToString(), CachePageSize = dataRow["cache_page_size"].ToString(), SsoUrl = dataRow["sso_url"].ToString(), ClientId = dataRow["client_id"].ToString(), ClientSecret = dataRow["client_secret"].ToString(), AccessToken = dataRow["access_token"].ToString(), AppKey = dataRow["app_key"].ToString(), GrantType = dataRow["grant_type"].ToString(), RequestTimeout = Convert.ToInt32(dataRow["request_timeout"]), ScheduleId = dataRow["schedule_id"].ToString(), Occurance = dataRow["occurance"].ToString(), StartDateTime = Convert.ToDateTime(dataRow["start_datetime"]), EndDateTime = Convert.ToDateTime(dataRow["end_datetime"]), Status = dataRow["status"].ToString(), NextStartDateTime = Convert.ToDateTime(dataRow["next_start_datetime"]), LastStartDateTime = Convert.ToDateTime(dataRow["last_start_datetime"]), Active = Convert.ToInt32(dataRow["active"]) }); } catch (Exception ex) { _eventLog1.WriteEntry(string.Format("Error getting configuration data.", ex)); throw ex; } } } } catch (Exception ex) { _eventLog1.WriteEntry(string.Format("Initialization failed: " + ex.Message, ex)); return(false); } _logger.Debug("Successfully retrieved configuration data."); return(true); }
private bool ProcessMessage(string message) { bool processed = true; SharePointProvisioningData sharePointProvisioningData = DeserializeData(message); if (sharePointProvisioningData.DataClassification.Equals("HBI", StringComparison.InvariantCultureIgnoreCase)) { try { // Determine the system connectivity mode based on the command line // arguments: -http, -tcp or -auto (defaults to auto) ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect; string serviceNamespace = RoleEnvironment.GetConfigurationSettingValue("General.SBServiceNameSpace"); string issuerName = RoleEnvironment.GetConfigurationSettingValue("General.SBIssuerName"); string issuerSecret = EncryptionUtility.Decrypt(RoleEnvironment.GetConfigurationSettingValue("General.SBIssuerSecret"), RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint")); // create the service URI based on the service namespace Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SharePointProvisioning"); // create the credentials object for the endpoint TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior(); sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret); // create the channel factory loading the configuration ChannelFactory <ISharePointProvisioningChannel> channelFactory = new ChannelFactory <ISharePointProvisioningChannel>("RelayEndpoint", new EndpointAddress(serviceUri)); // apply the Service Bus credentials channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential); // create and open the client channel ISharePointProvisioningChannel channel = channelFactory.CreateChannel(); channel.Open(); channel.ProvisionSiteCollection(sharePointProvisioningData); channel.Close(); channelFactory.Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); //log error } } else { try { SiteProvisioningBase siteToProvision = null; switch (sharePointProvisioningData.Template) { case SiteProvisioningTypes.ContosoCollaboration: siteToProvision = new ContosoCollaboration(); break; case SiteProvisioningTypes.ContosoProject: siteToProvision = new ContosoProject(); break; } siteToProvision.SharePointProvisioningData = sharePointProvisioningData; HookupAuthentication(siteToProvision); // Provision the site collection processed = siteToProvision.Execute(); } catch (Exception ex) { Debug.WriteLine(ex.Message); //log error } } // always return true to get the item of the queue...no retry mechanism foreseen return(true); }
static bool Initialize(string sequenceName) { _logger.Debug("Initialize ..."); try { #region init proxy info _proxyCredentialToken = ConfigurationManager.AppSettings["ProxyCredentialToken"]; _proxyHost = ConfigurationManager.AppSettings["ProxyHost"]; string proxyPort = ConfigurationManager.AppSettings["ProxyPort"]; int.TryParse(proxyPort, out _proxyPort); #endregion #region init client credentials _ssoURL = ConfigurationManager.AppSettings["SSO_URL"]; _clientId = ConfigurationManager.AppSettings["client_id"]; _clientSecret = ConfigurationManager.AppSettings["client_secret"]; _authType = ConfigurationManager.AppSettings["grant_type"]; string clientKey = ConfigurationManager.AppSettings["client_key"]; if (!string.IsNullOrEmpty(clientKey)) { _clientSecret = EncryptionUtility.Decrypt(_clientSecret, clientKey); } else { _clientSecret = EncryptionUtility.Decrypt(_clientSecret); } #endregion #region init exchange sequence and timeout string configPath = ConfigurationManager.AppSettings["ExchangeConfig"]; if (!File.Exists(configPath)) { _logger.Error("Exchange Configuration not found."); return(false); } ExchangeConfig config = Utility.Read <ExchangeConfig>(configPath, true); foreach (Sequence sequence in config) { if (sequence.Name.ToLower() == sequenceName.ToLower()) { _sequence = sequence; break; } } if (_sequence == null) { _logger.Error("Sequence [" + sequenceName + "] does not exist in exchange configuration."); return(false); } string httpRequestTimeout = ConfigurationManager.AppSettings["RequestTimeout"]; if (!string.IsNullOrWhiteSpace(httpRequestTimeout)) { _requestTimeout = Convert.ToInt32(httpRequestTimeout); } #endregion } catch (Exception ex) { _logger.Error("Initialization failed: " + ex.Message, ex); return(false); } return(true); }
public void ProcessTask(AgentConfig config) { string project = string.Empty; string app = string.Empty; string dataObject = string.Empty; AdapterSettings adapterSettings; NameValueCollection settings; string baseUrl = string.Empty; string scope = string.Empty;; string exchangeId = string.Empty; try { project = config.Scope; //config.Project; app = config.App; dataObject = config.DataObject; baseUrl = config.ExchangeUrl; scope = config.Scope; exchangeId = config.ExchangeId; _ssoURL = config.SsoUrl; _clientId = config.ClientId; _clientSecret = config.ClientSecret; _authType = config.GrantType; _clientSecret = EncryptionUtility.Decrypt(_clientSecret); settings = ConfigurationManager.AppSettings; settings["AppKey"] = config.AppKey; settings["AccessToken"] = config.AccessToken; adapterSettings = new AdapterSettings(); adapterSettings.AppendSettings(settings); Initialize(); string clientToken = GetClientToken(); if (config.IsExchange == 0) { if (!string.IsNullOrEmpty(clientToken)) { _settings["AllowImpersonation"] = "True"; _settings["ImpersonatedUser"] = _clientId; _settings["Authorization"] = clientToken; _settings["ClientToken"] = clientToken; _settings["UserName"] = _clientId; } if (string.IsNullOrEmpty(dataObject)) { RefreshCache(project, app, false); } else { RefreshCache(project, app, dataObject, false); } } else { string url = string.Format("{0}?scope={1}&xid={2}", baseUrl, scope, exchangeId); WebRequest request = CreateWebRequest(url); if (!string.IsNullOrEmpty(clientToken)) { _logger.Info("Use client token."); request.Headers.Add("AuthType", _authType); request.Headers.Add("ClientToken", clientToken); request.Headers.Add("UserName", _clientId); } request.Timeout = _requestTimeout; string responseText = GetResponseText(request); } _logger.Info("Task finished: "); } catch (Exception e) { _logger.Error("Error processing task: " + config.JobId + " " + e.Message); } }
public override bool Execute() { bool processed = false; string generalSiteDirectoryUrl = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryUrl"); string generalSiteDirectoryListName = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryListName"); string generalSiteCollectionUrl = RoleEnvironment.GetConfigurationSettingValue("General.SiteCollectionUrl"); string generalMailSMTPServer = RoleEnvironment.GetConfigurationSettingValue("General.MailSMTPServer"); string generalMailUser = RoleEnvironment.GetConfigurationSettingValue("General.MailUser"); string generalMailUserPassword = RoleEnvironment.GetConfigurationSettingValue("General.MailUserPassword"); string generalMailSiteAvailable = RoleEnvironment.GetConfigurationSettingValue("General.MailSiteAvailable"); string generalEncryptionThumbPrint = RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint"); //Decrypt mail password generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint); //On-Prem settings string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication"); try { SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager(); string tempSharePointUrl = this.SharePointProvisioningData.Url; string siteCollectionUrl = this.CreateOnPremises ? generalOnPremWebApplication : generalSiteCollectionUrl; // issue the final SharePoint url SharePointProvisioningData.Url = this.GetNextSiteCollectionUrl(generalSiteDirectoryUrl, generalSiteDirectoryListName, siteCollectionUrl); //update site directory status siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, tempSharePointUrl, this.SharePointProvisioningData.Url, "Provisioning"); //complete the site data this.SharePointProvisioningData.Template = "PROJECTSITE#0"; this.SharePointProvisioningData.SiteOwner = this.SharePointProvisioningData.Owners[0]; this.SharePointProvisioningData.Lcid = 1033; this.SharePointProvisioningData.TimeZoneId = 3; this.SharePointProvisioningData.StorageMaximumLevel = 100; this.SharePointProvisioningData.StorageWarningLevel = 80; //create the site collection this.AddSiteCollection(this.SharePointProvisioningData); // Update status siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Available"); // Send mail to owners List <String> mailTo = new List <string>(); string ownerNames = ""; string ownerAccounts = ""; foreach (SharePointUser owner in this.SharePointProvisioningData.Owners) { mailTo.Add(owner.Email); if (ownerNames.Length > 0) { ownerNames = ownerNames + ", "; ownerAccounts = ownerAccounts + ", "; } ownerNames = ownerNames + owner.Name; ownerAccounts = ownerAccounts + owner.Login; } // send email to notify the use of successful provisioning string mailBody = String.Format(generalMailSiteAvailable, this.SharePointProvisioningData.Title, this.SharePointProvisioningData.Url, ownerNames, ownerAccounts); MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site is ready to be used", mailBody); } catch (Exception ex) { new SiteDirectoryManager().UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Error during provisioning", ex); } return(processed); }
static void Main(string[] args) { // Determine the system connectivity mode based on the command line // arguments: -http, -tcp or -auto (defaults to auto) ServiceBusEnvironment.SystemConnectivity.Mode = GetConnectivityMode(args); string serviceNamespace = ConfigurationManager.AppSettings["General.SBServiceNameSpace"]; string issuerName = ConfigurationManager.AppSettings["General.SBIssuerName"]; string issuerSecret = EncryptionUtility.Decrypt(ConfigurationManager.AppSettings["SBIssuerSecret"], ConfigurationManager.AppSettings["General.EncryptionThumbPrint"]); // create the service URI based on the service namespace Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SharePointProvisioning"); // create the credentials object for the endpoint TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior(); sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret); // create the channel factory loading the configuration ChannelFactory <ISharePointProvisioningChannel> channelFactory = new ChannelFactory <ISharePointProvisioningChannel>("RelayEndpoint", new EndpointAddress(serviceUri)); // apply the Service Bus credentials channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential); // create and open the client channel ISharePointProvisioningChannel channel = channelFactory.CreateChannel(); channel.Open(); SharePointProvisioningData sharePointProvisioningData = new SharePointProvisioningData(); sharePointProvisioningData.Title = "Test site on-premises"; sharePointProvisioningData.Url = String.Format("{0}{1}", "https://bertonline.sharepoint.com/sites/", Guid.NewGuid().ToString()); sharePointProvisioningData.Template = "ContosoCollaboration"; sharePointProvisioningData.Name = ""; sharePointProvisioningData.DataClassification = "HBI"; SharePointUser[] owners = new SharePointUser[1]; SharePointUser owner = new SharePointUser(); owner.Login = "******"; owner.Name = "Kevin Cook"; owner.Email = "*****@*****.**"; owners[0] = owner; sharePointProvisioningData.Owners = owners; channel.ProvisionSiteCollection(sharePointProvisioningData); //Console.WriteLine("Enter text to echo (or [Enter] to exit):"); //string input = Console.ReadLine(); //while (input != String.Empty) //{ // try // { // Console.WriteLine("Server echoed: {0}", channel.Echo(input)); // } // catch (Exception e) // { // Console.WriteLine("Error: " + e.Message); // } // input = Console.ReadLine(); //} Console.ReadLine(); channel.Close(); channelFactory.Close(); }
public static string GetUserIdSingleClickSignInToken(string oneClickToken) { return(EncryptionUtility.Decrypt(oneClickToken)); }