Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor async code #14938

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Windows;
using System.Windows.Controls;
Expand Down Expand Up @@ -127,7 +128,7 @@ protected virtual void Dispose(bool disposing)
}
}

async void InitializeAsync()
async Task InitializeAsync()
{
VirtualFolderPath = string.Empty;
try
Expand Down
323 changes: 323 additions & 0 deletions src/Dynamo.All.sln

Large diffs are not rendered by default.

7 changes: 3 additions & 4 deletions src/DynamoCore/Logging/DynamoAnalyticsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public static String GetUserID()
/// </summary>
internal class DynamoAnalyticsClient : IAnalyticsClient, IDisposable
{
private readonly ManualResetEventSlim serviceInitialized = new ManualResetEventSlim(false);
private Task serviceInitialized;
private readonly object trackEventLockObj = new object();

/// <summary>
Expand Down Expand Up @@ -161,9 +161,8 @@ private void StartInternal()
//If not ReportingAnalytics, then set the idle time as infinite so idle state is not recorded.
Service.StartUp(product, new UserInfo(Session.UserId), hostInfo, TimeSpan.FromMinutes(30));
}

serviceInitialized.Set();
}

/// <summary>
/// Starts the client when DynamoModel is created. This method initializes
/// the Analytics service and application life cycle start is tracked.
Expand All @@ -173,7 +172,7 @@ public void Start()
// Start Analytics service regardless of optin status.
// Each track event will be enabled/disabled based on the corresponding optin status.
// Ex. ADP will manage optin status internally
Task.Run(() => StartInternal());
serviceInitialized = Task.Run(() => StartInternal());

TrackPreference("ReportingAnalytics", "", ReportingAnalytics ? 1 : 0);
}
Expand Down
3 changes: 2 additions & 1 deletion src/DynamoCoreWpf/UI/GuidedTour/GuidesValidationMethods.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
Expand Down Expand Up @@ -615,7 +616,7 @@ internal static void ExecuteViewDetailsSideBar(Step stepInfo, StepUIAutomation u
/// <summary>
/// This method will calculate the Popup location based in a item from the Library
/// </summary>
internal static async void CalculateLibraryItemLocation(Step stepInfo, StepUIAutomation uiAutomationData, bool enableFunction, GuideFlow currentFlow)
internal static async Task CalculateLibraryItemLocation(Step stepInfo, StepUIAutomation uiAutomationData, bool enableFunction, GuideFlow currentFlow)
{
CurrentExecutingStep = stepInfo;
if (uiAutomationData == null) return;
Expand Down
2 changes: 1 addition & 1 deletion src/DynamoCoreWpf/Utilities/ResourceUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ internal static async Task<object> ExecuteJSFunction(UIElement MainWindow, objec
/// <param name="fontStylePath">Path to the Font Style that will be used in some part of the HTML page</param>
/// <param name="localAssembly">Local Assembly in which the resource will be loaded</param>
/// <param name="userDataFolder">the folder that WebView2 will use for storing cache info</param>
internal static async void LoadWebBrowser(HtmlPage htmlPage, DynamoWebView2 webBrowserComponent, string resourcesPath, string fontStylePath, Assembly localAssembly, string userDataFolder = default(string))
internal static async Task LoadWebBrowser(HtmlPage htmlPage, DynamoWebView2 webBrowserComponent, string resourcesPath, string fontStylePath, Assembly localAssembly, string userDataFolder = default(string))
{
try
{
Expand Down
2 changes: 1 addition & 1 deletion src/DynamoCoreWpf/Utilities/WpfUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public static Rect BoundsRelativeTo(this FrameworkElement element,
/// <param name="ds"></param>
/// <param name="delay">delay in milliseconds</param>
/// <param name="callback">action to be called</param>
public static async void DelayInvoke(this Dispatcher ds, int delay, Action callback)
public static async Task DelayInvoke(this Dispatcher ds, int delay, Action callback)
{
await Task.Delay(delay);
await ds.BeginInvoke(callback);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ private bool WarnAboutDuplicatePackageConflicts(PackageVersion package,
return true;
}

internal async void ExecutePackageDownload(string name, PackageVersion package, string installPath)
internal async Task ExecutePackageDownload(string name, PackageVersion package, string installPath)
{
string msg = String.IsNullOrEmpty(installPath) ?
String.Format(Resources.MessageConfirmToInstallPackage, name, package.version) :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Forms;
using Dynamo.Core;
using Dynamo.Extensions;
using Dynamo.Graph.Nodes.ZeroTouch;
using Dynamo.Graph.Workspaces;
using Dynamo.Models;
Expand Down Expand Up @@ -2189,22 +2191,23 @@ private void Submit()
if (!updatedFiles.Any()) return;
}

try
{
// begin submission
var pmExtension = dynamoViewModel.Model.GetPackageManagerExtension();
var handle = pmExtension.PackageManagerClient.PublishAsync(Package, RetainFolderStructureOverride ? updatedFiles : contentFiles, MarkdownFiles, IsNewVersion, RetainFolderStructureOverride);
var pmExtension = dynamoViewModel.Model.GetPackageManagerExtension();

// start upload
Uploading = true;
UploadHandle = handle;
}
catch (Exception e)
pmExtension.PackageManagerClient.PublishAsync(Package,
RetainFolderStructureOverride ? updatedFiles : contentFiles,
MarkdownFiles, IsNewVersion, RetainFolderStructureOverride).ContinueWith((t) =>
{
UploadState = PackageUploadHandle.State.Error;
ErrorString = TranslatePackageManagerError(e.Message);
dynamoViewModel.Model.Logger.Log(e);
}
// start upload
UploadHandle = t.Result;
if (t.Exception != null)
{
UploadState = PackageUploadHandle.State.Error;
ErrorString = TranslatePackageManagerError(t.Exception.Message);
dynamoViewModel.Model.Logger.Log(t.Exception);
}
});

Uploading = true;
}

private static readonly Regex UserIsNotAMaintainerRegex =
Expand Down
8 changes: 3 additions & 5 deletions src/DynamoCoreWpf/Views/GuidedTour/PopupWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ private void PopupWindow_Opened(object sender, EventArgs e)
}
}

private async void InitWebView2Component()
private Task InitWebView2Component()
{
webBrowserComponent = new DynamoWebView2();

Expand All @@ -125,7 +125,7 @@ private async void InitWebView2Component()
contentGrid.Children.Add(webBrowserComponent);
Grid.SetRow(webBrowserComponent, 1);

ResourceUtilities.LoadWebBrowser(hostControlInfo.HtmlPage, webBrowserComponent, resourcesPath, mainFontStylePath, GetType().Assembly, WebBrowserUserDataFolder);
return ResourceUtilities.LoadWebBrowser(hostControlInfo.HtmlPage, webBrowserComponent, resourcesPath, mainFontStylePath, GetType().Assembly, WebBrowserUserDataFolder);
}


Expand Down Expand Up @@ -159,7 +159,7 @@ private void BackButton_Click(object sender, RoutedEventArgs e)
GuideFlowEvents.OnGuidedTourPrev();
}

private async void Popup_KeyDown(object sender, KeyEventArgs e)
private void Popup_KeyDown(object sender, KeyEventArgs e)
{
if (canMoveStep)
{
Expand All @@ -174,8 +174,6 @@ private async void Popup_KeyDown(object sender, KeyEventArgs e)
GuideFlowEvents.OnGuidedTourNext();
break;
}
//Adds a delay of 500ms to avoid Dynamo crash with a quick switch with the keys
await Task.Delay(500);

canMoveStep = true;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
Expand Down Expand Up @@ -155,12 +156,12 @@ private void watermarkLabel_MouseLeftButtonUp(object sender, MouseButtonEventArg
}

// Select the text inside the TextBox when clicked
private async void inputField_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
private void inputField_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var tb = sender as TextBox;
if (mouseClickSelection)
{
await Application.Current.Dispatcher.InvokeAsync(tb.SelectAll);
Application.Current.Dispatcher.Invoke(tb.SelectAll);

//disable the boolean porperty to selection apply only first time
mouseClickSelection = false;
Expand Down
4 changes: 2 additions & 2 deletions src/DynamoCoreWpf/Views/Preview/PreviewControl.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ private static Size ContentToControlSize(Size size)

#region Private Class Methods - Transition Helpers

private async void BeginFadeInTransition()
private void BeginFadeInTransition()
{
if (!IsHidden)
{
Expand Down Expand Up @@ -562,7 +562,7 @@ private async void BeginFadeInTransition()
delayTimer.Stop();
};

await Task.Run(() => delayTimer.Start());
delayTimer.Start();
}

private void ProcessFadeIn()
Expand Down
27 changes: 19 additions & 8 deletions src/DynamoCoreWpf/Views/SplashScreen/SplashScreen.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;
using Dynamo.Configuration;
Expand Down Expand Up @@ -329,10 +330,20 @@ private string GetUserDirectory()
String.Format("{0}.{1}", version.Major, version.Minor));
}

protected override async void OnContentRendered(EventArgs e)
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);

InitializeWebview2().ContinueWith((t) => {
if (t.Exception != null)
{
Console.WriteLine(t.Exception.Message);
}
});
}

private async Task InitializeWebview2()
{
string htmlString = string.Empty;
string jsonString = string.Empty;

Expand Down Expand Up @@ -389,7 +400,7 @@ protected override async void OnContentRendered(EventArgs e)
}
}

internal async void SetBarProperties(string version, string loadingDescription, float barSize)
internal async Task SetBarProperties(string version, string loadingDescription, float barSize)
{
var elapsedTime = loadingTimer.ElapsedMilliseconds;
totalLoadingTime += elapsedTime;
Expand All @@ -400,7 +411,7 @@ internal async void SetBarProperties(string version, string loadingDescription,
}
}

internal async void SetLoadingDone()
internal async Task SetLoadingDone()
{
if (webView?.CoreWebView2 != null)
{
Expand All @@ -414,7 +425,7 @@ internal async void SetLoadingDone()
/// Set the import status on splash screen.
/// </summary>
/// <param name="importStatus"></param>
internal async void SetImportStatus(ImportStatus importStatus)
internal async Task SetImportStatus(ImportStatus importStatus)
{
string importSettingsTitle = Dynamo.Wpf.Properties.Resources.SplashScreenImportSettings;
string errorDescription = string.Empty;
Expand Down Expand Up @@ -445,7 +456,7 @@ await webView.CoreWebView2.ExecuteScriptAsync("window.setImportStatus({" +
/// <summary>
/// Set the login status on splash screen.
/// </summary>
internal async void SetSignInStatus(bool status)
internal async Task SetSignInStatus(bool status)
{
if (webView?.CoreWebView2 != null)
{
Expand All @@ -457,7 +468,7 @@ await webView.CoreWebView2.ExecuteScriptAsync("window.setSignInStatus({" +
/// <summary>
/// Handle the login status changes on splash screen.
/// </summary>
internal async void HandleSignInStatusChange(bool status)
internal async Task HandleSignInStatusChange(bool status)
{
if (webView?.CoreWebView2 != null)
{
Expand All @@ -469,7 +480,7 @@ internal async void HandleSignInStatusChange(bool status)
/// Enable or disable the SignIn button on splash screen.
/// </summary>
/// <param name="enabled"></param>
internal async void SetSignInEnable(bool enabled)
internal async Task SetSignInEnable(bool enabled)
{
if (webView?.CoreWebView2 != null)
{
Expand All @@ -479,7 +490,7 @@ internal async void SetSignInEnable(bool enabled)
/// <summary>
/// Setup the values for all labels on splash screen using resources
/// </summary>
internal async void SetLabels()
internal async Task SetLabels()
{
if (webView.CoreWebView2 != null)
{
Expand Down
10 changes: 4 additions & 6 deletions src/DynamoPackages/PackageManagerClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,16 +226,14 @@ private bool ExecuteTermsOfUseCall(bool queryAcceptanceStatus)
}, false);
}

internal PackageUploadHandle PublishAsync(Package package, object files, IEnumerable<string> markdownFiles, bool isNewVersion, bool retainFolderStructure)
internal Task<PackageUploadHandle> PublishAsync(Package package, object files, IEnumerable<string> markdownFiles, bool isNewVersion, bool retainFolderStructure)
{
var packageUploadHandle = new PackageUploadHandle(PackageUploadBuilder.NewRequestBody(package));

Task.Factory.StartNew(() =>
return Task.Factory.StartNew(() =>
{
var packageUploadHandle = new PackageUploadHandle(PackageUploadBuilder.NewRequestBody(package));
Publish(package, files, markdownFiles, isNewVersion, packageUploadHandle, retainFolderStructure);
return packageUploadHandle;
});

return packageUploadHandle;
}

internal void Publish(Package package, object files, IEnumerable<string> markdownFiles, bool isNewVersion, PackageUploadHandle packageUploadHandle, bool retainFolderStructure = false)
Expand Down
6 changes: 3 additions & 3 deletions src/LibraryViewExtensionWebView2/LibraryViewController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ private string ReplaceUrlWithBase64Image(string html, string minifiedURL, bool m
Tuple.Create("/resources/search-icon-clear.svg",true)
};

async void InitializeAsync()
async Task InitializeAsync()
{
try
{
Expand Down Expand Up @@ -467,7 +467,7 @@ private void Browser_SizeChanged(object sender, SizeChangedEventArgs e)
}

//Changes the size of the font's library depending of the screen height
private async void SetLibraryFontSize()
private async Task SetLibraryFontSize()
{
//Gets the height of the primary monitor
var height = SystemParameters.PrimaryScreenHeight;
Expand All @@ -484,7 +484,7 @@ private async void SetLibraryFontSize()
}
}

private async void SetTooltipText()
private async Task SetTooltipText()
{
var jsonTooltipText = new { create = Resources.TooltipTextCreate, action = Resources.TooltipTextAction, query = Resources.TooltipTextQuery };
var jsonString = JsonConvert.SerializeObject(jsonTooltipText);
Expand Down
Loading
Loading