Skip to content

Commit

Permalink
Merge pull request #179 from BryanSoltis/master
Browse files Browse the repository at this point in the history
2023-06-26 - BryanSoltis - v2.8.0 Updates
  • Loading branch information
jocontr committed Jul 6, 2023
2 parents f953878 + 398a3aa commit ddbaff9
Show file tree
Hide file tree
Showing 117 changed files with 61,410 additions and 1,331 deletions.
10 changes: 9 additions & 1 deletion ready/AzNamingTool/App.razor
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<CascadingBlazoredModal>
@using AzureNamingTool.Models;

<CascadingValue Value="identityProviderDetails">
<CascadingBlazoredModal>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
Expand All @@ -13,3 +16,8 @@
</NotFound>
</Router>
</CascadingBlazoredModal>
</CascadingValue>
@code {
[Parameter]
public IdentityProviderDetails? identityProviderDetails { get; set; }
}
16 changes: 8 additions & 8 deletions ready/AzNamingTool/AzureNamingTool.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<Version>2.7.0</Version>
<Version>2.8.0</Version>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
Expand All @@ -19,13 +19,6 @@
<NoWarn>1591;1701;1702</NoWarn>
</PropertyGroup>

<ItemGroup>
<Compile Remove="VersionNotes\**" />
<Content Remove="VersionNotes\**" />
<EmbeddedResource Remove="VersionNotes\**" />
<None Remove="VersionNotes\**" />
</ItemGroup>

<ItemGroup>
<Content Remove="appsettings.Development.json" />
<Content Remove="appsettings.json" />
Expand Down Expand Up @@ -73,6 +66,9 @@
<Content Update="wwwroot\images\runnoft.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\js\jquery-3.7.0.min.js">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
</ItemGroup>

<ItemGroup>
Expand All @@ -81,4 +77,8 @@
</None>
</ItemGroup>

<ItemGroup>
<Folder Include="VersionNotes\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ public async Task<IActionResult> RequestName([FromBody] ResourceNameRequest requ
{
try
{
request.CreatedBy = "API";
ResourceNameResponse resourceNameRequestResponse = await ResourceNamingRequestService.RequestName(request);

if (resourceNameRequestResponse.Success)
Expand Down
17 changes: 17 additions & 0 deletions ready/AzNamingTool/Helpers/CacheHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,22 @@ public static string GetAllCacheData()
}
return data.ToString();
}

public static void ClearAllCache()
{
try
{
ObjectCache memoryCache = MemoryCache.Default;
List<string> cacheKeys = memoryCache.Select(kvp => kvp.Key).ToList();
foreach (string cacheKey in cacheKeys)
{
memoryCache.Remove(cacheKey);
}
}
catch (Exception ex)
{
AdminLogService.PostItem(new AdminLogMessage() { Title = "ERROR", Message = ex.Message });
}
}
}
}
160 changes: 143 additions & 17 deletions ready/AzNamingTool/Helpers/ConfigurationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Net.Http.Headers;
using System;
using Blazored.Toast.Services;
using Microsoft.AspNetCore.Mvc;

namespace AzureNamingTool.Helpers
{
Expand All @@ -39,15 +40,29 @@ public static string GetAppSetting(string key, bool decrypt = false)
{
var config = GetConfigurationData();

// Check if the app setting is already set
if (config.GetType().GetProperty(key) != null)
{
value = config.GetType().GetProperty(key).GetValue(config, null).ToString();

if ((decrypt) && (value != ""))
// Verify the value is encrypted, and should be decrypted
if ((decrypt) && (value != "") && (GeneralHelper.IsBase64Encoded(value)))
{
value = GeneralHelper.DecryptString(value, config.SALTKey);
}

// Set the result to cache
CacheHelper.SetCacheObject(key, value);
}
else
{
// Create a new configuration object and get the default for the property
SiteConfiguration newconfig = new();
value = newconfig.GetType().GetProperty(key).GetValue(newconfig, null).ToString();

// Set the result to the app settings
SetAppSetting(key, value, decrypt);

// Set the result to cache
CacheHelper.SetCacheObject(key, value);
}
Expand Down Expand Up @@ -87,7 +102,7 @@ public static void SetAppSetting(string key, string value, bool encrypt = false)
}
}

public static void VerifyConfiguration()
public static async void VerifyConfiguration(StateContainer state)
{
try
{
Expand All @@ -110,6 +125,13 @@ public static void VerifyConfiguration()
// Migrate the data
FileSystemHelper.MigrateDataToFile("adminlog.json", "settings/", "adminlogmessages.json", "settings/", true);
}

// Sync cnfiguration data
if (!state.ConfigurationDataSynced)
{
await SyncConfigurationData("ResourceComponent");
state.SetConfigurationDataSynced(true);
}
}
catch (Exception ex)
{
Expand Down Expand Up @@ -187,11 +209,18 @@ public static bool VerifyConnectivity()
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new();
PingReply reply = ping.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success)
try
{
pingsuccessful = true;
result = true;
PingReply reply = ping.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success)
{
pingsuccessful = true;
result = true;
}
}
catch (Exception)
{
// Catch this exception but continue to try a web request instead
}

// If ping is not successful, attempt to download a file
Expand All @@ -201,16 +230,14 @@ public static bool VerifyConnectivity()
var request = (HttpWebRequest)WebRequest.Create("https://github.com/aznamingtool/AzureNamingTool/blob/main/connectiontest.png");
request.KeepAlive = false;
request.Timeout = 1500;
using (var response = (HttpWebResponse)request.GetResponse())
using var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.OK)
{
result = true;
}
else
{
AdminLogService.PostItem(new AdminLogMessage() { Title = "ERROR", Message = "Connectivity Check Failed:" + response.StatusDescription });
}
result = true;
}
else
{
AdminLogService.PostItem(new AdminLogMessage() { Title = "ERROR", Message = "Connectivity Check Failed:" + response.StatusDescription });
}
}
}
Expand All @@ -226,7 +253,7 @@ public static bool VerifyConnectivity()
}
catch (Exception ex)
{
AdminLogService.PostItem(new AdminLogMessage() { Title = "ERROR", Message = ex.Message });
AdminLogService.PostItem(new AdminLogMessage() { Title = "ERROR", Message = "There was a problem verifying connectivty. Error: " + ex.Message });
}

// Set the result to cache
Expand Down Expand Up @@ -258,6 +285,7 @@ public async static Task<List<T>> GetList<T>()
nameof(CustomComponent) => await FileSystemHelper.ReadFile("customcomponents.json"),
nameof(AdminLogMessage) => await FileSystemHelper.ReadFile("adminlogmessages.json"),
nameof(GeneratedName) => await FileSystemHelper.ReadFile("generatednames.json"),
nameof(AdminUser) => await FileSystemHelper.ReadFile("adminusers.json"),
_ => "[]",
};
CacheHelper.SetCacheObject(typeof(T).Name, data);
Expand Down Expand Up @@ -323,6 +351,9 @@ public async static Task WriteList<T>(List<T> items)
case nameof(GeneratedName):
await FileSystemHelper.WriteConfiguation(items, "generatednames.json");
break;
case nameof(AdminUser):
await FileSystemHelper.WriteConfiguation(items, "adminusers.json");
break;
default:
break;
}
Expand All @@ -342,6 +373,7 @@ public async static Task WriteList<T>(List<T> items)
nameof(CustomComponent) => await FileSystemHelper.ReadFile("customcomponents.json"),
nameof(AdminLogMessage) => await FileSystemHelper.ReadFile("adminlogmessages.json"),
nameof(GeneratedName) => await FileSystemHelper.ReadFile("generatednames.json"),
nameof(AdminUser) => await FileSystemHelper.ReadFile("adminusers.json"),
_ => "[]",
};

Expand All @@ -356,6 +388,13 @@ public async static Task WriteList<T>(List<T> items)

public static async void UpdateSettings(SiteConfiguration config)
{
// Clear the cache
ObjectCache memoryCache = MemoryCache.Default;
List<string> cacheKeys = memoryCache.Select(kvp => kvp.Key).ToList();
foreach (string cacheKey in cacheKeys)
{
memoryCache.Remove(cacheKey);
}
var jsonWriteOptions = new JsonSerializerOptions()
{
WriteIndented = true
Expand Down Expand Up @@ -519,7 +558,7 @@ public static void ResetState(StateContainer state)
state.SetVerified(false);
state.SetAdmin(false);
state.SetPassword(false);
state.SetAppTheme("bg-default text-black");
state.SetAppTheme("bg-default text-dark");
}

public static async Task<string> GetToolVersion()
Expand Down Expand Up @@ -702,5 +741,92 @@ public static async Task<string> GetProgramSetting(string programSetting)
}
return result;
}

/// <summary>
/// This function is used to sync default configuration data with the user's local version
/// </summary>
/// <param name="type">string - Type of configuration data to sync</param>
public static async Task SyncConfigurationData(string type)
{
try
{
bool update = false;

switch (type)
{
case "ResourceComponent":
// Get all the existing components
List<ResourceComponent> currentComponents = new();
ServiceResponse serviceResponse = new();
serviceResponse = await ResourceComponentService.GetItems(true);
if (serviceResponse.Success)
{
currentComponents = serviceResponse.ResponseObject;
// Get the default component data
List<ResourceComponent> defaultComponents = new();
string data = await FileSystemHelper.ReadFile("resourcecomponents.json", "repository/");
if (!String.IsNullOrEmpty(data))
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};

if (!String.IsNullOrEmpty(data))
{
defaultComponents = JsonSerializer.Deserialize<List<ResourceComponent>>(data, options);
}

// Loop over the existing components to verify the data is complete
foreach (ResourceComponent currentComponent in currentComponents)
{
// Create a new component for any updates
ResourceComponent newComponent = currentComponent;
// Get the matching default component for the current component
ResourceComponent defaultcomponent = defaultComponents.Find(x => x.Name == currentComponent.Name);
// Check the data to see if it's been configured
if (String.IsNullOrEmpty(currentComponent.MinLength))
{
if (defaultcomponent != null)
{
newComponent.MinLength = defaultcomponent.MinLength;
}
else
{
newComponent.MinLength = "1";
}
update = true;
}

// Check the data to see if it's been configured
if (String.IsNullOrEmpty(currentComponent.MaxLength))
{
if (defaultcomponent != null)
{
newComponent.MaxLength = defaultcomponent.MaxLength;
}
else
{
newComponent.MaxLength = "10";
}
update = true;
}
if (update)
{
await ResourceComponentService.PostItem(newComponent);
}
}
}
}
break;
}
}
catch (Exception ex)
{
await AdminLogService.PostItem(new AdminLogMessage() { Title = "ERROR", Message = ex.Message });
}

}
}
}
12 changes: 5 additions & 7 deletions ready/AzNamingTool/Helpers/FileSystemHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,11 @@ public static async Task WriteFile(string fileName, string content, string folde
{
try
{
using (FileStream fstr = File.Open(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folderName + fileName), FileMode.Truncate, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fstr);
sw.Write(content);
sw.Flush();
sw.Dispose();
}
using FileStream fstr = File.Open(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folderName + fileName), FileMode.Truncate, FileAccess.Write);
StreamWriter sw = new(fstr);
sw.Write(content);
sw.Flush();
sw.Dispose();
return;
}
catch (Exception)
Expand Down
16 changes: 16 additions & 0 deletions ready/AzNamingTool/Helpers/GeneralHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,22 @@ public static string DecryptString(string cipherText, string keyString)
return streamReader.ReadToEnd();
}

public static bool IsBase64Encoded(string value)
{
bool base64encoded = false;
try
{
byte[] byteArray = Convert.FromBase64String(value);
base64encoded = true;
}
catch (FormatException)
{
// The string is not base 64. Dismiss the error and return false
}
return base64encoded;
}


public static async Task<string> DownloadString(string url)
{
string data;
Expand Down
Loading

0 comments on commit ddbaff9

Please sign in to comment.