Here are the examples of the csharp api System.Diagnostics.Debug.WriteLine(string, params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2746 Examples
19
View Source File : Amf0Reader.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public bool TryGetStrictArray(Span<byte> buffer, out List<object> array, out int consumedLength)
{
array = default;
consumedLength = default;
if (!TryDescribeData(buffer, out var type, out _))
{
return false;
}
if (type != Amf0Type.StrictArray)
{
return false;
}
var obj = new List<object>();
_referenceTable.Add(obj);
var elementCount = NetworkBitConverter.ToUInt32(buffer.Slice(Amf0CommonValues.MARKER_LENGTH, sizeof(uint)));
int consumed = Amf0CommonValues.MARKER_LENGTH + sizeof(uint);
var arrayBodyBuffer = buffer.Slice(consumed);
var elementBodyBuffer = arrayBodyBuffer;
System.Diagnostics.Debug.WriteLine(elementCount);
for (uint i = 0; i < elementCount; i++)
{
if (!TryGetValue(elementBodyBuffer, out _, out var element, out var bufferConsumed))
{
return false;
}
obj.Add(element);
if (elementBodyBuffer.Length - bufferConsumed < 0)
{
return false;
}
elementBodyBuffer = elementBodyBuffer.Slice(bufferConsumed);
consumed += bufferConsumed;
}
array = obj;
consumedLength = consumed;
return true;
}
19
View Source File : HistoryViewer.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private static void RunLiveChangesMonitor(VersionControlLogReader reader, string gourcePath, string arguments)
{
var gourceStartInfo = new ProcessStartInfo(gourcePath, arguments)
{
WindowStyle = ProcessWindowStyle.Maximized,
RedirectStandardInput = true,
UseShellExecute = false
};
var process = Process.Start(gourceStartInfo);
if (process == null)
throw new InvalidDataException("Failed to start process: " + gourceStartInfo.FileName);
using (var gourceWriter = new StreamWriter(process.StandardInput.BaseStream, Encoding.UTF8))
{
gourceWriter.AutoFlush = process.StandardInput.AutoFlush;
gourceWriter.NewLine = process.StandardInput.NewLine;
while (!process.HasExited)
{
var line = reader.ReadLine();
Debug.WriteLine("LOG: " + (line ?? "<NULL>"));
if (line == null)
{
// Waiting for second to avoid frequent server calls
System.Threading.Thread.Sleep(1000);
}
else
{
gourceWriter.WriteLine(line);
// System.Threading.Thread.Sleep(100);
}
}
}
}
19
View Source File : CompletionWindowBase.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
void CloseIfFocusLost()
{
if (CloseOnFocusLost) {
Debug.WriteLine("CloseIfFocusLost: this.IsActive=" + this.IsActive + " IsTextAreaFocused=" + IsTextAreaFocused);
if (!this.IsActive && !IsTextAreaFocused) {
Close();
}
}
}
19
View Source File : FoldingSection.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
internal void ValidateCollapsedLineSections()
{
if (!isFolded) {
RemoveCollapsedLineSection();
return;
}
// It is possible that StartOffset/EndOffset get set to invalid values via the property setters in TextSegment,
// so we coerce those values into the valid range.
DoreplacedentLine startLine = manager.doreplacedent.GetLineByOffset(StartOffset.CoerceValue(0, manager.doreplacedent.TextLength));
DoreplacedentLine endLine = manager.doreplacedent.GetLineByOffset(EndOffset.CoerceValue(0, manager.doreplacedent.TextLength));
if (startLine == endLine) {
RemoveCollapsedLineSection();
} else {
if (collapsedSections == null)
collapsedSections = new CollapsedLineSection[manager.textViews.Count];
// Validate collapsed line sections
DoreplacedentLine startLinePlusOne = startLine.NextLine;
for (int i = 0; i < collapsedSections.Length; i++) {
var collapsedSection = collapsedSections[i];
if (collapsedSection == null || collapsedSection.Start != startLinePlusOne || collapsedSection.End != endLine) {
// recreate this collapsed section
if (collapsedSection != null) {
Debug.WriteLine("CollapsedLineSection validation - recreate collapsed section from " + startLinePlusOne + " to " + endLine);
collapsedSection.Uncollapse();
}
collapsedSections[i] = manager.textViews[i].CollapseLines(startLinePlusOne, endLine);
}
}
}
}
19
View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
[Conditional("DEBUG")]
public static void CheckIsFrozen(Freezable f)
{
if (f != null && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f.ToString());
}
19
View Source File : SelectionMouseHandler.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
void StartDrag()
{
// mouse capture and Drag'n'Drop doesn't mix
textArea.ReleaseMouseCapture();
// prevent nested StartDrag calls
mode = MouseSelectionMode.Drag;
DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
DragDropEffects allowedEffects = DragDropEffects.All;
var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Doreplacedent, s)).ToList();
foreach (ISegment s in deleteOnMove) {
ISegment[] result = textArea.GetDeletableSegments(s);
if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
allowedEffects &= ~DragDropEffects.Move;
}
}
var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
textArea.RaiseEvent(copyingEventArgs);
if (copyingEventArgs.CommandCancelled)
return;
object dragDescriptor = new object();
this.currentDragDescriptor = dragDescriptor;
DragDropEffects resultEffect;
using (textArea.AllowCaretOutsideSelection()) {
var oldCaretPosition = textArea.Caret.Position;
try {
Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
} catch (COMException ex) {
// ignore COM errors - don't crash on badly implemented drop targets
Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
return;
}
if (resultEffect == DragDropEffects.None) {
// reset caret if drag was aborted
textArea.Caret.Position = oldCaretPosition;
}
}
this.currentDragDescriptor = null;
if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
bool draggedInsideSingleDoreplacedent = (dragDescriptor == textArea.Doreplacedent.UndoStack.LastGroupDescriptor);
if (draggedInsideSingleDoreplacedent)
textArea.Doreplacedent.UndoStack.StartContinuedUndoGroup(null);
textArea.Doreplacedent.BeginUpdate();
try {
foreach (ISegment s in deleteOnMove) {
textArea.Doreplacedent.Remove(s.Offset, s.Length);
}
} finally {
textArea.Doreplacedent.EndUpdate();
if (draggedInsideSingleDoreplacedent)
textArea.Doreplacedent.UndoStack.EndUndoGroup();
}
}
}
19
View Source File : DetectClicksOnChartPartsModifier.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public override void OnModifierMouseDown(ModifierMouseArgs e)
{
base.OnModifierMouseDown(e);
IEnumerable<IHitTestable> chartElements = this.YAxes.Cast<IHitTestable>()
.Concat(this.XAxes)
.Concat(new[] {this.ModifierSurface});
var clickedElement = chartElements.FirstOrDefault(ce => IsPointWithinBounds(e.MousePoint, ce));
if (clickedElement != null)
{
Debug.WriteLine("The following element was clicked: " + WhatElement(clickedElement));
}
}
19
View Source File : WebViewRender.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
var oldWebView = e.OldElement as WebViewer;
if (oldWebView != null)
oldWebView.EvaluateJavascript = null;
var newWebView = e.NewElement as WebViewer;
if (newWebView != null)
newWebView.EvaluateJavascript = async (js) =>
{
ManualResetEvent reset = new ManualResetEvent(false);
var response = "";
Device.BeginInvokeOnMainThread(() =>
{
System.Diagnostics.Debug.WriteLine("Javascript Send: " + js);
Control?.EvaluateJavascript(js, new JavascriptCallback((r) => { response = r; reset.Set(); }));
});
await Task.Run(() => { reset.WaitOne(); });
if (response == "null")
response = string.Empty;
return response;
};
if (Control != null && e.NewElement != null)
{
InitializeCommands((WebViewer)e.NewElement);
SetupControl();
}
}
19
View Source File : WebViewRender.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public void OnReceiveValue(Java.Lang.Object value)
{
System.Diagnostics.Debug.WriteLine("Javascript Return: " + Convert.ToString(value));
_callback?.Invoke(Convert.ToString(value));
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
public int OnAfterSave(uint docCookie)
{
if (!UpdateManager.Current.IsConnected)
{
System.Diagnostics.Debug.WriteLine("RealXaml was unable to send the xaml. No connection to the notifier.");
return VSConstants.S_OK;
}
ThreadHelper.ThrowIfNotOnUIThread();
if (_dte == null)
return VSConstants.S_OK;
try
{
Doreplacedent doc = FindDoreplacedentByCookie(docCookie);
if (doc == null)
return VSConstants.S_OK;
string kind = doc.Kind;
string lang = doc.Language;
string filePath = doc.FullName;
string fileExt = Path.GetExtension(filePath)?.ToLower() ?? ".unknown";
if (fileExt != ".xaml")
return VSConstants.S_OK;
XDoreplacedent xdoc = XDoreplacedent.Load(filePath);
XNamespace xnsp = "http://schemas.microsoft.com/winfx/2009/xaml";
string pageId = xdoc.Root.Attribute(xnsp + "Clreplaced").Value;
TextDoreplacedent textdoc = (TextDoreplacedent)(doc.Object("TextDoreplacedent"));
var p = textdoc.StartPoint.CreateEditPoint();
string xaml = p.GetText(textdoc.EndPoint);
_xamlCache[pageId] = xaml;
// Save is due to a project build
// Xaml will be sent after the build
if (!this.IsBuilding)
{
Task.Run(
async () =>
{
try
{
await UpdateManager.Current.SendXamlAsync(pageId, xaml, true);
}
catch (Exception ex)
{
_outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
_outputPane.OutputString(Environment.NewLine);
_outputPane.OutputString(ex.ToString());
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
System.Diagnostics.Debug.WriteLine(ex);
}
});
}
}
catch (Exception ex)
{
_outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
_outputPane.OutputString(Environment.NewLine);
_outputPane.OutputString(ex.ToString());
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
System.Diagnostics.Debug.WriteLine(ex);
}
return VSConstants.S_OK;
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void BuildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
{
if (!UpdateManager.Current.IsConnected)
return;
try
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
if (_mainDllProject != null
&& Scope == vsBuildScope.vsBuildScopeProject
&& Action == vsBuildAction.vsBuildActionBuild)
{
EnvDTE.Property property = _mainDllProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath");
string fullPath = _mainDllProject.Properties.Item("FullPath").Value.ToString();
string outputFileName = _mainDllProject.Properties.Item("OutputFileName").Value.ToString();
string outputPath = property.Value.ToString();
string replacedemblyPath = Path.Combine(fullPath, outputPath, outputFileName);
using (MemoryStream ms = new MemoryStream())
{
// Make a copy of the file into memory to avoid any file lock
using (FileStream fs = File.OpenRead(replacedemblyPath))
await fs.CopyToAsync(ms);
await UpdateManager.Current.SendreplacedemblyAsync(outputFileName, ms.ToArray());
if(_xamlCache.Count > 0)
{
// Force a xaml update for every page
foreach(var cacheItem in _xamlCache)
await UpdateManager.Current.SendXamlAsync(cacheItem.Key, cacheItem.Value, true);
_xamlCache.Clear();
}
_outputPane.OutputString("Requesting replacedembly update...");
_outputPane.OutputString(Environment.NewLine);
}
}
}
catch(Exception ex)
{
_outputPane.OutputString($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
_outputPane.OutputString(Environment.NewLine);
_outputPane.OutputString(ex.ToString());
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
this.IsBuilding = false;
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void UpdateManager_PageAppeared(object sender, PageNotificationEventArgs e)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
_outputPane.OutputString($"The page '{e.PageId}' is now visible.");
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"The page '{e.PageId}' is now visible.");
try
{
EnvDTE.Projecreplacedem appPi = _dte.Solution.FindProjecreplacedem("App.xaml");
if (appPi != null)
{
foreach (Projecreplacedem pi in appPi.ContainingProject.Projecreplacedems)
{
if (!pi.Name.Contains(".xaml"))
continue;
string fileName = pi.FileNames[0];
XDoreplacedent xdoc = XDoreplacedent.Load(fileName);
XNamespace xnsp = "http://schemas.microsoft.com/winfx/2009/xaml";
string pageId = xdoc.Root.Attribute(xnsp + "Clreplaced").Value;
if (pageId != e.PageId)
continue;
var doreplacedent = pi.Doreplacedent;
string localPath = pi.Properties.Item("LocalPath").Value?.ToString();
string xaml = System.IO.File.ReadAllText(localPath);
await UpdateManager.Current.SendXamlAsync(pageId, xaml, false);
}
}
}
catch(Exception ex)
{
_outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
_outputPane.OutputString(Environment.NewLine);
_outputPane.OutputString(ex.ToString());
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void UpdateManager_PageDisappeared(object sender, PageNotificationEventArgs e)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
_outputPane.OutputString($"The page '{e.PageId}' went away.");
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"The page '{e.PageId}' went away.");
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void UpdateManager_replacedemblyLoaded(object sender, replacedemblyNotificationEventArgs e)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
_outputPane.OutputString($"A new version of the replacedembly '{e.replacedemblyName}' has been loaded. Now running version '{e.Version}'.");
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"A new version of the replacedembly '{e.replacedemblyName}' has been loaded. Now running version '{e.Version}'.");
}
19
View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
internal void Setup(Application application)
{
if (application == null)
throw new ArgumentNullException("application");
AppDomain.CurrentDomain.UnhandledException += this.CurrentDomain_UnhandledException;
TaskScheduler.UnobservedTaskException += this.TaskScheduler_UnobservedTaskException;
_app = new WeakReference<Application>(application);
application.PageAppearing += Application_PageAppearing;
application.PageDisappearing += Application_PageDisappearing;
_connectionTCS = new TaskCompletionSource<bool>();
Task.Run(
async () =>
{
try
{
await ConnectAsync();
if (_isConnected)
{
// Connection successfully estabilished
_connectionTCS.SetResult(_isConnected);
}
else
{
// Unable to connect, we should retry later
_connectionTCS.SetResult(_isConnected);
System.Diagnostics.Debug.WriteLine("Unable to connect to the RealXaml server.");
while (true)
{
System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
await ConnectAsync();
if (_isConnected)
{
break;
}
System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
await Task.Delay(5000);
}
}
}
catch(Exception ex)
{
_connectionTCS.SetException(ex);
}
});
}
19
View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async Task ConnectAsync()
{
if (_isConnected)
return;
// Emulators loopback addresses
IPAddress[] loopbackAddresses = new[]
{
IPAddress.Parse("127.0.0.1"),
IPAddress.Parse("10.0.2.2"),
IPAddress.Parse("10.0.3.2"),
IPAddress.Parse("169.254.80.80")
};
// Check if we are an emulator instance
List<Task<string>> waitTasks = new List<Task<string>>();
CancellationTokenSource cts = new CancellationTokenSource();
// Look for server using localhost (an emulator device)
foreach (var ipAddress in loopbackAddresses.Take(1))
{
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (!isPortOpen)
return null;
var connection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:5001/hub")
.Build();
await connection.StartAsync(cts.Token);
if (cts.IsCancellationRequested)
return null;
_useLocalHost = true;
_hubConnection = connection;
cts.Cancel();
return ipAddress.ToString();
}
catch (Exception ex)
{
return null;
}
}, cts.Token));
}
// Look for server using broadcast (a real device)
waitTasks.Add(Task.Run<string>(
async () =>
{
// Discover the server
using (UdpClient client = new UdpClient())
{
client.EnableBroadcast = true;
byte[] requestData = Encoding.ASCII.GetBytes($"AreYouTheServer?");
Task<int> sendTask = client.SendAsync(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 5002));
await Task.WhenAny(new[] { sendTask, Task.Delay(300) });
if (sendTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
Task<UdpReceiveResult> receiveTask = client.ReceiveAsync();
await Task.WhenAny(new[] { receiveTask, Task.Delay(300) });
if (receiveTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
UdpReceiveResult serverResponseData = receiveTask.Result;
string serverResponse = Encoding.ASCII.GetString(serverResponseData.Buffer);
if (serverResponse == "YesIamTheServer!")
{
string ipAddress = serverResponseData.RemoteEndPoint.Address.ToString();
_useLocalHost = false;
_hubConnection = null;
cts.Cancel();
return ipAddress.ToString();
}
}
}
client.Close();
}
return null;
}));
// Timeout task
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
await Task.Delay(5000, cts.Token);
cts.Cancel();
return null;
}
catch
{
return null;
}
}));
try
{
string ipAddress = await WaitForAnyGetHostIpTaskAsync(waitTasks);
if (ipAddress != null)
{
if (_hubConnection == null)
{
string port = _useLocalHost ? "5001" : "5002";
_hubConnection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:{port}/hub")
.Build();
await _hubConnection.StartAsync();
}
_isConnected = true;
_serverAddress = ipAddress;
_hubConnection.Closed +=
async (error) =>
{
System.Diagnostics.Debug.WriteLine("Connection with RealXaml has been lost.");
while(_hubConnection.State == HubConnectionState.Disconnected)
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (isPortOpen)
{
System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
await _hubConnection.StartAsync();
if (_hubConnection.State == HubConnectionState.Connected)
{
await Task.Delay(300);
await _hubConnection.SendAsync("NotifyIde", "Connection was lost. Here I'am again.");
System.Diagnostics.Debug.WriteLine($"Successfully restored lost to the RealXaml server.");
break;
}
}
System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
await Task.Delay(5000);
}
};
_hubConnection.On<string, byte[], bool>("ReloadXaml",
async (pageId, data, refresh) => await WhenReloadXaml(pageId, data, refresh));
_hubConnection.On<string, byte[]>("Reloadreplacedembly",
async (replacedemblyName, data) => await WhenReloadreplacedembly(replacedemblyName, data));
string clientId = $"RXID-{DateTime.Now.Ticks}";
await _hubConnection.SendAsync("RegisterClient", clientId);
System.Diagnostics.Debug.WriteLine($"Successfully connected to the RealXaml server.");
System.Diagnostics.Debug.WriteLine($"Your client ID is {clientId}");
return;
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error while trying to connect to the RealXaml server.");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async Task Reloadreplacedmbly(string replacedemblyName, byte[] data)
{
try
{
data = DecompressData(data);
replacedembly replacedembly = replacedembly.Load(data);
/*
* We use the two attributes MainPage and RootPage to let RealXaml know
* how he need to restart our application on replacedembly reload.
* Different scenario are possibile:
*
* At least we need to define one MainPage (for single page, no navigation)
* or we need to define one RootPage (for multi page with navigation).
* When defining only a RootPage, a NavigationPage will be used as MainPage.
*
* We can use them both to specify which clreplaced will be used as MainPage and RootPage.
* Using them togheter means that your custom MainPage needs to have a RootPage specified in the constructor.
*
*/
Type mainPageType = replacedembly.GetTypes()
.Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(MainPageAttribute))).FirstOrDefault();
Type rootPageType = replacedembly.GetTypes()
.Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(RootPageAttribute))).FirstOrDefault();
if (mainPageType == null && rootPageType == null)
throw new InvalidOperationException("Unable to create a new MainPage. Did you mark a page with the [MainPage] or the [RootPage] attribute? ");
Application app = null;
if (_app.TryGetTarget(out app))
{
Device.BeginInvokeOnMainThread(
async () =>
{
try
{
Page rootPage = null;
// In case of single page, no navigation
if(mainPageType != null
&& rootPageType == null)
{
// Create the new main page
app.MainPage = (Page)Activator.CreateInstance(mainPageType);
}
// In case of multi page with navigation
else if(rootPageType != null
&& mainPageType == null)
{
mainPageType = typeof(NavigationPage);
app.MainPage = new NavigationPage((Page)Activator.CreateInstance(rootPageType));
}
// In case of custom configuration
else if(mainPageType != null
&& rootPageType != null)
{
// Create the new main page which must host a root page
rootPage = (Page)Activator.CreateInstance(rootPageType);
app.MainPage = (Page)Activator.CreateInstance(mainPageType, rootPage);
}
// Reset collected pages
_pages.Clear();
// Re collect the root page
if (rootPageType != null)
{
_pages.Add(rootPageType.FullName, new WeakReference(rootPage));
await ReloadXaml(rootPage);
}
// Re collect the main page (could be a NavigationPage)
if (app.MainPage != null)
{
_pages.Add(mainPageType.FullName, new WeakReference(app.MainPage));
if (app.MainPage.GetType() != typeof(NavigationPage))
await ReloadXaml(app.MainPage);
}
// Notify that the replacedembly was loaded correctly
await _hubConnection.SendAsync("replacedemblyReloaded", replacedemblyName, replacedembly.GetName().Version.ToString());
System.Diagnostics.Debug.WriteLine($"A new main page of type '{mainPageType.FullName}' has been loaded!", "Ok");
}
catch (Exception ex)
{
// Notify that the replacedembly was loaded correctly
await _hubConnection.SendAsync("ThrowException", ex.ToString());
System.Diagnostics.Debug.WriteLine($"Unable to load the replacedembly '{replacedemblyName}'");
System.Diagnostics.Debug.WriteLine(ex);
}
});
}
}
catch (Exception ex)
{
// Notify that the replacedembly was loaded correctly
await _hubConnection.SendAsync("ThrowException", ex.ToString());
System.Diagnostics.Debug.WriteLine($"Unable to load the replacedembly '{replacedemblyName}'");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
View Source File : ViewerServer.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
public void Start()
{
_cts = new CancellationTokenSource();
Task.Run(() =>
{
UdpClient server = new UdpClient(5002);
byte[] responseData = Encoding.ASCII.GetBytes("YesIamTheServer!");
while (!_cts.IsCancellationRequested)
{
IPEndPoint clientEp = new IPEndPoint(IPAddress.Any, 0);
byte[] clientRequestData = server.Receive(ref clientEp);
string clientRequest = Encoding.ASCII.GetString(clientRequestData);
if (clientRequest.Contains("AreYouTheServer?"))
{
System.Diagnostics.Debug.WriteLine($"A new peer is connecting @ {clientEp.Address.ToString()}:{clientEp.Port}");
server.Send(responseData, responseData.Length, clientEp);
}
}
}, _cts.Token);
_host = WebHost.CreateDefaultBuilder()
.UseKestrel()
.UseUrls($"http://localhost:5001", $"http://{GetLocalIPAddress()}:5002")
.UseStartup<Startup>()
.Build();
_host.Run();
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
// When initialized asynchronously, the current thread may be a background thread at this point.
// Do any initialization that requires the UI thread after switching to the UI thread.
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
_dte = await GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
if (_dte == null)
return;
// Intercept build commands
string[] buildCommandNames = new[]
{
"Build.BuildSolution",
"Build.RebuildSolution",
"Build.BuildSelection",
"Build.RebuildSelection",
"ClreplacedViewContextMenus.ClreplacedViewProject.Build",
"ClreplacedViewContextMenus.ClreplacedViewProject.Rebuild",
"Build.ProjectPickerBuild",
"Build.ProjectPickerRebuild",
"Build.BuildOnlyProject",
"Build.RebuildOnlyProject"
};
_cmdEvents = new List<CommandEvents>();
foreach (string buildCommandName in buildCommandNames)
{
var buildCommand = _dte.Commands.Item(buildCommandName);
var cmdev = _dte.Events.CommandEvents[buildCommand.Guid, buildCommand.ID];
cmdev.BeforeExecute += this.BuildCommand_BeforeExecute;
_cmdEvents.Add(cmdev);
}
_dte.Events.SolutionEvents.BeforeClosing += SolutionEvents_BeforeClosing;
_dte.Events.BuildEvents.OnBuildBegin += BuildEvents_OnBuildBegin;
_dte.Events.BuildEvents.OnBuildDone += BuildEvents_OnBuildDone;
_dte.Events.BuildEvents.OnBuildProjConfigBegin += BuildEvents_OnBuildProjConfigBegin;
_rdt = (IVsRunningDoreplacedentTable)(await GetServiceAsync(typeof(SVsRunningDoreplacedentTable)));
_rdt.AdviseRunningDocTableEvents(this, out _rdtCookie);
await AdMaiora.RealXaml.Extension.Commands.EnableRealXamlCommand.InitializeAsync(this, _dte);
await AdMaiora.RealXaml.Extension.Commands.DisableRealXamlCommand.InitializeAsync(this, _dte);
CreateOutputPane();
try
{
string currentPath = Path.GetDirectoryName(GetType().replacedembly.Location);
_replacedemblyResolver = new ManualreplacedemblyResolver(
replacedembly.LoadFile(Path.Combine(currentPath, "Newtonsoft.Json.dll")),
replacedembly.LoadFile(Path.Combine(currentPath, "System.Buffers.dll")),
replacedembly.LoadFile(Path.Combine(currentPath, "System.Numerics.Vectors.dll"))
);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
_outputPane.OutputString("Something went wrong loading replacedemblies.");
_outputPane.OutputString(ex.ToString());
}
UpdateManager.Current.IdeRegistered += this.UpdateManager_IdeRegistered;
UpdateManager.Current.ClientRegistered += this.UpdateManager_ClientRegistered;
UpdateManager.Current.PageAppeared += this.UpdateManager_PageAppeared;
UpdateManager.Current.PageDisappeared += this.UpdateManager_PageDisappeared;
UpdateManager.Current.XamlUpdated += this.UpdateManager_XamlUpdated;
UpdateManager.Current.replacedemblyLoaded += this.UpdateManager_replacedemblyLoaded;
UpdateManager.Current.ExceptionThrown += this.UpdateManager_ExceptionThrown;
UpdateManager.Current.IdeNotified += this.Current_IdeNotified;
_xamlCache.Clear();
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private void SolutionEvents_BeforeClosing()
{
try
{
UpdateManager.Current.StopAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("RealXaml was unable to deactivate itself!");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void UpdateManager_ClientRegistered(object sender, ClientNotificationEventArgs e)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
_outputPane.OutputString($"A new client with ID {e.ClientId} is now connected.");
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"A new client with ID {e.ClientId} is now connected.");
}
19
View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async Task ReloadXaml(Page page, byte[] data = null)
{
try
{
Type pageType = page.GetType();
MethodInfo configureAfterLoadMethodInfo =
pageType.GetMethods(
BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Static
| BindingFlags.Instance
| BindingFlags.InvokeMethod)
.Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(RunAfterXamlLoadAttribute)))
.SingleOrDefault();
bool useAsyncConfigureAfterLoad = (configureAfterLoadMethodInfo?.CustomAttributes
.Any(x => x.AttributeType == typeof(AsyncStateMachineAttribute))).GetValueOrDefault(false);
Device.BeginInvokeOnMainThread(
async () =>
{
try
{
// We need to clear tool bar items
// because reloading the xaml seems
// not resetting the buttons
page.ToolbarItems?.Clear();
// Reload the xaml!
page.Resources.Clear();
if (data != null)
{
string xaml = DecompressXaml(data);
page.LoadFromXaml(xaml);
}
else
{
string pageId = page.GetType().FullName;
if (_xamlCache.TryGetValue(pageId, out data))
{
string xaml = DecompressXaml(data);
page.LoadFromXaml(xaml);
}
}
// Configure after xaml reload
// This is usally needed when some data is binded via code
if (useAsyncConfigureAfterLoad)
{
await (Task)configureAfterLoadMethodInfo?.Invoke(page, null);
}
else
{
configureAfterLoadMethodInfo?.Invoke(page, null);
}
// Notify that the xaml was loaded correctly
await _hubConnection.SendAsync("XamlReloaded", page.GetType().FullName, data);
System.Diagnostics.Debug.WriteLine($"Page '{page.GetType().FullName}' received a new xaml.");
}
catch (Exception ex)
{
// Notify that something went wrong
await _hubConnection.SendAsync("ThrowException", ex.ToString());
System.Diagnostics.Debug.WriteLine($"Unable to update the xaml for page '{page.GetType().FullName}'");
System.Diagnostics.Debug.WriteLine(ex);
}
});
}
catch (Exception ex)
{
// Notify that something went wrong
await _hubConnection.SendAsync("ThrowException", ex.ToString());
System.Diagnostics.Debug.WriteLine($"Unable to update the xaml for page '{page.GetType().FullName}'");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
View Source File : DisableRealXamlCommand.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void Execute(object sender, EventArgs e)
{
// Switch to the main thread - the call to AddCommand in SendreplacedemblyCommand's constructor requires
// the UI thread.
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(this.package.DisposalToken);
try
{
Projecreplacedem appPI = this.dte.Solution.FindProjecreplacedem("App.xaml") as Projecreplacedem;
if (appPI == null)
{
VsShellUtilities.ShowMessageBox(
this.package,
"You need to open a valid soultion first!",
"RealXaml",
OLEMSGICON.OLEMSGICON_WARNING,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
return;
}
await UpdateManager.Current.StopAsync();
this.MenuItem.Enabled = false;
EnableRealXamlCommand.Instance.MenuItem.Enabled = true;
VsShellUtilities.ShowMessageBox(
this.package,
"RealXaml is deactivated!",
"RealXaml",
OLEMSGICON.OLEMSGICON_WARNING,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("RealXaml was unable to deactivate itself!");
System.Diagnostics.Debug.WriteLine(ex);
VsShellUtilities.ShowMessageBox(
this.package,
"Unable to deactivate RealXaml!",
"RealXaml",
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void UpdateManager_ExceptionThrown(object sender, ExceptionNotificationEventArgs e)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
_outputPane.OutputString($"Something went wrong!");
_outputPane.OutputString(Environment.NewLine);
_outputPane.OutputString(e.Message);
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"Something went wrong!");
System.Diagnostics.Debug.WriteLine(e.Message);
}
19
View Source File : UpdateManager.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private void KillRunningProcesses()
{
if (File.Exists(_processDatFilePath))
{
using (var s = File.OpenText(_processDatFilePath))
{
int processId = 0;
try
{
while(!s.EndOfStream)
{
processId = Int32.Parse(s.ReadLine());
if (processId == 0)
continue;
var process = Process.GetProcessById(processId);
if (process != null && !process.HasExited)
process.Kill();
}
}
catch (Exception ex)
{
if (processId != 0)
System.Diagnostics.Debug.WriteLine($"RealXaml was unable to kill process with id {processId}");
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
19
View Source File : EnableRealXamlCommand.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void Execute(object sender, EventArgs e)
{
// Switch to the main thread - the call to AddCommand in SendreplacedemblyCommand's constructor requires
// the UI thread.
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(this.package.DisposalToken);
try
{
Projecreplacedem appPI = this.dte.Solution.FindProjecreplacedem("App.xaml") as Projecreplacedem;
if (appPI == null)
{
DisableRealXamlCommand.Instance.MenuItem.Enabled = false;
VsShellUtilities.ShowMessageBox(
this.package,
"You need to open a valid soultion first!",
"RealXaml",
OLEMSGICON.OLEMSGICON_WARNING,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
return;
}
await UpdateManager.Current.StartAsync();
this.MenuItem.Enabled = false;
DisableRealXamlCommand.Instance.MenuItem.Enabled = true;
VsShellUtilities.ShowMessageBox(
this.package,
"RealXaml is activated!",
"RealXaml",
OLEMSGICON.OLEMSGICON_INFO,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}
catch(Exception ex)
{
DisableRealXamlCommand.Instance.MenuItem.Enabled = false;
System.Diagnostics.Debug.WriteLine("RealXaml was unable to activate itself.");
System.Diagnostics.Debug.WriteLine(ex);
VsShellUtilities.ShowMessageBox(
this.package,
"Unable to activate RealXaml!",
"RealXaml",
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}
}
19
View Source File : SendAssemblyCommand.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void Execute(object sender, EventArgs e)
{
try
{
// Switch to the main thread - the call to AddCommand in SendreplacedemblyCommand's constructor requires
// the UI thread.
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(this.package.DisposalToken);
var dte = await this.package.GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
var projects = dte.ActiveSolutionProjects as Array;
var project = projects.Cast<Project>().FirstOrDefault();
if (project == null)
return;
EnvDTE.Property property = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath");
string fullPath = project.Properties.Item("FullPath").Value.ToString();
string outputFileName = project.Properties.Item("OutputFileName").Value.ToString();
string outputPath = property.Value.ToString();
string replacedemblyPath = Path.Combine(fullPath, outputPath, outputFileName);
using (MemoryStream ms = new MemoryStream())
{
// Make a copy of the file into memory to avoid any file lock
using (FileStream fs = File.OpenRead(replacedemblyPath))
await fs.CopyToAsync(ms);
UpdateManager.Current.Notifyreplacedembly(outputFileName, ms.ToArray());
this.OutputPane?.OutputString("Requesting replacedembly update...");
this.OutputPane?.OutputString(Environment.NewLine);
}
}
catch (Exception ex)
{
this.OutputPane?.OutputString($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
this.OutputPane?.OutputString(Environment.NewLine);
this.OutputPane?.OutputString(ex.ToString());
this.OutputPane?.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
//dte.Solution.SolutionBuild.BuildProject(
// project.ConfigurationManager.ActiveConfiguration.ConfigurationName,
// project.UniqueName);
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private async void UpdateManager_XamlUpdated(object sender, PageNotificationEventArgs e)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
_outputPane.OutputString($"The page '{e.PageId}' received a new xaml.");
_outputPane.OutputString(Environment.NewLine);
System.Diagnostics.Debug.WriteLine($"The page '{e.PageId}' received a new xaml.");
}
19
View Source File : MainPage.xaml.cs
License : MIT License
Project Creator : adrianstevens
License : MIT License
Project Creator : adrianstevens
private async void BtnToText_Clicked(object sender, EventArgs e)
{
var speech = new SpeechToText("{bing speech api key goes here");
var result = await speech.RecognizeSpeechAsync(audioRecording.GetFilePath());
System.Diagnostics.Debug.WriteLine(lblText.Text = result.DisplayText);
}
19
View Source File : SerializationTests.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
[Fact]
public void DefaultValue_Test()
{
System.Diagnostics.Debug.WriteLine(default(UInt64Value));
}
19
View Source File : DataMap.cs
License : MIT License
Project Creator : aerosoul94
License : MIT License
Project Creator : aerosoul94
private void VScrollBar_ValueChanged(object sender, EventArgs e)
{
Debug.WriteLine(vScrollBar.Value);
}
19
View Source File : RedisConnectionPool.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public void Connect(EndPoint endpoint, int timeout)
{
_socket = _pool.Connect();
System.Diagnostics.Debug.WriteLine("Got socket #{0}", _socket.LocalEndPoint);
}
19
View Source File : SocketPool.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public void Dispose()
{
foreach (var socket in _pool)
{
System.Diagnostics.Debug.WriteLine("Disposing socket #{0}", socket.LocalEndPoint);
socket.Dispose();
}
}
19
View Source File : FileSystem.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
private static void DumpDirToDebug(string indent, Directory dir)
{
Debug.WriteLine(indent + dir.Name);
indent += " ";
foreach (FSObject item in dir)
{
if (item.IsDirectory)
{
DumpDirToDebug(indent, item as Directory);
}
else
{
var file = item as File;
Debug.WriteLine(indent + item.Name + " (Size: " + file.Size + ", Compressed: " + file.IsCompressed +
")");
}
}
}
19
View Source File : ControlFlowAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
private static void DumpCodePath(CodePath path)
{
HLInstruction instruction = path.StartInstruction;
while (instruction != null)
{
Debug.WriteLine(instruction.Instruction.ToString());
if (instruction.BranchCodesPaths != null && instruction.BranchCodesPaths.Count > 0)
{
foreach (var item in instruction.BranchCodesPaths)
{
Debug.WriteLine(" " + item.Key + " --> " + item.Value.Name);
}
}
instruction = instruction.NextInstruction;
}
}
19
View Source File : DTSweep.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
private static void EdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node)
{
try
{
tcx.EdgeEvent.ConstrainedEdge = edge;
tcx.EdgeEvent.Right = edge.P.X > edge.Q.X;
if (IsEdgeSideOfTriangle(node.Triangle, edge.P, edge.Q))
{
return;
}
// For now we will do all needed filling
// TODO: integrate with flip process might give some better performance
// but for now this avoid the issue with cases that needs both flips and fills
FillEdgeEvent(tcx, edge, node);
EdgeEvent(tcx, edge.P, edge.Q, node.Triangle, edge.Q);
}
catch (PointOnEdgeException e)
{
Debug.WriteLine("Skipping Edge: {0}", e.Message);
}
}
19
View Source File : BboxToGeoCoordinateBoundsConverter.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var val = (Vector2dBounds)value;
// TODO: This is not working correctly, and setting "bbox: [0,0,0,0]" to Vector2d properties for some reason.
System.Diagnostics.Debug.WriteLine(val);
serializer.Serialize(writer, val.ToArray());
}
19
View Source File : Day05Tests.cs
License : MIT License
Project Creator : AlexChesser
License : MIT License
Project Creator : AlexChesser
[Test]
[TestCase("1,2,3,4,5", "3,4,5")]
[TestCase("1,2,3,4,5,6", "4,5,6")]
public void _876_Middle_of_the_Linked_List(string arr, string expected)
{
var s = new _876_Middle_of_the_Linked_List.Solution();
ListNode head = ListNode.Create(arr);
Debug.WriteLine(ListNode.replacedtring(head));
var result = s.MiddleNode(head);
replacedert.AreEqual(expected, ListNode.replacedtring(result));
}
19
View Source File : SuperIndexer.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public void SubmitGroupUpdate(IMessageContainer messageContainer, IEnumerable<Message> mostRecentMessages)
{
var messages = this.GroupUpdates.GetOrAdd(messageContainer.Id, new List<Message>());
messages.AddRange(mostRecentMessages);
Debug.WriteLine("Submitted updates for chat " + messageContainer.Name);
}
19
View Source File : USPSInternationalRates.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void USPS_Intl_Returns_Single_Rate_When_Using_Valid_Addresses_For_Single_Service()
{
var rateManager = new RateManager();
rateManager.AddProvider(new USPSInternationalProvider(_uspsUserId, "Priority Mail International"));
var response = rateManager.GetRates(_domesticAddress1, _internationalAddress2, _package1);
Debug.WriteLine(string.Format("Rates returned: {0}", response.Rates.Any() ? response.Rates.Count.ToString() : "0"));
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
replacedert.AreEqual(response.Rates.Count, 1);
replacedert.True(response.Rates.First().TotalCharges > 0);
Debug.WriteLine(response.Rates.First().Name + ": " + response.Rates.First().TotalCharges);
}
19
View Source File : USPSProviderTests.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void USPS_Domestic_Returns_Multiple_Rates_When_Using_Valid_Addresses_For_All_Services()
{
var rateManager = new RateManager();
rateManager.AddProvider(new USPSProvider(_uspsUserId));
var response = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
Debug.WriteLine(string.Format("Rates returned: {0}", response.Rates.Any() ? response.Rates.Count.ToString() : "0"));
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
replacedert.IsEmpty(response.InternalErrors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
19
View Source File : USPSProviderTests.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void USPS_Domestic_Returns_Multiple_Rates_When_Using_Valid_Addresses_For_All_Services_And_Multiple_Packages()
{
var rateManager = new RateManager();
rateManager.AddProvider(new USPSProvider(_uspsUserId));
var response = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
Debug.WriteLine(string.Format("Rates returned: {0}", response.Rates.Any() ? response.Rates.Count.ToString() : "0"));
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
19
View Source File : SuperIndexer.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public void EndTransaction()
{
Task.Run(async () =>
{
Debug.WriteLine("Ending Super Indexer Transaction...");
var result = this.WaitingOnGroupAndChatListings.WaitOne(TimeSpan.FromSeconds(10));
if (!result)
{
Debug.WriteLine("No group list available, loading new...");
var client = this.GroupsAndChats.FirstOrDefault()?.Client;
if (client == null)
{
return;
}
await client.GetGroupsAsync();
await client.GetChatsAsync();
this.GroupsAndChats = Enumerable.Concat<IMessageContainer>(client.Groups(), client.Chats());
}
this.OutdatedGroupIdList = this.CheckForOutdatedCache(this.GroupsAndChats);
Debug.WriteLine("Dirty groups computed, count " + this.OutdatedGroupIdList.Count);
using (var context = this.CacheManager.OpenNewContext())
{
// Update Group and Chat metadata in cache
if (DateTime.Now.Subtract(this.LastMetadataUpdate) > this.SettingsManager.CoreSettings.MetadataCacheInterval)
{
this.LastMetadataUpdate = DateTime.Now;
// Remove old metadata. Doing a removal and addition in the same cycle was causing
// OtherUserId foreign key for Chats to be null. Doing true updates with cascading deletes
// should be possible, but this can be done easily in SQLite without any further migrations (GMDC 33.0.3)
foreach (var metaData in this.GroupsAndChats)
{
if (metaData is Group groupMetadata)
{
var existing = context.GroupMetadata
.Include(g => g.Members)
.FirstOrDefault(g => g.Id == groupMetadata.Id);
if (existing != null)
{
foreach (var member in existing.Members)
{
context.Remove(member);
}
context.GroupMetadata.Remove(existing);
}
}
else if (metaData is Chat chatMetadata)
{
var existingChat = context.ChatMetadata.FirstOrDefault(c => c.Id == metaData.Id);
if (existingChat != null)
{
context.Remove(existingChat);
}
var existingMember = context.Find<Member>(chatMetadata.OtherUser.Id);
if (existingMember != null)
{
context.Remove(existingMember);
}
}
}
context.SaveChanges();
foreach (var addMetaData in this.GroupsAndChats)
{
context.Add(addMetaData);
}
context.SaveChanges();
}
// Process updates for each group and chat
var fullyUpdatedGroupIds = new List<string>();
foreach (var id in this.GroupUpdates.Keys)
{
var messages = this.GroupUpdates[id];
var groupState = context.IndexStatus.Find(id);
if (groupState == null)
{
// No cache status exists for this group. Force a full re-index.
}
else if (this.OutdatedGroupIdList.Contains(id))
{
var availableMessageIds = messages.Select(m => long.Parse(m.Id)).ToList();
var messageContainer = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);
long.TryParse(groupState.LastIndexedId, out var lastIndexId);
if (availableMessageIds.Contains(lastIndexId))
{
// All new messages have already been loaded and are ready to index.
var newMessages = new List<Message>();
var newLastIndexId = lastIndexId;
foreach (var msg in messages)
{
if (long.TryParse(msg.Id, out var messageId) && messageId > lastIndexId)
{
newMessages.Add(msg);
if (messageId > newLastIndexId)
{
newLastIndexId = messageId;
}
}
}
context.AddMessages(newMessages);
groupState.LastIndexedId = newLastIndexId.ToString();
context.SaveChanges();
fullyUpdatedGroupIds.Add(id);
}
}
}
Debug.WriteLine("In place deltas applied, resolved " + fullyUpdatedGroupIds.Count);
// Preplaced 2, go through all originally outdated chats and run the complete re-index task on them
// if they couldn't be automatically updated with available messages.
foreach (var id in this.OutdatedGroupIdList)
{
if (!fullyUpdatedGroupIds.Contains(id))
{
var container = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);
var cts = new CancellationTokenSource();
Debug.WriteLine("Full index scan required for " + container.Name);
// Don't start multiple overlapping indexing tasks.
var existingScan = this.TaskManager.RunningTasks.FirstOrDefault(t => t.Tag == id);
if (existingScan == null)
{
this.TaskManager.AddTask(
$"Indexing {container.Name}",
id,
this.IndexGroup(container, cts),
cts);
}
}
}
}
this.GroupUpdates.Clear();
this.WaitingOnGroupAndChatListings.Reset();
});
}
19
View Source File : PluginManager.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public void LoadPlugins(string pluginsPath)
{
if (!Directory.Exists(pluginsPath))
{
return;
}
string[] dllFileNames = Directory.GetFiles(pluginsPath, "*.dll");
ICollection<replacedembly> replacedemblies = new List<replacedembly>(dllFileNames.Length);
foreach (string dllFile in dllFileNames)
{
replacedembly pluginreplacedembly = LoadPlugin(dllFile);
replacedemblies.Add(pluginreplacedembly);
}
Type pluginType = typeof(PluginBase);
ICollection<Type> pluginTypes = new List<Type>();
foreach (replacedembly replacedembly in replacedemblies)
{
try
{
if (replacedembly != null)
{
Type[] types = replacedembly.GetTypes();
foreach (Type type in types)
{
if (type.IsInterface || type.IsAbstract)
{
continue;
}
else
{
if (type.IsSubclreplacedOf(pluginType))
{
pluginTypes.Add(type);
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error loading plugin {0}. Error Code: {1}", replacedembly.FullName, ex.Message);
}
}
this.GroupChatPlugins.Clear();
this.MessageComposePlugins.Clear();
foreach (Type type in pluginTypes)
{
var plugin = (PluginBase)Activator.CreateInstance(type);
if (plugin is IMessageComposePlugin messageComposePlugin)
{
this.MessageComposePlugins.Add(messageComposePlugin);
}
else if (plugin is IGroupChatPlugin groupChatPlugin)
{
this.GroupChatPlugins.Add(groupChatPlugin);
}
else if (plugin is IGroupChatCachePlugin groupChatCachePlugin)
{
this.GroupChatCachePlugins.Add(groupChatCachePlugin);
}
}
}
19
View Source File : UPSRates.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void UPS_Returns_Multiple_Rates_When_Using_Valid_Addresses_For_All_Services_And_Multple_Packages()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPreplacedword));
var response = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
19
View Source File : UPSRates.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void UPS_Returns_Rates_When_Using_International_Origin_And_Destination_Addresses_For_All_Services()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPreplacedword));
var response = rateManager.GetRates(InternationalAddress2, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
19
View Source File : UPSRates.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void UPS_Domestic_Returns_Rates_When_Using_International_Addresses_For_Single_Service()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPreplacedword, "UPS Worldwide Express"));
var response = rateManager.GetRates(DomesticAddress1, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
19
View Source File : UPSRates.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void UPS_Returns_Multiple_Rates_When_Using_Valid_Addresses_For_All_Services()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPreplacedword));
var response = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
19
View Source File : UPSRates.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void UPS_Returns_Rates_When_Using_International_Destination_Addresses_And_RetailRates_For_All_Services()
{
var rateManager = new RateManager();
var provider = new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPreplacedword)
{
UseRetailRates = true
};
rateManager.AddProvider(provider);
var response = rateManager.GetRates(DomesticAddress1, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
19
View Source File : UPSRates.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
[Test]
public void UPS_Returns_Rates_When_Using_International_Destination_Addresses_For_All_Services()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPreplacedword));
var response = rateManager.GetRates(DomesticAddress1, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
replacedert.NotNull(response);
replacedert.IsNotEmpty(response.Rates);
replacedert.IsEmpty(response.Errors);
foreach (var rate in response.Rates)
{
replacedert.NotNull(rate);
replacedert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
See More Examples