System.Diagnostics.Debug.WriteLine(object)

Here are the examples of the csharp api System.Diagnostics.Debug.WriteLine(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

947 Examples 7

19 View Source File : Cloner.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public static bool TryClone<T>(T toClone, out T newObject)
        {
            if (toClone.GetType().IsValueType)
            {
                newObject = toClone;
                return true;
            }

            if (toClone is ICloneable cloneable)
            {
                newObject = (T)cloneable.Clone();
                return true;
            }

            Debug.WriteLine(toClone.GetType());

            if (Cloners.TryGetValue(toClone.GetType(), out IObjectCloner cloner))
            {
                newObject = (T)cloner.Clone(toClone);
                return true;
            }

            if (toClone.GetType().GetConstructor(Type.EmptyTypes) == null)
            {
                newObject = (T)Activator.CreateInstance(toClone.GetType());
                return false;
            }

            newObject = default;
            return false;
        }

19 View Source File : WindowHooks.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private static bool MonitorEnumCallBack(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData)
            {
                Debug.WriteLine(hMonitor);
                MONITORINFO mon_info = new();
                mon_info.cbSize = (uint)Marshal.SizeOf(mon_info);
                NativeMethods.GetMonitorInfo(hMonitor, mon_info);
                Debug.WriteLine(Marshal.GetLastWin32Error());
                AllMonitorInfo.Add(mon_info);
                return true;
            }

19 View Source File : WindowHooks.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public static Rectangle CurrentMonitorSize()
        {
            NativeMethods.GetCursorPos(out POINT lpPoint);
            IntPtr lPrimaryScreen = NativeMethods.MonitorFromPoint(lpPoint, NativeMethods.MonitorOptions.MONITOR_DEFAULTTOPRIMARY);
            MONITORINFO lPrimaryScreenInfo = new();
            lPrimaryScreenInfo.cbSize = (uint)Marshal.SizeOf(lPrimaryScreenInfo);
            if (NativeMethods.GetMonitorInfo(lPrimaryScreen, lPrimaryScreenInfo) == false)
            {
                Debug.WriteLine(Marshal.GetLastWin32Error());
                return new Rectangle();
            }
            return new Rectangle { Rect = lPrimaryScreenInfo.rcWork };
        }

19 View Source File : YouTubeVideoIdExtension.cs
License : MIT License
Project Creator : adamfisher

public object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {
                Debug.WriteLine($"Acquiring YouTube stream source URL from VideoId='{VideoId}'...");
                var videoInfoUrl = $"http://www.youtube.com/get_video_info?video_id={VideoId}";

                using (var client = new HttpClient())
                {
                    var videoPageContent = client.GetStringAsync(videoInfoUrl).Result;
                    var videoParameters = HttpUtility.ParseQueryString(videoPageContent);
                    var encodedStreamsDelimited = WebUtility.HtmlDecode(videoParameters["url_encoded_fmt_stream_map"]);
                    var encodedStreams = encodedStreamsDelimited.Split(',');
                    var streams = encodedStreams.Select(HttpUtility.ParseQueryString);

                    var streamsByPriority = streams
                        .OrderBy(s =>
                        {
                            var type = s["type"];
                            if (type.Contains("video/mp4")) return 10;
                            if (type.Contains("video/3gpp")) return 20;
                            if (type.Contains("video/x-flv")) return 30;
                            if (type.Contains("video/webm")) return 40;
                            return int.MaxValue;
                        })
                        .ThenBy(s =>
                        {
                            var quality = s["quality"];

                            switch (Device.Idiom)
                            {
                                case TargetIdiom.Phone:
                                    return Array.IndexOf(new[] { "medium", "high", "small" }, quality);
                                default:
                                    return Array.IndexOf(new[] { "high", "medium", "small" }, quality);
                            }
                        })
                        .FirstOrDefault();

                    Debug.WriteLine($"Stream URL: {streamsByPriority["url"]}");
					return VideoSource.FromUri(streamsByPriority["url"]);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error occured while attempting to convert YouTube video ID into a remote stream path.");
                Debug.WriteLine(ex);
            }

            return null;
        }

19 View Source File : HttpUtility.cs
License : MIT License
Project Creator : adamfisher

public static string GetFileContents(string filePath)
        {
            var contents = string.Empty;
            var path = filePath.ToLower();

            try
            {
                if (path.StartsWith("http:") || path.StartsWith("https:"))
                    return contents;

                var httpClient = new HttpClient();

                using (var stream = httpClient.GetStreamAsync(filePath).Result)
                using (var reader = new StreamReader(stream))
                {
                    contents = reader.ReadToEnd();
                }
			}
			catch(Exception ex)
			{
				Debug.WriteLine (ex);
			}

            return contents;
        }

19 View Source File : VimeoVideoIdExtension.cs
License : MIT License
Project Creator : adamfisher

public object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {
                Debug.WriteLine($"Acquiring Vimeo stream source URL from VideoId='{VideoId}'...");
                var videoInfoUrl = $"https://player.vimeo.com/video/{VideoId}/config";

                using (var client = new HttpClient())
                {
                    var videoPageContent = client.GetStringAsync(videoInfoUrl).Result;
                    var videoPageBytes = Encoding.UTF8.GetBytes(videoPageContent);

                    using (var stream = new MemoryStream(videoPageBytes))
                    {
                        var serializer = new DataContractJsonSerializer(typeof(VimeoVideo));
                        var metaData = (VimeoVideo)serializer.ReadObject(stream);
                        var files = metaData.request.files.progressive;

                        // Exact match
                        var url = files.OrderByDescending(s => s.width).Select(s => s.url).FirstOrDefault();

                        Debug.WriteLine($"Stream URL: {url}");
                        return VideoSource.FromUri(url);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error occured while attempting to convert Vimeo video ID into a remote stream path.");
                Debug.WriteLine(ex);
            }

            return null;
        }

19 View Source File : CoverletCoverageProvider.cs
License : MIT License
Project Creator : ademanuele

CoverageParameters ParseSettings(XmlNode coverageSettings)
    {
      try
      {        
        string configurationXml = coverageSettings.InnerXml;
        XmlSerializer serializer = new XmlSerializer(typeof(CoverletRunSettingsConfiguration));
        using StringReader reader = new StringReader(configurationXml);
        CoverletRunSettingsConfiguration settings = (CoverletRunSettingsConfiguration)serializer.Deserialize(reader);
        return settings.ToParameters();
      }
      catch (Exception e)
      {
        Debug.WriteLine(e);
        return defaultCoverageParameters;
      }
    }

19 View Source File : RxPageHost.cs
License : MIT License
Project Creator : adospace

private void OnLayout()
        {
            try
            {
                Layout();
                SetupAnimationTimer();
            }
            catch (Exception ex)
            {
                RxApplication.Instance?.FireUnhandledExpectionEvent(ex);
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

19 View Source File : RxApplication.cs
License : MIT License
Project Creator : adospace

internal void FireUnhandledExpectionEvent(Exception ex)
        {
            UnhandledException?.Invoke(new UnhandledExceptionEventArgs(ex, false));
            System.Diagnostics.Debug.WriteLine(ex);
        }

19 View Source File : ApiPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected override void OnPageLoaded()
        {
            IsFailed = false;
            Message = null;
            State = 0;
            try
            {
                DoActin(_action);
            }
            catch (AgebullBusinessException exception)
            {
                IsFailed = true;
                Message = exception.Message;
            }
            catch (Exception exception)
            {
                IsFailed = true;
                State = 3;
                Message = "*--系统内部错误--*";
                Debug.WriteLine(exception);
                LogRecorder.Error(exception.StackTrace);
                LogRecorder.Error(exception.ToString());
                LogRecorder.MonitorTrace("Exception:"+ exception.Message);
            }
        }

19 View Source File : ApiPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected override void OnResult()
        {
            Response.Clear();
            try
            {
                if (string.IsNullOrWhiteSpace(CustomJson))
                {
#if NewJson
                    var msg = string.IsNullOrEmpty(Message)
                        ? (IsFailed ? BusinessContext.Current.LastMessage ?? "操作失败" : "操作成功")
                        : Message.Replace('\"', '\'');
                    if (AjaxResult == null)
                    {
                        AjaxResult = new AjaxResult
                        {
                            State = State,
                            Succeed = !IsFailed,
                            Message = msg,
                            Message2 = Message2
                        };
                    }
                    else
                    {
                        AjaxResult.Message = msg;
                        AjaxResult.Message2 = Message2;
                        AjaxResult.Succeed = !IsFailed;
                        AjaxResult.State = State;
                    }
                    CustomJson = JsonConvert.SerializeObject(AjaxResult);
#else
                var json = new StringBuilder();
                json.AppendFormat(@"{{""succeed"":{0}", this.IsFailed ? "false" : "true");
                json.AppendFormat(@",""message"":""{0}""",
                    string.IsNullOrEmpty(this.Message)
                        ? (this.IsFailed ? "操作失败" : "操作成功")
                        : this.Message.Replace('\"', '\''));
                if (!string.IsNullOrWhiteSpace(this.ResultData))
                {
                    json.AppendFormat(@",{0}", this.ResultData);
                }
                json.Append('}');
                this.CustomJson = json.ToString();
#endif
                }
                Response.Write(CustomJson);
            }
            catch (Exception exception)
            {
                LogRecorder.Error(exception.ToString());
                Debug.WriteLine(exception);
                Response.Write(@"{""succeed"":false,""message"":""***系统内部错误**""}");
            }
            LogRecorder.MonitorTrace(CustomJson);
        }

19 View Source File : MyPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected void Page_Load(object sender, EventArgs e)
        {
            CurrentPageName = GetFriendPageUrl();
            LogRecorder.BeginMonitor(CurrentPageName);
            LogRecorder.MonitorTrace(Request.Url.AbsolutePath);

            LogRequestInfo();
            try
            {
                ProcessRequest();
            }
            catch (Exception exception)
            {
                LogRecorder.EndStepMonitor();
                LogRecorder.BeginStepMonitor("Exception");
                LogRecorder.MonitorTrace(exception.Message);
                LogRecorder.Exception(exception);
                Debug.WriteLine(exception);
                OnFailed(exception);
                LogRecorder.EndStepMonitor();
            }
            LogRecorder.BeginStepMonitor("Result");
            OnResult();
            LogRecorder.EndStepMonitor();
            LogRecorder.EndMonitor();
        }

19 View Source File : TfsSourceCodeHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void CheckIn()
        {
            int changesetForAdd;
            //������ļ��Ŷӵȴ�Ǩ��TFS����
            _workspace.PendAdd(_codeFile);

            //  �����ȴ���ӵ��ļ����
            var pendingAdds = new List<PendingChange>(_workspace.GetPendingChanges(_codeFile));
            var array = pendingAdds.ToArray();
            if (array.Length <= 0 ||
                !array.Any(p => string.Equals(p.FileName, _codeFile, StringComparison.InvariantCultureIgnoreCase)))
            {
                changesetForAdd = _workspace.Undo(_codeFile);
                Debug.WriteLine(changesetForAdd);
                return;
            }
            var a2 =
                array.Where(p => string.Equals(p.FileName, _codeFile, StringComparison.InvariantCultureIgnoreCase))
                    .ToArray();
            // ��������CheckInϵͳ��
            changesetForAdd = _workspace.CheckIn(a2, "������Զ��ύ");
            Debug.WriteLine(changesetForAdd);
        }

19 View Source File : ItemsViewModel.cs
License : MIT License
Project Creator : aimore

async Task ExecuteLoadItemsCommand()
        {
            if (IsBusy)
                return;

            IsBusy = true;

            try
            {
                Items.Clear();
                var items = await DataStore.GereplacedemsAsync(true);
                foreach (var item in items)
                {
                    Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }

19 View Source File : FileSource.cs
License : MIT License
Project Creator : alen-smajic

private IAsyncRequest proxyResponse(
			string url
			, Action<Response> callback
			, int timeout
			, CanonicalTileId tileId
			, string tilesetId
		)
		{

			// TODO: plugin caching somewhere around here

			var request = IAsyncRequestFactory.CreateRequest(
				url
				, (Response response) =>
				{
					if (response.XRateLimitInterval.HasValue) { XRateLimitInterval = response.XRateLimitInterval; }
					if (response.XRateLimitLimit.HasValue) { XRateLimitLimit = response.XRateLimitLimit; }
					if (response.XRateLimitReset.HasValue) { XRateLimitReset = response.XRateLimitReset; }
					callback(response);
					lock (_lock)
					{
						//another place to catch if request has been cancelled
						try
						{
							_requests.Remove(response.Request);
						}
						catch (Exception ex)
						{
							System.Diagnostics.Debug.WriteLine(ex);
						}
					}
				}
				, timeout
			);
			lock (_lock)
			{
				//sometimes we get here after the request has already finished
				if (!request.IsCompleted)
				{
					_requests.Add(request, 0);
				}
			}
			//yield return request;
			return request;
		}

19 View Source File : FileSource.cs
License : MIT License
Project Creator : alen-smajic

public void WaitForAllRequests()
		{
			int waitTimeMs = 200;
			while (_requests.Count > 0)
			{
				lock (_lock)
				{
					List<IAsyncRequest> reqs = _requests.Keys.ToList();
					for (int i = reqs.Count - 1; i > -1; i--)
					{
						if (reqs[i].IsCompleted)
						{
							// another place to watch out if request has been cancelled
							try
							{
								_requests.Remove(reqs[i]);
							}
							catch (Exception ex)
							{
								System.Diagnostics.Debug.WriteLine(ex);
							}
						}
					}
				}

#if WINDOWS_UWP
				System.Threading.Tasks.Task.Delay(waitTimeMs).Wait();
#else
				//Thread.Sleep(50);
				// TODO: get rid of DoEvents!!! and find non-blocking wait that works for Net3.5
				//System.Windows.Forms.Application.DoEvents();

				var resetEvent = new ManualResetEvent(false);
				ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
				{
					Thread.Sleep(waitTimeMs);
					resetEvent.Set();
				}), null);
				UnityEngine.Debug.Log("before waitOne " + DateTime.Now.Ticks);
				resetEvent.WaitOne();
				UnityEngine.Debug.Log("after waitOne " + DateTime.Now.Ticks);
				resetEvent.Close();
				resetEvent = null;
#endif
			}
		}

19 View Source File : Plot.cs
License : MIT License
Project Creator : AlexGyver

protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            try
            {
                lock (this.invalidateLock)
                {
                    if (this.isModelInvalidated)
                    {
                        if (this.model != null)
                        {
                            this.model.Update(this.updateDataFlag);
                            this.updateDataFlag = false;
                        }

                        this.isModelInvalidated = false;
                    }
                }

                lock (this.renderingLock)
                {
                    this.renderContext.SetGraphicsTarget(e.Graphics);
                    if (this.model != null)
                    {
                        this.model.Render(this.renderContext, this.Width, this.Height);
                    }

                    if (this.zoomRectangle != Rectangle.Empty)
                    {
                        using (var zoomBrush = new SolidBrush(Color.FromArgb(0x40, 0xFF, 0xFF, 0x00)))
                        using (var zoomPen = new Pen(Color.Black))
                        {
                            zoomPen.DashPattern = new float[] { 3, 1 };
                            e.Graphics.FillRectangle(zoomBrush, this.zoomRectangle);
                            e.Graphics.DrawRectangle(zoomPen, this.zoomRectangle);
                        }
                    }
                }
            }
            catch (Exception paintException)
            {
                var trace = new StackTrace(paintException);
                Debug.WriteLine(paintException);
                Debug.WriteLine(trace);
                using (var font = new Font("Arial", 10))
                {
                    e.Graphics.DrawString(
                        "OxyPlot paint exception: " + paintException.Message, font, Brushes.Red, 10, 10);
                }
            }
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : alexrainman

public async Task Get()
        {
            var response = await client.GetAsync(new Uri("https://restcountries.eu/data/ala.svg"));

            Debug.WriteLine(response.Content);
        }

19 View Source File : NetMidiDownload.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static string DownloadMidi(string id)
        {



                try
                {
                    var request = (HttpWebRequest)WebRequest.Create(url+id);
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                    var response = (HttpWebResponse)request.GetResponse();
                using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        var responseString = reader.ReadToEnd();
                        return responseString;

                    }
                }
                
                    
                }
                catch (Exception e)
                {

                    Debug.WriteLine(e);
                    throw e;
                }



            
        }

19 View Source File : CodeFixProvider.cs
License : GNU General Public License v3.0
Project Creator : AminEsmaeily

private static async Task<Doreplacedent> AddAnnotationAsync(CodeFixContext context, CancellationToken cancellationToken)
        {
            var doreplacedent = context.Doreplacedent;
            var root = await doreplacedent.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            SemanticModel sm = await doreplacedent.GetSemanticModelAsync();
            SyntaxToken invocation = root.FindToken(diagnosticSpan.Start);
            InvocationExpressionSyntax completeMethod = await GetInvokedMethodAsync(context, cancellationToken);

            MethodDeclarationSyntax callerMethodContainer = (MethodDeclarationSyntax)invocation.Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();

            var calleeAttributes = NotHandledreplacedyzer.GetAllAttributes(sm, completeMethod);
            var catchedAttributes = await GetCallerAttributesAsync(context, cancellationToken);
            var tryElement = invocation.Parent.FirstAncestorOrSelf<TryStatementSyntax>();

            var newAttributes = callerMethodContainer.AttributeLists;
            foreach(var attrib in calleeAttributes)
            {
                var skip = false;
                var typeParameter = attrib.AttributeData.ConstructorArguments.FirstOrDefault(f => f.Type.TypeKind == TypeKind.Clreplaced);
                if (typeParameter.Type == null)
                    continue;

                var exceptionName = typeParameter.Value.ToString();
                foreach (var catchedAttribute in catchedAttributes)
                {
                    var typeOfExp = catchedAttribute.DescendantNodes().OfType<TypeOfExpressionSyntax>();
                    if (typeOfExp == null || !typeOfExp.Any())
                    {
                        skip = true;
                        continue;
                    }

                    var identifier = typeOfExp.First().DescendantNodes().OfType<IdentifierNameSyntax>();
                    if (identifier == null || !identifier.Any())
                    {
                        skip = true;
                        continue;
                    }

                    var semanticType = sm.GetTypeInfo(identifier.First()).Type;
                    if (semanticType != null && exceptionName.Equals(semanticType.ToString()))
                    {
                        skip = true;
                        break;
                    }
                }

                if (!skip && tryElement != null)
                {
                    foreach (var f in tryElement.Catches)
                    {
                        if (f.Declaration != null)
                            foreach (var k in f.Declaration.DescendantNodes().OfType<IdentifierNameSyntax>())
                            {
                                var typeInfo = sm.GetTypeInfo(k);
                                if (typeInfo.Type == null)
                                    continue;

                                if (typeInfo.Type.ToString().Equals(typeof(Exception).FullName) ||
                                    typeInfo.Type.ToString().Equals(exceptionName))
                                {
                                    skip = true;
                                    break;
                                }
                            }

                        if (skip)
                            break;
                    }
                }

                if (skip)
                    continue;

                var attributeName = typeof(ThrowsExceptionAttribute).FullName.Substring(0, typeof(ThrowsExceptionAttribute).FullName.IndexOf("Attribute"));
                newAttributes = newAttributes.Add(
                    SyntaxFactory.AttributeList(
                        SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
                        SyntaxFactory.Attribute(
                            SyntaxFactory.IdentifierName(attributeName)).WithArgumentList(
                            SyntaxFactory.AttributeArgumentList(
                                SyntaxFactory.SingletonSeparatedList<AttributeArgumentSyntax>(
                                SyntaxFactory.AttributeArgument(
                                    SyntaxFactory.TypeOfExpression(
                                    SyntaxFactory.IdentifierName(exceptionName)))))))));
            }

            try
            {
                return doreplacedent.WithSyntaxRoot(root.ReplaceNode(callerMethodContainer, callerMethodContainer.WithAttributeLists(newAttributes)));
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex);
                return doreplacedent.WithSyntaxRoot(root);
            }
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void Button_Click_3(object sender, RoutedEventArgs e)
        {
            roomlist.Items.Clear();
            int size = 0;
            int count = 0;

            try
            {
                Task<dynamic> t = object1.publicroom();
                await t;

                foreach (dynamic x in t.Result.chunk)
                {
                    size++;
                }

                Debug.WriteLine(size);
                Window1.room = new string[size, 2];
                count = 0;

                foreach (dynamic x in t.Result.chunk)
                {
                    try
                    {
                        room[count, 0] = t.Result.chunk[count].aliases[0];
                    }
                    catch
                    {
                        room[count, 0] = t.Result.chunk[count].name;
                    }

                    room[count, 1] = t.Result.chunk[count].room_id;
                    roomlist.Items.Add(room[count, 0]);
                    count++;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

19 View Source File : CodeFixProvider.cs
License : GNU General Public License v3.0
Project Creator : AminEsmaeily

private static async Task<Doreplacedent> AddTryCatchAsync(CodeFixContext context, CancellationToken cancellationToken)
        {
            var doreplacedent = context.Doreplacedent;
            var root = await doreplacedent.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            SyntaxToken invocation = root.FindToken(diagnosticSpan.Start);

            InvocationExpressionSyntax completeMethod = await GetInvokedMethodAsync(context, cancellationToken);

            SemanticModel sm = await doreplacedent.GetSemanticModelAsync();
            var calleeAttributes = NotHandledreplacedyzer.GetAllAttributes(sm, completeMethod);
            var catchedAttributes = await GetCallerAttributesAsync(context, cancellationToken);
            var tryElement = invocation.Parent.FirstAncestorOrSelf<TryStatementSyntax>();

            var oldRoot = await doreplacedent.GetSyntaxRootAsync(cancellationToken);
            SyntaxNode newRoot = null;

            var catches = new List<CatchClauseSyntax>();
            foreach (var attrib in calleeAttributes)
            {
                var skip = false;
                var typeParameter = attrib.AttributeData.ConstructorArguments.FirstOrDefault(f => f.Type.TypeKind == TypeKind.Clreplaced);
                if (typeParameter.Type == null)
                    continue;

                var exceptionName = typeParameter.Value.ToString();
                foreach (var catchedAttribute in catchedAttributes)
                {
                    var typeOfExp = catchedAttribute.DescendantNodes().OfType<TypeOfExpressionSyntax>();
                    if (typeOfExp == null || !typeOfExp.Any())
                    {
                        skip = true;
                        continue;
                    }

                    var identifier = typeOfExp.First().DescendantNodes().OfType<IdentifierNameSyntax>();
                    if (identifier == null || !identifier.Any())
                    {
                        skip = true;
                        continue;
                    }

                    var semanticType = sm.GetTypeInfo(identifier.First()).Type;
                    if (semanticType != null && exceptionName.Equals(semanticType.ToString()))
                    {
                        skip = true;
                        break;
                    }
                }

                if (skip)
                    continue;

                bool createCatchPart = tryElement == null;
                if (!createCatchPart)
                {
                    var exists = false;
                    foreach (var f in tryElement.Catches)
                    {
                        if (f.Declaration != null)
                            foreach (var k in f.Declaration.DescendantNodes().OfType<IdentifierNameSyntax>())
                            {
                                var typeInfo = sm.GetTypeInfo(k);
                                if (typeInfo.Type == null)
                                    continue;

                                if (typeInfo.Type.ToString().Equals(typeof(Exception).FullName) ||
                                    typeInfo.Type.ToString().Equals(exceptionName))
                                {
                                    exists = true;
                                    break;
                                }
                            }

                        if (exists)
                            break;
                    }

                    createCatchPart = !exists;
                }
                
                if (createCatchPart)
                {
                    IdentifierNameSyntax catchTypeSyntax = SyntaxFactory.IdentifierName(exceptionName);
                    var catchDeclaration = SyntaxFactory.CatchDeclaration(catchTypeSyntax, new SyntaxToken());
                    var blockSyntax = SyntaxFactory.Block();
                    var catchPart = SyntaxFactory.CatchClause(catchDeclaration, null, blockSyntax);

                    catches.Add(catchPart);
                }
            }

            try
            {
                if (tryElement != null)
                    newRoot = oldRoot.InsertNodesAfter(tryElement.Catches.Last(), catches);
                else
                {
                    var body = completeMethod.FirstAncestorOrSelf<StatementSyntax>();
                    var expressionIndex = body.Parent.ChildNodesAndTokens().ToList().IndexOf(body);
                    BlockSyntax block = SyntaxFactory.Block(body);

                    TryStatementSyntax trySyntax = SyntaxFactory.TryStatement(block, new SyntaxList<CatchClauseSyntax>(), null);
                    trySyntax = trySyntax.AddCatches(catches.ToArray()).NormalizeWhitespace(elasticTrivia:true);

                    newRoot = oldRoot.ReplaceNode(body, trySyntax);
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex);
            }

            return doreplacedent.WithSyntaxRoot(newRoot);
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void getver()
        {
            string finalres =null;
            string value;

            try
            {
                Task<dynamic> t = object1.version();
                await t;

                foreach (string x in t.Result.versions)
                {
                    value = x;
                    Debug.WriteLine(value);
                    finalres = finalres + "Version " + value + "\n";
                }

                Debug.WriteLine(finalres);
                versionbox.Text = finalres;
            }
            catch (Exception ex)
            {
                versionbox.Text = "Error fetching supported version!";
                Debug.WriteLine(ex);

            }
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string user = usernamebox.Text;
            statusbox2.Doreplacedent.Blocks.Clear();
            statusbox2.AppendText("Querying data, please wait...");

            try
            {
                Task<dynamic> t = object1.Whois(usernamebox.Text);
                await t;
                statusbox2.Doreplacedent.Blocks.Clear();
                string username = t.Result.user_id;
                Debug.WriteLine(username);
                statusbox2.AppendText("User ID: " + t.Result.user_id + "\n\n");

                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(t.Result.devices))
                {
                  string name = descriptor.Name;
                  object value = descriptor.GetValue(t.Result.devices);
                  statusbox2.AppendText(name+" : "+value+"\n");
                 }
            }
            catch (Exception ex)
            {
                statusbox2.AppendText("Something went wrong...\n");
                statusbox2.AppendText("ex");
                Debug.WriteLine(ex);
            }
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void create_click(object sender, RoutedEventArgs e)
        {
            string user = username_create.Text;
            string preplaced = preplacedword_create.Preplacedword;
            string sec = secret_create.Preplacedword;
            bool? admin = admin_check.IsChecked;

            Debug.WriteLine(user);
            Debug.WriteLine(preplaced);
            Debug.WriteLine(sec);
            Debug.WriteLine(admin);

            statusbox2.Doreplacedent.Blocks.Clear();

            try
            {
                Task<string> t = object1.create(user, preplaced, admin, sec);
                await t;
                statusboxcreate.Content = "User created!";
                username_create.Text = "";
                preplacedword_create.Preplacedword = "";
                secret_create.Preplacedword = "";
            }
            catch (Exception ex)
            {
                statusboxcreate.Content = "Something went wrong...";
                Debug.WriteLine(ex);
            }
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void Purge_Button(object sender, RoutedEventArgs e)
        {
            MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Purging a room will kick out all users including you and will never be accessible again.", "PURGE ROOM?", System.Windows.MessageBoxButton.YesNo);
            if (messageBoxResult == MessageBoxResult.Yes)
            {
                try
                {
                    Task<dynamic> t = object1.purge(roomidbox.Text);
                    await t;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
        }

19 View Source File : CodeFixProvider.cs
License : GNU General Public License v3.0
Project Creator : AminEsmaeily

private static async Task<IEnumerable<AttributeListSyntax>> GetCallerAttributesAsync(CodeFixContext context, CancellationToken cancellationToken)
        {
            SemanticModel sm = await context.Doreplacedent.GetSemanticModelAsync();
            var root = await context.Doreplacedent.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            SyntaxToken invocation = root.FindToken(diagnosticSpan.Start);

            MethodDeclarationSyntax callerMethod = (MethodDeclarationSyntax)invocation.Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();
            SyntaxNode callerClreplaced = invocation.Parent.AncestorsAndSelf().OfType<ClreplacedDeclarationSyntax>().FirstOrDefault();
            try
            {
                var result = ((MethodDeclarationSyntax)callerMethod).AttributeLists
                    .Union(((ClreplacedDeclarationSyntax)callerClreplaced).AttributeLists)
                    .Where(f => (f.DescendantNodes().OfType<QualifiedNameSyntax>().Any() &&
                                sm.GetTypeInfo(f.DescendantNodes().OfType<QualifiedNameSyntax>().FirstOrDefault()).Type != null &&
                                sm.GetTypeInfo(f.DescendantNodes().OfType<QualifiedNameSyntax>().FirstOrDefault()
                                                .DescendantNodes().OfType<IdentifierNameSyntax>().Last()).Type.ToString().Equals(typeof(ThrowsExceptionAttribute).FullName)) ||
                                (f.DescendantNodes().OfType<IdentifierNameSyntax>().Any() &&
                                 sm.GetTypeInfo(f.DescendantNodes().OfType<IdentifierNameSyntax>().First()).Type != null &&
                                 sm.GetTypeInfo(f.DescendantNodes().OfType<IdentifierNameSyntax>().First()).Type.ToString().Equals(typeof(ThrowsExceptionAttribute).FullName))).ToList();
                return result;

            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex);
                throw ex;
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string user = UserBox.Text;
            string preplacedword = PreplacedBox.Preplacedword;
            string homeserver = HomeserverBox.Text;
            object1 = new trinity(homeserver=homeserver.ToString());
            statustext.Content = "Logging in, please wait";

            try
            {
                loginbutton.IsEnabled = false;
                Task<string> t = object1.Login(user, preplacedword);
                await t;
                Debug.WriteLine(t.Result);
                statustext.Content = "Login Success!";

                
                Window1 form = new Window1(object1.gettoken(), homeserver, object1.getadmin(), preplacedword);
                form.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
                loginbutton.IsEnabled = true;
                statustext.Content = "";
                Debug.WriteLine(ex);
            }
        }

19 View Source File : trinity.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

public async Task<dynamic> purge(string roomid)
        {
            int size = 0 ;
            int count = 0;
            string[] members;

            //GET THE MEMBERS INTO AN ARRAY
            string memberquery = "/_matrix/client/r0/rooms/"+roomid+"/members";
            string joinroom = "/_matrix/client/r0/rooms/{roomId}/join";
            string kickquery = "/_matrix/client/r0/rooms/"+roomid+"/kick";
            string setprivate = "/_matrix/client/r0/rooms/"+roomid+ "/state/m.room.join_rules";
            string delist = "/_matrix/client/r0/directory/list/room/"+roomid;

            string query = BASE_URL + memberquery + authstring;
            string joinroomm = BASE_URL + joinroom + authstring;
            string kickqueryy = BASE_URL + kickquery + authstring;
            string setprivatee = BASE_URL + setprivate + authstring;
            string delistt = BASE_URL + delist + authstring;

            string joinjson = "{\"room_id\": \""+roomid+"\"}";
            await client.PostAsync(kickqueryy, new StringContent(joinjson, Encoding.UTF8, "application/json"));

            Debug.WriteLine(query);
            var response = await client.GetAsync(query);
            var mes = await response.Content.ReadreplacedtringAsync();
            checkresp(response.StatusCode);

            Debug.WriteLine(mes);

            dynamic values = JsonConvert.DeserializeObject<dynamic>(mes);

            foreach (dynamic x in values.chunk)
            {
                size++;
            }

            Debug.WriteLine(size);
            members = new string[size];
            count = 0;

            foreach (dynamic x in values.chunk)
            {
                members[count] = values.chunk[count].user_id;
                Debug.WriteLine(members[count]);
                count++;
            }

            //Delist room and lockdown

            string json3 = "{\"visibility\": \"private\"}";
            await client.PutAsync(delistt, new StringContent(json3, Encoding.UTF8, "application/json"));

            string json2 = "{\"join_rule\": \"invite\"}";
            await client.PutAsync(setprivatee, new StringContent(json2, Encoding.UTF8, "application/json"));

            //Proceeds to kick all members
            foreach (string x in members)
            {
                if (x != adminuser)
                {
                    Debug.WriteLine("KICKED: " + x);
                    string json = "{\"reason\": \"This room has been purged\", \"user_id\": \"" + x + "\"}";
                    await client.PostAsync(kickqueryy, new StringContent(json, Encoding.UTF8, "application/json"));
                }
            }
            Debug.WriteLine("KICKED: " + adminuser);
            string jsona = "{\"reason\": \"This room has been purged\", \"user_id\": \"" + adminuser + "\"}";
            await client.PostAsync(kickqueryy, new StringContent(jsona, Encoding.UTF8, "application/json"));

            return null;
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

protected async override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            Debug.WriteLine("CLOSINGGGG");
            try
            {
                Debug.WriteLine("Logging out");
                Task<string> t = object1.Logout();
                await t;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("logoutfail");
                Debug.WriteLine(ex);
            }
            Application.Current.Shutdown();
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string user = usernamebox.Text;
            statusbox2.Doreplacedent.Blocks.Clear();

            try
            {
                Task<string> t = object1.deactivate(usernamebox.Text);
                await t;

                statusbox2.AppendText("User sucessfully deactivated\n");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

19 View Source File : Interface.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aminhusni

private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            string user = usernamebox.Text;
            statusbox2.Doreplacedent.Blocks.Clear();

            try
            {
                Task<string> t = object1.reset(usernamebox.Text);
                await t;
                string stringgy = t.Result;
                statusbox2.AppendText("Temporary Preplacedword:" + stringgy);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

19 View Source File : AnkhErrorHandler.cs
License : Apache License 2.0
Project Creator : AmpScm

public void Invoke(Exception ex, ExceptionInfo info)
            {
                try
                {
                    // BH: Uses reflection to find the best match based on the exception??

                    Type t = typeof(HandlerDelegator);
                    MethodInfo method = t.GetMethod("DoHandle", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { ex.GetType(), typeof(ExceptionInfo) }, null);

                    if (method != null)
                        method.Invoke(this, new object[] { ex, info });
                    else
                        DoHandle(ex, info);
                }
                catch (Exception x)
                {
                    Debug.WriteLine(x);
                }
            }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : anjoy8

private async Task GetGpsLocation()
        {
            var dependencyService = ViewModelLocator.Resolve<IDependencyService>();
            var locator = dependencyService.Get<ILocationServiceImplementation>();

            if (locator.IsGeolocationEnabled && locator.IsGeolocationAvailable)
            {
                locator.DesiredAccuracy = 50;

                try
                {
                    var position = await locator.GetPositionAsync();
                    _settingsService.Lareplacedude = position.Lareplacedude.ToString();
                    _settingsService.Longitude = position.Longitude.ToString();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
            else
            {
                _settingsService.AllowGpsLocation = false;
            }
        }

19 View Source File : UpdateChecker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

[MethodImpl(MethodImplOptions.NoInlining)]
        public static dynamic GetHojoring()
        {
            const string HojoringTypeName = "ACT.Hojoring.Common.Hojoring";

            var obj = default(object);

            lock (Locker)
            {
                if (hojoringInstance != null)
                {
                    return hojoringInstance;
                }

                try
                {
#if DEBUG
                    // DEBUGビルド時に依存関係でDLLを配置させるためにタイプを参照する
                    new ACT.Hojoring.Common.Hojoring();
#endif
                    var t = Type.GetType(HojoringTypeName);

                    if (t == null)
                    {
                        var cd = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
                        var hojoring = Path.Combine(cd, "ACT.Hojoring.Common.dll");
                        if (File.Exists(hojoring))
                        {
                            var asm = replacedembly.LoadFrom(hojoring);
                            t = asm?.GetType(HojoringTypeName);
                        }
                    }

                    if (t != null)
                    {
                        obj = Activator.CreateInstance(t);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    obj = null;
                }

                hojoringInstance = obj;
                return obj;
            }
        }

19 View Source File : UpdateChecker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

[MethodImpl(MethodImplOptions.NoInlining)]
        private static Version GetHojoringVersion()
        {
            var ver = default(Version);

            try
            {
                var hojoring = GetHojoring();
                if (hojoring != null)
                {
                    ver = hojoring.Version;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                ver = null;
            }

            return ver;
        }

19 View Source File : UpdateChecker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

[MethodImpl(MethodImplOptions.NoInlining)]
        public static void ShowSplash()
        {
            if (isShowen)
            {
                return;
            }

            isShowen = true;

            try
            {
                // エントリアセンブリのパスを出力する
                var entry = replacedembly.GetEntryreplacedembly().Location;
                Logger.Trace($"Entry {entry}");

                // ついでにFFXIV_ACT_Pluginのバージョンを出力する
                var ffxivPlugin = ActGlobals.oFormActMain?.ActPlugins?
                    .FirstOrDefault(
                        x => x.pluginFile.Name.ContainsIgnoreCase("FFXIV_ACT_Plugin"))?
                    .pluginFile.FullName;

                if (File.Exists(ffxivPlugin))
                {
                    var vi = FileVersionInfo.GetVersionInfo(ffxivPlugin);
                    if (vi != null)
                    {
                        Logger.Trace($"FFXIV_ACT_Plugin v{vi.FileMajorPart}.{vi.FileMinorPart}.{vi.FileBuildPart}.{vi.FilePrivatePart}");
                    }
                }

                // Hojoringのバージョンを出力しつつSPLASHを表示する
                var hojoring = GetHojoring();
                if (hojoring != null)
                {
                    var ver = hojoring.Version as Version;
                    if (ver != null)
                    {
                        Logger.Trace($"Hojoring v{ver.Major}.{ver.Minor}.{ver.Revision}");
                    }

                    hojoring.ShowSplash("initializing...");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

19 View Source File : ReleaseNotes.cs
License : MIT License
Project Creator : anoyetta

public static async Task<ReleaseNotes> DeserializeAsync(
            Uri uri)
        {
            var source = string.Empty;

            using (var client = new WebClient())
            {
                try
                {
                    client.Encoding = new UTF8Encoding(false);
                    source = await client.DownloadStringTaskAsync(uri);
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                    return null;
                }
            }

            return Deserialize(source);
        }

19 View Source File : RestClientBase.cs
License : MIT License
Project Creator : anoyetta

public async Task GetVersionAsync()
        {
            try
            {
                var result = await this.GetAsync("version");
                var vi = await result?.Content?.ReadAsAsync<VersionInfoModel>();
                if (vi != null)
                {
                    HelpViewModel.Instance.AddVersionInfos(vi);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

19 View Source File : ARNotificationView.cs
License : Apache License 2.0
Project Creator : AppRopio

public override void TouchesMoved(Foundation.NSSet touches, UIEvent evt)
        {
            if (touches.Count == 1)
            {
                var touch = touches.First() as UITouch;
                var point = touch.LocationInView(this);


                var currentScrollOrientation = Math.Abs(GetTouchDistance(touch.Timestamp, point.X, _previousTouchPosition.X)) > Math.Abs(GetTouchDistance(touch.Timestamp, point.Y, _previousTouchPosition.Y)) ?
                                         ARNotificationScrollOrientation.FromRightToLeft :
                                         (point.Y < _previousTouchPosition.Y ? ARNotificationScrollOrientation.FromBottomToTop : ARNotificationScrollOrientation.FromTopToBottom);

                //if (_scrollOrientation == ARNotificationScrollOrientation.Unknown)
                //    _scrollOrientation = currentScrollOrientation;
                //else if ((_scrollOrientation == ARNotificationScrollOrientation.FromLeftToRight || _scrollOrientation == ARNotificationScrollOrientation.FromRightToLeft)
                //        && (currentScrollOrientation == ARNotificationScrollOrientation.FromLeftToRight || currentScrollOrientation == ARNotificationScrollOrientation.FromRightToLeft))
                //    _scrollOrientation = currentScrollOrientation;
                //else if ((_scrollOrientation == ARNotificationScrollOrientation.FromBottomToTop || _scrollOrientation == ARNotificationScrollOrientation.FromTopToBottom)
                    //    && (currentScrollOrientation == ARNotificationScrollOrientation.FromBottomToTop || currentScrollOrientation == ARNotificationScrollOrientation.FromTopToBottom))
                    //_scrollOrientation = currentScrollOrientation;

                Debug.WriteLine(point);
                Debug.WriteLine(_scrollOrientation);
                Debug.WriteLine(_previousTouchPosition);

                if (Frame.Y == 0 && point.X < _previousTouchPosition.X && currentScrollOrientation == ARNotificationScrollOrientation.FromRightToLeft)
                {
                    var delta = _previousTouchPosition.X - point.X;

                    this.ChangeFrame(x: Frame.X - delta);

                    _scrollOrientation = currentScrollOrientation;
                }
                else if (Frame.X == 0 && point.Y < _previousTouchPosition.Y && currentScrollOrientation == ARNotificationScrollOrientation.FromBottomToTop)
                {
                    var delta = _previousTouchPosition.Y - point.Y;

                    this.ChangeFrame(y: Frame.Y - delta);

                    _scrollOrientation = currentScrollOrientation;
                }
                else if (Frame.X == 0 && _alertType == ARNotificationType.Error && point.Y > _previousTouchPosition.Y && currentScrollOrientation == ARNotificationScrollOrientation.FromTopToBottom)
                {
                    var delta = point.Y - _previousTouchPosition.Y;

                    if (_realTextSize.Height > TEXT_VIEW_HEIGHT)
                    {
                        var newHeight = Frame.Height + delta;
                        var maxHeight = (nfloat)Math.Min(_realTextSize.Height + TEXT_VIEW_OFFSET, DeviceInfo.ScreenHeight);

                        this.ChangeFrame(h: newHeight > maxHeight ? maxHeight : newHeight);
                    }

                    _scrollOrientation = currentScrollOrientation;
                }

                _previousTouchPosition = point;
            }

            base.TouchesMoved(touches, evt);
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : Arefu

private void installToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var OFD = new OpenFileDialog())
            {
                OFD.replacedle = "Select Mod To Enable";
                OFD.Filter = "Wolf Mod Data |*.moddta";
                if (OFD.ShowDialog() != DialogResult.OK) return;

                if (!File.Exists(OFD.FileName.Replace("moddta", "modpkg")))
                    throw new Exception("Mod Package Not Found! Please Read The Wiki On How To Create Mods.");

                var ModFileInfo = new JavaScriptSerializer().Deserialize<ModInfo>(File.ReadAllText(OFD.FileName));

                var AllFilesFound = true;
                var CompareSizes = new Dictionary<long, ModFile>();
                Reader?.Close();

                using (var GetFileSizeReader = new StreamReader(File.Open($"{Utilities.GetInstallDir()}\\YGO_DATA.TOC", FileMode.Open, FileAccess.Read)))
                {
                    for (var Count = 0; Count < ModFileInfo.Files.Count; Count++)
                    {
                        GetFileSizeReader.BaseStream.Position = 0;
                        GetFileSizeReader.ReadLine();
                        while (!GetFileSizeReader.EndOfStream)
                        {
                            var Line = GetFileSizeReader.ReadLine();
                            if (Line == null) break;
                            Line = Line.TrimStart(' ');
                            Line = Regex.Replace(Line, @"  +", " ", RegexOptions.Compiled);
                            var LineData = Line.Split(' ');

                            if (new FileInfo(LineData[2]).Name == new FileInfo(ModFileInfo.Files[Count]).Name)
                            {
                                GetFileSizeReader.BaseStream.Position = 0; //Because We're Breaking We Need To Reset Stream DUH
                                GetFileSizeReader.ReadLine();
                                AllFilesFound = true;
                                CompareSizes.Add(Utilities.HexToDec(LineData[0]), new ModFile(ModFileInfo, Count));
                                break;
                            }
                            AllFilesFound = false;
                        }
                    }
                }

                if (AllFilesFound == false)
                {
                    var Reply = MessageBox.Show("Not All Files Were Found In The TOC File, Do You Want To Contiue?", "Lost Files Found In Mod!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (Reply == DialogResult.No) return;
                }

                using (var LogWriter = File.AppendText("Install_Log.log"))
                {
                    foreach (var ModFile in CompareSizes)
                        if (ModFile.Key < ModFile.Value.FileSize)
                        {
                            var Reply = MessageBox.Show("File Already In Game Is Bigger, Do You Want To Continue?", "File Size Mismatch!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                            if (Reply == DialogResult.No)
                            {
                                LogWriter.Write($"[{DateTime.Now}]: Didn't Inject {ModFile.Value.FileName}, Discarded By User!\n\r");
                                continue;
                            }

                            LogWriter.Write($"[{DateTime.Now}]: Injecting {ModFile.Value.FileName} With Size Of {ModFile.Value.FileSize} The original file is bigger\n\r");

                            //Open DAT, Insert In Right Place...
                        }
                        else
                        {
                            LogWriter.Write($"[{DateTime.Now}]: Injecting {ModFile.Value.FileName} With Size Of {ModFile.Value.FileSize} This File Is Smaller!\n\r");
                            var Sum = 0L;
                            var NullOutSize = 0L;
                            Reader?.Close();
                            using (Reader = new StreamReader(File.Open($"{InstallDir}\\YGO_DATA.TOC", FileMode.Open, FileAccess.Read)))
                            {
                                Reader.BaseStream.Position = 0;
                                Reader.ReadLine();
                                while (!Reader.EndOfStream
                                ) //Breaks on 116a658 44 D3D11\characters\m9575_number_39_utopia\m9575_number_39_utopia.phyre ?
                                {
                                    var Line = Reader.ReadLine();
                                    if (Line == null) break;
                                    Line = Line.TrimStart(' ');
                                    Line = Regex.Replace(Line, @"  +", " ", RegexOptions.Compiled);
                                    var LineData = Line.Split(' ');
                                    if (LineData[2] == ModFile.Value.FileName)
                                    {
                                        NullOutSize = Utilities.HexToDec(LineData[0]);
                                        break;
                                    }

                                    Sum = Sum + Utilities.HexToDec(LineData[0]);
                                }

                                Debug.WriteLine(Sum);
                                using (var Writer = new BinaryWriter(File.Open($"{InstallDir}\\YGO_DATA.DAT", FileMode.Open, FileAccess.ReadWrite)))
                                {
                                    Writer.BaseStream.Position = Sum;
                                    var NullCount = 0L;
                                    do
                                    {
                                        Writer.Write(0x00);
                                        NullCount++;
                                    } while (NullCount < NullOutSize);
                                }
                            }
                        }
                }
            }
        }

19 View Source File : VimeoVideoIdExtension.cs
License : MIT License
Project Creator : arqueror

public object ProvideValue(ref List<eliteVideoQuality> availableQualities, ref eliteVideoQuality currentVideoQuality)
        {
            try
            {
                Debug.WriteLine($"Acquiring Vimeo stream source URL from VideoId='{VideoId}'...");
                var videoInfoUrl = $"https://player.vimeo.com/video/{VideoId}/config";

                using (var client = new HttpClient())
                {
                    var videoPageContent = client.GetStringAsync(videoInfoUrl).Result;
                    var videoPageBytes = Encoding.UTF8.GetBytes(videoPageContent);

                    using (var stream = new MemoryStream(videoPageBytes))
                    {
                        var serializer = new DataContractJsonSerializer(typeof(VimeoVideo));
                        var metaData = (VimeoVideo)serializer.ReadObject(stream);
                        var files = metaData.request.files.progressive;

                        var videoUrl = "";
                        var videos = files.OrderBy(s => s.width).Select(s => new VideoQualityModel { Quality = s.quality, Url = s.url }).ToList();


                        var countFlag = 0;
                        foreach (var videoQualityModel in videos)
                        {
                            if (videoQualityModel.Quality.Contains(((int)eliteVideoQuality.Low).ToString()))
                            {
                                availableQualities.Add(eliteVideoQuality.Low);
                            }
                            else if (videoQualityModel.Quality.Contains(((int)eliteVideoQuality.Normal).ToString()))
                            {
                                availableQualities.Add(eliteVideoQuality.Normal);
                            }
                            else if (videoQualityModel.Quality.Contains(((int)eliteVideoQuality.Medium).ToString()))
                            {
                                availableQualities.Add(eliteVideoQuality.Medium);
                            }
                            else if (videoQualityModel.Quality.Contains(((int)eliteVideoQuality.High).ToString()))
                            {
                                availableQualities.Add(eliteVideoQuality.High);
                            }
                        }

                        // Exact match
                        if (videos.Any())
                        {
                            //try to find preferred quality
                            var prefQuality = videos.FirstOrDefault(v => v.Quality.Contains(VideoQuality.ToString()));
                            if (prefQuality != null)
                            {
                                prefQuality.Quality = Regex.Replace(prefQuality.Quality, "[^0-9]", "");
                                videoUrl = prefQuality.Url;
                                currentVideoQuality = (eliteVideoQuality)Enum.Parse(typeof(eliteVideoQuality), prefQuality.Quality);
                                return VideoSource.FromUri(videoUrl);
                            }

                            //Not found.. Pick first quality in list and expose to caller available qualities
                            videoUrl = videos.First().Url;
                            var finalQuality = Regex.Replace(videos.First().Quality, "[^0-9]", "");
                            currentVideoQuality = (eliteVideoQuality)Enum.Parse(typeof(eliteVideoQuality), finalQuality);
                            Debug.WriteLine($"Stream URL: {videoUrl}");

                            //Make sure we can access URL.
                            if (!string.IsNullOrEmpty(videoUrl))
                            {
                                try
                                {
                                    var request = new HttpRequestMessage(HttpMethod.Head, videoUrl);
                                    var result = coreSettings.HttpClientSingleton.SendAsync(request).Result;
                                    if (!result.IsSuccessStatusCode)
                                    {
                                        return null;
                                    }

                                }
                                catch
                                {
                                    return null;
                                }

                            }

                            return VideoSource.FromUri(videoUrl);

                        }

                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error occured while attempting to convert Vimeo video ID into a remote stream path.");
                Debug.WriteLine(ex);
            }

            return null;
        }

19 View Source File : RemoteKitWebServer.cs
License : Apache License 2.0
Project Creator : artemshuba

private async void ProcessFileResponse(StreamSocket socket, RemoteKitHttpRequest request)
        {
            try
            {
                if (_apiClient != null)
                {
                    var stream = await _apiClient.ProcessFileAsync(request.RequestTarget);

                    if (stream != null)
                    {
                        var response = new HttpResponse();

                        var length = stream.Length;
                        var extension = Path.GetExtension(request.RequestTarget);
                        var contentType = "application/" + extension;

                        switch (extension)
                        {
                            case ".js":
                                contentType = "application/javascript";
                                break;

                            case ".css":
                                contentType = "text/css";
                                break;

                            case ".png":
                                contentType = "image/png";
                                break;

                            case ".svg":
                                contentType = "image/svg+xml";
                                break;

                            case ".html":
                            case ".htm":
                            default:
                                contentType = "text/html";
                                break;
                        }

                        response.Headers.Add("Content-Length", length.ToString());
                        response.Headers.Add("Content-Type", contentType);
                        response.Headers.Add("Connection", "close");

                        var buffer = new byte[length];
                        await stream.ReadAsync(buffer, 0, (int)length);
                        stream.Dispose();
                        response.Data = buffer;

                        await WriteResponse(socket, response);

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            //write 404 response
            var failResponse = new HttpResponse();
            failResponse.Status = "HTTP/1.1 404 Not found";
            failResponse.Headers.Add("Content-Length", "0");
            await WriteResponse(socket, failResponse);
        }

19 View Source File : LottieAnimationView.cs
License : Apache License 2.0
Project Creator : ascora

public virtual async Task SetAnimationAsync(string replacedetName)
        {
            _animationName = replacedetName;
            var cachedComposition = LottieCompositionCache.Instance.Get(replacedetName);
            if (cachedComposition != null)
            {
                Composition = cachedComposition;
                return;
            }

            ClearComposition();
            CancelLoaderTask();

            var cancellationTokenSource = new CancellationTokenSource();

            _compositionTaskCTS = cancellationTokenSource;

            try
            {
                var compositionResult = await LottieCompositionFactory.Fromreplacedet(_lottieDrawable.RenderTarget, replacedetName, cancellationTokenSource.Token);

                LottieCompositionCache.Instance.Put(replacedetName, compositionResult.Value);

                Composition = compositionResult.Value;
            }
            catch (TaskCanceledException e)
            {
                Debug.WriteLine(e);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Unable to parse composition", e);
            }
        }

19 View Source File : LottieAnimationView.cs
License : Apache License 2.0
Project Creator : ascora

public virtual async Task SetAnimationAsync(JsonReader reader, string cacheKey)
        {
            ClearComposition();
            CancelLoaderTask();
            var cancellationTokenSource = new CancellationTokenSource();

            _compositionTaskCTS = cancellationTokenSource;

            try
            {
                var compositionResult = await LottieCompositionFactory.FromJsonReader(reader, cacheKey, cancellationTokenSource.Token);

                if (compositionResult.Value != null)
                {
                    Composition = compositionResult.Value;
                }
                _compositionTaskCTS = null;
            }
            catch (TaskCanceledException e)
            {
                Debug.WriteLine(e);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Unable to parse composition", e);
            }
        }

19 View Source File : LottieAnimationView.cs
License : Apache License 2.0
Project Creator : ascora

public async Task SetAnimationFromUrlAsync(string url)
        {
            ClearComposition();
            CancelLoaderTask();
            var cancellationTokenSource = new CancellationTokenSource();

            _compositionTaskCTS = cancellationTokenSource;

            try
            {
                var compositionResult = await LottieCompositionFactory.FromUrlAsync(_lottieDrawable.RenderTarget, url, cancellationTokenSource.Token);

                if (compositionResult.Value != null)
                {
                    Composition = compositionResult.Value;
                }
                _compositionTaskCTS = null;
            }
            catch (TaskCanceledException e)
            {
                Debug.WriteLine(e);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Unable to parse composition", e);
            }
        }

19 View Source File : LogHelper.cs
License : Apache License 2.0
Project Creator : aspnet

internal static void LogException(LoggerFunc logger, string location, Exception exception)
        {
            if (logger == null)
            {
                Debug.WriteLine(exception);
            }
            else
            {
                logger(TraceEventType.Error, 0, location, exception, LogStateAndError);
            }
        }

19 View Source File : ProcessDialog.xaml.cs
License : GNU General Public License v3.0
Project Creator : autodotua

public void Show()
        {
            if (showCount++>0)
            {
                return;
            }
            System.Diagnostics.Debug.WriteLine(showCount);
            Message = "正在处理";
            Visibility = Visibility.Visible;
            if (Configs.ShowRing)
            {
                ring.IsActive = true;
                DoubleAnimation ani = new DoubleAnimation(1, Configs.AnimationDuration);
                Dispatcher.Invoke(() =>
                BeginAnimation(OpacityProperty, ani));
            }
            else
            {
                Cursor = System.Windows.Input.Cursors.Wait;
            }
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : Autodesk-Forge

private async void isTranslationReady(object sender, EventArgs e)
    {
      DerivativesApi derivative = new DerivativesApi();
      derivative.Configuration.AccessToken = AccessToken;

      // get the translation manifest
      dynamic manifest = await derivative.GetManifestAsync((string)_translationTimer.Tag);
      int progress = (string.IsNullOrWhiteSpace(Regex.Match(manifest.progress, @"\d+").Value) ? 100 : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value));

      // for better UX, show a small number of progress (instead zero)
      progressBar.Value = (progress == 0 ? 10 : progress);
      progressBar.CustomText = string.Format("Translation in progress: {0}", progress);
      Debug.WriteLine(progress);

      // if ready, hide everything
      if (progress >= 100)
      {
        progressBar.Hide();
        _translationTimer.Enabled = false;
      }
    }

19 View Source File : BenchmarkTest.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public void CoreTestInit(string testName)
        {
            if (ThrownException?.Value != null)
            {
                ThrownException.Value = null;
            }

            _stringWriter = new StringWriter();
            Console.SetOut(_stringWriter);

            var testClreplacedType = TestClreplacedType;
            var testMethodMemberInfo = GetCurrentExecutionMethodInfo(testName);
            Container = ServicesCollection.Current.FindCollection(testClreplacedType.FullName);
            _currentTestExecutionProvider = new PluginProvider();
            InitializeTestExecutionBehaviorObservers(_currentTestExecutionProvider);
            var categories = _categories;
            var authors = _authors;
            var descriptions = _descriptions;
            try
            {
                _currentTestExecutionProvider.PreTestInit(testName, testMethodMemberInfo, testClreplacedType, new List<object>(), categories, authors, descriptions);
                TestInit();
                _currentTestExecutionProvider.PostTestInit(testName, testMethodMemberInfo, testClreplacedType, new List<object>(), categories, authors, descriptions);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                _currentTestExecutionProvider.TestInitFailed(ex, testName, testMethodMemberInfo, testClreplacedType, new List<object>(), categories, authors, descriptions);
                throw;
            }
        }

See More Examples