content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace PowerShellTools.Repl { internal class ResizingAdorner : Adorner { private readonly VisualCollection _visualChildren; private readonly Thumb _bottomRight; public ResizingAdorner(UIElement adornedElement) : base(adornedElement) { _visualChildren = new VisualCollection(this); _bottomRight = BuildAdornerCorner(Cursors.SizeNWSE, HandleBottomRight); } private Thumb BuildAdornerCorner(Cursor cursor, DragDeltaEventHandler dragHandler) { var thumb = new Thumb(); // TODO: this thumb should be styled to look like a dotted triangle, // similar to the one you can see on the bottom right corner of // Internet Explorer window thumb.Cursor = cursor; thumb.Height = thumb.Width = 10; thumb.Opacity = 0.40; thumb.Background = new SolidColorBrush(Colors.MediumBlue); thumb.DragDelta += dragHandler; thumb.DragStarted += (s, e) => { var handler = ResizeStarted; if (handler != null) { handler(this, e); } }; thumb.DragCompleted += (s, e) => { var handler = ResizeCompleted; if (handler != null) { handler(this, e); } }; _visualChildren.Add(thumb); return thumb; } private void HandleBottomRight(object sender, DragDeltaEventArgs eventArgs) { var thumb = sender as Thumb; var element = AdornedElement as FrameworkElement; if (element == null || thumb == null) { return; } element.MaxWidth = Math.Max(element.MaxWidth + eventArgs.HorizontalChange, thumb.DesiredSize.Width); element.MaxHeight = Math.Max(element.MaxHeight + eventArgs.VerticalChange, thumb.DesiredSize.Height); var size = new Size(element.MaxWidth, element.MaxHeight); AdornedElement.Measure(size); } protected override Size ArrangeOverride(Size finalSize) { var desiredWidth = AdornedElement.DesiredSize.Width; var desiredHeight = AdornedElement.DesiredSize.Height; var adornerWidth = DesiredSize.Width; var adornerHeight = DesiredSize.Height; _bottomRight.Arrange(new Rect((desiredWidth - adornerWidth) / 2, (desiredHeight - adornerHeight) / 2, adornerWidth, adornerHeight)); return finalSize; } protected override int VisualChildrenCount { get { return _visualChildren.Count; } } protected override Visual GetVisualChild(int index) { return _visualChildren[index]; } public event RoutedEventHandler ResizeStarted; public event RoutedEventHandler ResizeCompleted; } }
40.885417
114
0.584713
[ "Apache-2.0" ]
Bhaskers-Blu-Org2/poshtools
ReplWindow/Repl/ResizingAdorner.cs
3,927
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.AppMesh.Inputs { public sealed class RouteSpecTcpRouteArgs : Pulumi.ResourceArgs { /// <summary> /// The action to take if a match is determined. /// </summary> [Input("action", required: true)] public Input<Inputs.RouteSpecTcpRouteActionArgs> Action { get; set; } = null!; public RouteSpecTcpRouteArgs() { } } }
27.961538
88
0.664374
[ "ECL-2.0", "Apache-2.0" ]
JakeGinnivan/pulumi-aws
sdk/dotnet/AppMesh/Inputs/RouteSpecTcpRouteArgs.cs
727
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; [module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "member", Target = "IronPython.Runtime.Exceptions.TraceBackFrame..ctor(System.Object,System.Object,System.Object)", MessageId = "0#globals")] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "member", Target = "IronPython.Runtime.Exceptions.TraceBackFrame.Globals", MessageId = "Globals")] namespace IronPython.Runtime.Exceptions { [PythonType("traceback")] [Serializable] public class TraceBack { private readonly TraceBack _next; private readonly TraceBackFrame _frame; private int _line; public TraceBack(TraceBack nextTraceBack, TraceBackFrame fromFrame) { _next = nextTraceBack; _frame = fromFrame; } public TraceBack tb_next { get { return _next; } } public TraceBackFrame tb_frame { get { return _frame; } } public int tb_lineno { get { return _line; } } public int tb_lasti { get { return 0; // not presently tracked } } internal void SetLine(int lineNumber) { _line = lineNumber; } /// <summary> /// returns string containing human readable representation of traceback /// </summary> internal string Extract() { var sb = new StringBuilder(); var tb = this; while (tb != null) { var f = tb._frame; var lineno = tb._line; var co = f.f_code; var filename = co.co_filename; var name = co.co_name; sb.AppendFormat(" File \"{0}\", line {1}, in {2}{3}", filename, lineno, name, Environment.NewLine); tb = tb._next; } return sb.ToString(); } } [PythonType("frame")] [DebuggerDisplay("Code = {f_code.co_name}, Line = {f_lineno}")] [Serializable] public class TraceBackFrame { private readonly PythonTracebackListener _traceAdapter; private TracebackDelegate _trace; private object _traceObject; internal int _lineNo; private readonly PythonDebuggingPayload _debugProperties; private readonly Func<IDictionary<object, object>> _scopeCallback; private readonly PythonDictionary _globals; private readonly object _locals; private readonly FunctionCode _code; private readonly CodeContext/*!*/ _context; private readonly TraceBackFrame _back; internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, object locals, FunctionCode code) { _globals = globals; _locals = locals; _code = code; _context = context; } internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, object locals, FunctionCode code, TraceBackFrame back) { _globals = globals; _locals = locals; _code = code; _context = context; _back = back; } internal TraceBackFrame(PythonTracebackListener traceAdapter, FunctionCode code, TraceBackFrame back, PythonDebuggingPayload debugProperties, Func<IDictionary<object, object>> scopeCallback) { _traceAdapter = traceAdapter; _code = code; _back = back; _debugProperties = debugProperties; _scopeCallback = scopeCallback; } [SpecialName, PropertyMethod] public object Getf_trace() { if (_traceAdapter != null) { return _traceObject; } else { return null; } } [SpecialName, PropertyMethod] public void Setf_trace(object value) { _traceObject = value; _trace = (TracebackDelegate)Converter.ConvertToDelegate(value, typeof(TracebackDelegate)); } [SpecialName, PropertyMethod] public void Deletef_trace() { Setf_trace(null); } public void clear() { // TODO: add actual implementation of clear } internal CodeContext Context { get { return _context; } } internal TracebackDelegate TraceDelegate { get { if (_traceAdapter != null) { return _trace; } else { return null; } } } public PythonDictionary f_globals { get { object context; if (_scopeCallback != null && _scopeCallback().TryGetValue(Compiler.Ast.PythonAst.GlobalContextName, out context) && context != null) { return ((CodeContext)context).GlobalDict; } else { return _globals; } } } public object f_locals { get { if (_traceAdapter != null && _scopeCallback != null) { if (_code.IsModule) { // don't use the scope callback for locals in a module, use our globals dictionary instead return f_globals; } return new PythonDictionary(new DebuggerDictionaryStorage(_scopeCallback())); } else { return _locals; } } } public FunctionCode f_code { get { return _code; } } public object f_builtins { get { return _context.LanguageContext.BuiltinModuleDict; } } public TraceBackFrame f_back { get { return _back; } } public object f_lineno { get { if (_traceAdapter != null) { return _lineNo; } else { return 1; } } set { if (!(value is int)) { throw PythonOps.ValueError("lineno must be an integer"); } SetLineNumber((int)value); } } private void SetLineNumber(int newLineNum) { var pyThread = PythonOps.GetFunctionStackNoCreate(); if (_traceAdapter == null || !IsTopMostFrame(pyThread)) { throw PythonOps.ValueError("f_lineno can only be set by a trace function on the topmost frame"); } FunctionCode funcCode = _debugProperties.Code; Dictionary<int, Dictionary<int, bool>> loopAndFinallyLocations = _debugProperties.LoopAndFinallyLocations; Dictionary<int, bool> handlerLocations = _debugProperties.HandlerLocations; Dictionary<int, bool> currentLoopIds = null; bool inForLoopOrFinally = loopAndFinallyLocations != null && loopAndFinallyLocations.TryGetValue(_lineNo, out currentLoopIds); int originalNewLine = newLineNum; if (newLineNum < funcCode.Span.Start.Line) { throw PythonOps.ValueError("line {0} comes before the current code block", newLineNum); } else if (newLineNum > funcCode.Span.End.Line) { throw PythonOps.ValueError("line {0} comes after the current code block", newLineNum); } while (newLineNum <= funcCode.Span.End.Line) { var span = new SourceSpan(new SourceLocation(0, newLineNum, 1), new SourceLocation(0, newLineNum, Int32.MaxValue)); // Check if we're jumping onto a handler bool handlerIsFinally; if (handlerLocations != null && handlerLocations.TryGetValue(newLineNum, out handlerIsFinally)) { throw PythonOps.ValueError("can't jump to 'except' line"); } // Check if we're jumping into a for-loop Dictionary<int, bool> jumpIntoLoopIds; if (loopAndFinallyLocations != null && loopAndFinallyLocations.TryGetValue(newLineNum, out jumpIntoLoopIds)) { // If we're not in any loop already - then we can't jump into a loop if (!inForLoopOrFinally) { throw BadForOrFinallyJump(newLineNum, jumpIntoLoopIds); } // If we're in loops - we can only jump if we're not entering a new loop foreach (int jumpIntoLoopId in jumpIntoLoopIds.Keys) { if (!currentLoopIds.ContainsKey(jumpIntoLoopId)) { throw BadForOrFinallyJump(newLineNum, currentLoopIds); } } } else if (currentLoopIds != null) { foreach (bool isFinally in currentLoopIds.Values) { if (isFinally) { throw PythonOps.ValueError("can't jump out of 'finally block'"); } } } if (_traceAdapter.PythonContext.TracePipeline.TrySetNextStatement(_code.co_filename, span)) { _lineNo = newLineNum; return; } ++newLineNum; } throw PythonOps.ValueError("line {0} is invalid jump location ({1} - {2} are valid)", originalNewLine, funcCode.Span.Start.Line, funcCode.Span.End.Line); } private bool IsTopMostFrame(List<FunctionStack> pyThread) { return pyThread != null && pyThread.Count != 0 && pyThread[pyThread.Count - 1].Frame == this; } private static Exception BadForOrFinallyJump(int newLineNum, Dictionary<int, bool> jumpIntoLoopIds) { foreach (bool isFinally in jumpIntoLoopIds.Values) { if (isFinally) { return PythonOps.ValueError("can't jump into 'finally block'", newLineNum); } } return PythonOps.ValueError("can't jump into 'for loop'", newLineNum); } } public delegate TracebackDelegate TracebackDelegate(TraceBackFrame frame, string result, object payload); }
36.830565
272
0.557189
[ "Apache-2.0" ]
AnandEmbold/ironpython3
Src/IronPython/Runtime/Exceptions/TraceBack.cs
11,086
C#
//----------------------------------------------------------------------- // <copyright file="DotNettyTransport.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Runtime.Serialization; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Akka.Actor; using Akka.Configuration; using Akka.Event; using Akka.Util; using DotNetty.Buffers; using DotNetty.Codecs; using DotNetty.Common.Utilities; using DotNetty.Handlers.Tls; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Transport.Channels.Sockets; namespace Akka.Remote.Transport.DotNetty { internal abstract class CommonHandlers : ChannelHandlerAdapter { protected readonly DotNettyTransport Transport; protected readonly ILoggingAdapter Log; protected CommonHandlers(DotNettyTransport transport, ILoggingAdapter log) { Transport = transport; Log = log; } public override void ChannelActive(IChannelHandlerContext context) { base.ChannelActive(context); if (!Transport.ConnectionGroup.TryAdd(context.Channel)) { Log.Warning("Unable to ADD channel [{0}->{1}](Id={2}) to connection group. May not shut down cleanly.", context.Channel.LocalAddress, context.Channel.RemoteAddress, context.Channel.Id); } } public override void ChannelInactive(IChannelHandlerContext context) { base.ChannelInactive(context); if (!Transport.ConnectionGroup.TryRemove(context.Channel)) { Log.Warning("Unable to REMOVE channel [{0}->{1}](Id={2}) from connection group. May not shut down cleanly.", context.Channel.LocalAddress, context.Channel.RemoteAddress, context.Channel.Id); } } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { base.ExceptionCaught(context, exception); Log.Error(exception, "Error caught channel [{0}->{1}](Id={2})", context.Channel.LocalAddress, context.Channel.RemoteAddress, context.Channel.Id); } protected abstract AssociationHandle CreateHandle(IChannel channel, Address localAddress, Address remoteAddress); protected abstract void RegisterListener(IChannel channel, IHandleEventListener listener, object msg, IPEndPoint remoteAddress); protected void Init(IChannel channel, IPEndPoint remoteSocketAddress, Address remoteAddress, object msg, out AssociationHandle op) { var localAddress = DotNettyTransport.MapSocketToAddress((IPEndPoint)channel.LocalAddress, Transport.SchemeIdentifier, Transport.System.Name, Transport.Settings.Hostname); if (localAddress != null) { var handle = CreateHandle(channel, localAddress, remoteAddress); handle.ReadHandlerSource.Task.ContinueWith(s => { var listener = s.Result; RegisterListener(channel, listener, msg, remoteSocketAddress); channel.Configuration.AutoRead = true; // turn reads back on }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted); op = handle; } else { op = null; channel.CloseAsync(); } } } internal class DotNettyTransportException : RemoteTransportException { /// <summary> /// Initializes a new instance of the <see cref="DotNettyTransportException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="cause">The exception that is the cause of the current exception.</param> public DotNettyTransportException(string message, Exception cause = null) : base(message, cause) { } /// <summary> /// Initializes a new instance of the <see cref="DotNettyTransportException"/> class. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param> protected DotNettyTransportException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal abstract class DotNettyTransport : Transport { internal readonly ConcurrentSet<IChannel> ConnectionGroup; protected readonly TaskCompletionSource<IAssociationEventListener> AssociationListenerPromise; protected readonly ILoggingAdapter Log; protected volatile Address LocalAddress; protected internal volatile IChannel ServerChannel; private readonly IEventLoopGroup _serverEventLoopGroup; private readonly IEventLoopGroup _clientEventLoopGroup; protected DotNettyTransport(ActorSystem system, Config config) { System = system; Config = config; if (system.Settings.Config.HasPath("akka.remote.helios.tcp")) { var heliosFallbackConfig = system.Settings.Config.GetConfig("akka.remote.helios.tcp"); config = heliosFallbackConfig.WithFallback(config); } Settings = DotNettyTransportSettings.Create(config); Log = Logging.GetLogger(System, GetType()); _serverEventLoopGroup = new MultithreadEventLoopGroup(Settings.ServerSocketWorkerPoolSize); _clientEventLoopGroup = new MultithreadEventLoopGroup(Settings.ClientSocketWorkerPoolSize); ConnectionGroup = new ConcurrentSet<IChannel>(); AssociationListenerPromise = new TaskCompletionSource<IAssociationEventListener>(); SchemeIdentifier = (Settings.EnableSsl ? "ssl." : string.Empty) + Settings.TransportMode.ToString().ToLowerInvariant(); } public DotNettyTransportSettings Settings { get; } public sealed override string SchemeIdentifier { get; protected set; } public override long MaximumPayloadBytes => Settings.MaxFrameSize; private TransportMode InternalTransport => Settings.TransportMode; public sealed override bool IsResponsibleFor(Address remote) => true; protected async Task<IChannel> NewServer(EndPoint listenAddress) { if (InternalTransport != TransportMode.Tcp) throw new NotImplementedException("Haven't implemented UDP transport at this time"); if (listenAddress is DnsEndPoint dns) { listenAddress = await DnsToIPEndpoint(dns).ConfigureAwait(false); } return await ServerFactory().BindAsync(listenAddress).ConfigureAwait(false); } public override async Task<(Address, TaskCompletionSource<IAssociationEventListener>)> Listen() { EndPoint listenAddress; IPAddress ip; if (IPAddress.TryParse(Settings.Hostname, out ip)) listenAddress = new IPEndPoint(ip, Settings.Port); else listenAddress = new DnsEndPoint(Settings.Hostname, Settings.Port); try { var newServerChannel = await NewServer(listenAddress).ConfigureAwait(false); // Block reads until a handler actor is registered // no incoming connections will be accepted until this value is reset // it's possible that the first incoming association might come in though newServerChannel.Configuration.AutoRead = false; ConnectionGroup.TryAdd(newServerChannel); ServerChannel = newServerChannel; var addr = MapSocketToAddress( socketAddress: (IPEndPoint)newServerChannel.LocalAddress, schemeIdentifier: SchemeIdentifier, systemName: System.Name, hostName: Settings.PublicHostname, publicPort: Settings.PublicPort); if (addr == null) throw new ConfigurationException($"Unknown local address type {newServerChannel.LocalAddress}"); LocalAddress = addr; // resume accepting incoming connections #pragma warning disable 4014 // we WANT this task to run without waiting AssociationListenerPromise.Task.ContinueWith(result => newServerChannel.Configuration.AutoRead = true, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion); #pragma warning restore 4014 return (addr, AssociationListenerPromise); } catch (Exception ex) { Log.Error(ex, "Failed to bind to {0}; shutting down DotNetty transport.", listenAddress); try { await Shutdown().ConfigureAwait(false); } catch { // ignore errors occurring during shutdown } throw; } } public override async Task<AssociationHandle> Associate(Address remoteAddress) { if (!ServerChannel.Open) throw new ChannelException("Transport is not open"); return await AssociateInternal(remoteAddress).ConfigureAwait(false); } protected abstract Task<AssociationHandle> AssociateInternal(Address remoteAddress); public override async Task<bool> Shutdown() { try { var tasks = new List<Task>(); foreach (var channel in ConnectionGroup) { tasks.Add(channel.CloseAsync()); } var all = Task.WhenAll(tasks); await all.ConfigureAwait(false); var server = ServerChannel?.CloseAsync() ?? TaskEx.Completed; await server.ConfigureAwait(false); return all.IsCompleted && server.IsCompleted; } finally { // free all of the connection objects we were holding onto ConnectionGroup.Clear(); #pragma warning disable 4014 // shutting down the worker groups can take up to 10 seconds each. Let that happen asnychronously. _clientEventLoopGroup.ShutdownGracefullyAsync(); _serverEventLoopGroup.ShutdownGracefullyAsync(); #pragma warning restore 4014 } } protected Bootstrap ClientFactory(Address remoteAddress) { if (InternalTransport != TransportMode.Tcp) throw new NotSupportedException("Currently DotNetty client supports only TCP tranport mode."); var addressFamily = Settings.DnsUseIpv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; var client = new Bootstrap() .Group(_clientEventLoopGroup) .Option(ChannelOption.SoReuseaddr, Settings.TcpReuseAddr) .Option(ChannelOption.SoKeepalive, Settings.TcpKeepAlive) .Option(ChannelOption.TcpNodelay, Settings.TcpNoDelay) .Option(ChannelOption.ConnectTimeout, Settings.ConnectTimeout) .Option(ChannelOption.AutoRead, false) .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default) .ChannelFactory(() => Settings.EnforceIpFamily ? new TcpSocketChannel(addressFamily) : new TcpSocketChannel()) .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel => SetClientPipeline(channel, remoteAddress))); if (Settings.ReceiveBufferSize.HasValue) client.Option(ChannelOption.SoRcvbuf, Settings.ReceiveBufferSize.Value); if (Settings.SendBufferSize.HasValue) client.Option(ChannelOption.SoSndbuf, Settings.SendBufferSize.Value); if (Settings.WriteBufferHighWaterMark.HasValue) client.Option(ChannelOption.WriteBufferHighWaterMark, Settings.WriteBufferHighWaterMark.Value); if (Settings.WriteBufferLowWaterMark.HasValue) client.Option(ChannelOption.WriteBufferLowWaterMark, Settings.WriteBufferLowWaterMark.Value); return client; } protected async Task<IPEndPoint> DnsToIPEndpoint(DnsEndPoint dns) { IPEndPoint endpoint; //if (!Settings.EnforceIpFamily) //{ // endpoint = await ResolveNameAsync(dns).ConfigureAwait(false); //} //else //{ var addressFamily = Settings.DnsUseIpv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; endpoint = await ResolveNameAsync(dns, addressFamily).ConfigureAwait(false); //} return endpoint; } #region private methods private void SetInitialChannelPipeline(IChannel channel) { var pipeline = channel.Pipeline; if (Settings.LogTransport) { pipeline.AddLast("Logger", new AkkaLoggingHandler(Log)); } if (InternalTransport == TransportMode.Tcp) { pipeline.AddLast("FrameDecoder", new LengthFieldBasedFrameDecoder(Settings.ByteOrder, (int)MaximumPayloadBytes, 0, 4, 0, 4, true)); if (Settings.BackwardsCompatibilityModeEnabled) { pipeline.AddLast("FrameEncoder", new HeliosBackwardsCompatabilityLengthFramePrepender(4, false)); } else { pipeline.AddLast("FrameEncoder", new LengthFieldPrepender(Settings.ByteOrder, 4, 0, false)); } } if(Settings.BatchWriterSettings.EnableBatching) pipeline.AddLast("BatchWriter", new FlushConsolidationHandler(Settings.BatchWriterSettings.MaxExplicitFlushes)); } private void SetClientPipeline(IChannel channel, Address remoteAddress) { if (Settings.EnableSsl) { var certificate = Settings.Ssl.Certificate; var host = certificate.GetNameInfo(X509NameType.DnsName, false); var tlsHandler = Settings.Ssl.SuppressValidation ? new TlsHandler(stream => new SslStream(stream, true, (sender, cert, chain, errors) => true), new ClientTlsSettings(host)) : TlsHandler.Client(host, certificate); channel.Pipeline.AddFirst("TlsHandler", tlsHandler); } SetInitialChannelPipeline(channel); var pipeline = channel.Pipeline; if (InternalTransport == TransportMode.Tcp) { var handler = new TcpClientHandler(this, Logging.GetLogger(System, typeof(TcpClientHandler)), remoteAddress); pipeline.AddLast("ClientHandler", handler); } } private void SetServerPipeline(IChannel channel) { if (Settings.EnableSsl) { channel.Pipeline.AddFirst("TlsHandler", TlsHandler.Server(Settings.Ssl.Certificate)); } SetInitialChannelPipeline(channel); var pipeline = channel.Pipeline; if (Settings.TransportMode == TransportMode.Tcp) { var handler = new TcpServerHandler(this, Logging.GetLogger(System, typeof(TcpServerHandler)), AssociationListenerPromise.Task); pipeline.AddLast("ServerHandler", handler); } } private ServerBootstrap ServerFactory() { if (InternalTransport != TransportMode.Tcp) throw new NotSupportedException("Currently DotNetty server supports only TCP tranport mode."); var addressFamily = Settings.DnsUseIpv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; var server = new ServerBootstrap() .Group(_serverEventLoopGroup) .Option(ChannelOption.SoReuseaddr, Settings.TcpReuseAddr) .Option(ChannelOption.SoKeepalive, Settings.TcpKeepAlive) .Option(ChannelOption.TcpNodelay, Settings.TcpNoDelay) .Option(ChannelOption.AutoRead, false) .Option(ChannelOption.SoBacklog, Settings.Backlog) .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default) .ChannelFactory(() => Settings.EnforceIpFamily ? new TcpServerSocketChannel(addressFamily) : new TcpServerSocketChannel()) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(SetServerPipeline)); if (Settings.ReceiveBufferSize.HasValue) server.Option(ChannelOption.SoRcvbuf, Settings.ReceiveBufferSize.Value); if (Settings.SendBufferSize.HasValue) server.Option(ChannelOption.SoSndbuf, Settings.SendBufferSize.Value); if (Settings.WriteBufferHighWaterMark.HasValue) server.Option(ChannelOption.WriteBufferHighWaterMark, Settings.WriteBufferHighWaterMark.Value); if (Settings.WriteBufferLowWaterMark.HasValue) server.Option(ChannelOption.WriteBufferLowWaterMark, Settings.WriteBufferLowWaterMark.Value); return server; } private async Task<IPEndPoint> ResolveNameAsync(DnsEndPoint address) { var resolved = await Dns.GetHostEntryAsync(address.Host).ConfigureAwait(false); //NOTE: for some reason while Helios takes first element from resolved address list // on the DotNetty side we need to take the last one in order to be compatible return new IPEndPoint(resolved.AddressList[resolved.AddressList.Length - 1], address.Port); } private async Task<IPEndPoint> ResolveNameAsync(DnsEndPoint address, AddressFamily addressFamily) { var resolved = await Dns.GetHostEntryAsync(address.Host).ConfigureAwait(false); var found = resolved.AddressList.LastOrDefault(a => a.AddressFamily == addressFamily); if (found == null) { throw new KeyNotFoundException($"Couldn't resolve IP endpoint from provided DNS name '{address}' with address family of '{addressFamily}'"); } return new IPEndPoint(found, address.Port); } #endregion #region static methods public static Address MapSocketToAddress(IPEndPoint socketAddress, string schemeIdentifier, string systemName, string hostName = null, int? publicPort = null) { return socketAddress == null ? null : new Address(schemeIdentifier, systemName, SafeMapHostName(hostName) ?? SafeMapIPv6(socketAddress.Address), publicPort ?? socketAddress.Port); } private static string SafeMapHostName(string hostName) { IPAddress ip; return !string.IsNullOrEmpty(hostName) && IPAddress.TryParse(hostName, out ip) ? SafeMapIPv6(ip) : hostName; } private static string SafeMapIPv6(IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetworkV6 ? "[" + ip + "]" : ip.ToString(); public static EndPoint ToEndpoint(Address address) { if (!address.Port.HasValue) throw new ArgumentNullException(nameof(address), $"Address port must not be null: {address}"); IPAddress ip; return IPAddress.TryParse(address.Host, out ip) ? (EndPoint)new IPEndPoint(ip, address.Port.Value) : new DnsEndPoint(address.Host, address.Port.Value); } /// <summary> /// Maps an Akka.NET address to correlated <see cref="EndPoint"/>. /// </summary> /// <param name="address">Akka.NET fully qualified node address.</param> /// <exception cref="ArgumentException">Thrown if address port was not provided.</exception> /// <returns><see cref="IPEndPoint"/> for IP-based addresses, <see cref="DnsEndPoint"/> for named addresses.</returns> public static EndPoint AddressToSocketAddress(Address address) { if (address.Port == null) throw new ArgumentException($"address port must not be null: {address}"); EndPoint listenAddress; IPAddress ip; if (IPAddress.TryParse(address.Host, out ip)) { listenAddress = new IPEndPoint(ip, (int)address.Port); } else { // DNS resolution will be performed by the transport listenAddress = new DnsEndPoint(address.Host, (int)address.Port); } return listenAddress; } #endregion } internal class HeliosBackwardsCompatabilityLengthFramePrepender : LengthFieldPrepender { private readonly List<object> _temporaryOutput = new List<object>(2); public HeliosBackwardsCompatabilityLengthFramePrepender(int lengthFieldLength, bool lengthFieldIncludesLengthFieldLength) : base(ByteOrder.LittleEndian, lengthFieldLength, 0, lengthFieldIncludesLengthFieldLength) { } protected override void Encode(IChannelHandlerContext context, IByteBuffer message, List<object> output) { base.Encode(context, message, output); var lengthFrame = (IByteBuffer)_temporaryOutput[0]; var combined = lengthFrame.WriteBytes(message); ReferenceCountUtil.SafeRelease(message, 1); // ready to release it - bytes have been copied output.Add(combined.Retain()); _temporaryOutput.Clear(); } } }
45.261569
182
0.635563
[ "Apache-2.0" ]
aTiKhan/akka.net
src/core/Akka.Remote/Transport/DotNetty/DotNettyTransport.cs
22,497
C#
using Upgrade; namespace Ship { namespace SecondEdition.TIEFoFighter { public class EpsilonSquadronCadet : TIEFoFighter { public EpsilonSquadronCadet() : base() { PilotInfo = new PilotCardInfo( "Epsilon Squadron Cadet", 1, 25 ); ImageUrl = "https://vignette.wikia.nocookie.net/xwing-miniatures-second-edition/images/1/18/Swz26_a1_epsilon-pilot.png"; } } } }
24.590909
136
0.513863
[ "MIT" ]
Arahain/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Pilots/TIEFoFighter/EpsilonSquadronCadet.cs
543
C#
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Threading; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; /// <summary> /// Keeps logging configuration and provides simple API to modify it. /// </summary> ///<remarks>This class is thread-safe.<c>.ToList()</c> is used for that purpose.</remarks> public class LoggingConfiguration { private readonly IDictionary<string, Target> _targets = new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase); private List<object> _configItems = new List<object>(); /// <summary> /// Variables defined in xml or in API. name is case case insensitive. /// </summary> private readonly ThreadSafeDictionary<string, SimpleLayout> _variables = new ThreadSafeDictionary<string, SimpleLayout>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets the factory that will be configured /// </summary> public LogFactory LogFactory { get; } /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration() : this(LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration(LogFactory logFactory) { LogFactory = logFactory ?? LogManager.LogFactory; LoggingRules = new List<LoggingRule>(); } /// <summary> /// Use the old exception log handling of NLog 3.0? /// </summary> /// <remarks>This method was marked as obsolete on NLog 4.1 and it may be removed in a future release.</remarks> [Obsolete("This option will be removed in NLog 5. Marked obsolete on NLog 4.1")] public bool ExceptionLoggingOldStyle { get; set; } /// <summary> /// Gets the variables defined in the configuration. /// </summary> public IDictionary<string, SimpleLayout> Variables => _variables; /// <summary> /// Gets a collection of named targets specified in the configuration. /// </summary> /// <returns> /// A list of named targets. /// </returns> /// <remarks> /// Unnamed targets (such as those wrapped by other targets) are not returned. /// </remarks> public ReadOnlyCollection<Target> ConfiguredNamedTargets => GetAllTargetsThreadSafe().AsReadOnly(); /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// </summary> public virtual IEnumerable<string> FileNamesToWatch => ArrayHelper.Empty<string>(); /// <summary> /// Gets the collection of logging rules. /// </summary> public IList<LoggingRule> LoggingRules { get; private set; } internal List<LoggingRule> GetLoggingRulesThreadSafe() { lock (LoggingRules) return LoggingRules.ToList(); } private void AddLoggingRulesThreadSafe(LoggingRule rule) { lock (LoggingRules) LoggingRules.Add(rule); } private bool TryGetTargetThreadSafe(string name, out Target target) { lock (_targets) return _targets.TryGetValue(name, out target); } private List<Target> GetAllTargetsThreadSafe() { lock (_targets) return _targets.Values.ToList(); } private Target RemoveTargetThreadSafe(string name) { Target target; lock (_targets) { if (_targets.TryGetValue(name, out target)) { _targets.Remove(name); } } if (target != null) { InternalLogger.Debug("Unregistered target {0}: {1}", name, target.GetType().FullName); } return target; } private void AddTargetThreadSafe(string name, Target target, bool forceOverwrite) { if (string.IsNullOrEmpty(name) && !forceOverwrite) return; lock (_targets) { if (!forceOverwrite && _targets.ContainsKey(name)) return; _targets[name] = target; } if (!string.IsNullOrEmpty(target.Name) && target.Name != name) { InternalLogger.Info("Registered target {0}: {1} (Target created with different name: {2})", name, target.GetType().FullName, target.Name); } else { InternalLogger.Debug("Registered target {0}: {1}", name, target.GetType().FullName); } } /// <summary> /// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get; set; } /// <summary> /// Gets all targets. /// </summary> public ReadOnlyCollection<Target> AllTargets { get { var configTargets = _configItems.OfType<Target>(); return configTargets.Concat(GetAllTargetsThreadSafe()).Distinct(TargetNameComparer).ToList().AsReadOnly(); } } /// <summary> /// Compare <see cref="Target"/> objects based on their name. /// </summary> /// <remarks>This property is use to cache the comparer object.</remarks> private static readonly IEqualityComparer<Target> TargetNameComparer = new TargetNameEqualityComparer(); /// <summary> /// Defines methods to support the comparison of <see cref="Target"/> objects for equality based on their name. /// </summary> private class TargetNameEqualityComparer : IEqualityComparer<Target> { public bool Equals(Target x, Target y) { return string.Equals(x.Name, y.Name); } public int GetHashCode(Target obj) { return (obj.Name != null ? obj.Name.GetHashCode() : 0); } } /// <summary> /// Registers the specified target object. The name of the target is read from <see cref="Target.Name"/>. /// </summary> /// <param name="target"> /// The target object with a non <see langword="null"/> <see cref="Target.Name"/> /// </param> /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception> public void AddTarget([NotNull] Target target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (target.Name == null) { throw new ArgumentNullException(nameof(target) + ".Name cannot be null."); } AddTargetThreadSafe(target.Name, target, true); } /// <summary> /// Registers the specified target object under a given name. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="target">The target object.</param> /// <exception cref="ArgumentException">when <paramref name="name"/> is <see langword="null"/></exception> /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception> public void AddTarget(string name, Target target) { if (name == null) { // TODO: NLog 5 - The ArgumentException should be changed to ArgumentNullException for name parameter. throw new ArgumentException("Target name cannot be null", nameof(name)); } if (target == null) { throw new ArgumentNullException(nameof(target)); } AddTargetThreadSafe(name, target, true); } /// <summary> /// Finds the target with the specified name. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <returns> /// Found target or <see langword="null"/> when the target is not found. /// </returns> public Target FindTargetByName(string name) { Target value; if (!TryGetTargetThreadSafe(name, out value)) { return null; } return value; } /// <summary> /// Finds the target with the specified name and specified type. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <typeparam name="TTarget">Type of the target</typeparam> /// <returns> /// Found target or <see langword="null"/> when the target is not found of not of type <typeparamref name="TTarget"/> /// </returns> public TTarget FindTargetByName<TTarget>(string name) where TTarget : Target { return FindTargetByName(name) as TTarget; } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogRuntimeException("Target '{0}' not found", targetName); } AddRule(minLevel, maxLevel, target, loggerNamePattern, false); } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern = "*") { if (target == null) { throw new ArgumentNullException(nameof(target)); } AddRule(minLevel, maxLevel, target, loggerNamePattern, false); } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="final">Gets or sets a value indicating whether to quit processing any further rule when this one matches.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern, bool final) { if (target == null) { throw new ArgumentNullException(nameof(target)); } AddLoggingRulesThreadSafe(new LoggingRule(loggerNamePattern, minLevel, maxLevel, target) { Final = final }); AddTargetThreadSafe(target.Name, target, false); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogConfigurationException("Target '{0}' not found", targetName); } AddRuleForOneLevel(level, target, loggerNamePattern, false); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*") { if (target == null) { throw new ArgumentNullException(nameof(target)); } AddRuleForOneLevel(level, target, loggerNamePattern, false); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="final">Gets or sets a value indicating whether to quit processing any further rule when this one matches.</param> public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern, bool final) { if (target == null) { throw new ArgumentNullException(nameof(target)); } var loggingRule = new LoggingRule(loggerNamePattern, target) { Final = final }; loggingRule.EnableLoggingForLevel(level); AddLoggingRulesThreadSafe(loggingRule); AddTargetThreadSafe(target.Name, target, false); } /// <summary> /// Add a rule for all loglevels. /// </summary> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogRuntimeException("Target '{0}' not found", targetName); } AddRuleForAllLevels(target, loggerNamePattern, false); } /// <summary> /// Add a rule for all loglevels. /// </summary> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(Target target, string loggerNamePattern = "*") { if (target == null) { throw new ArgumentNullException(nameof(target)); } AddRuleForAllLevels(target, loggerNamePattern, false); } /// <summary> /// Add a rule for all loglevels. /// </summary> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="final">Gets or sets a value indicating whether to quit processing any further rule when this one matches.</param> public void AddRuleForAllLevels(Target target, string loggerNamePattern, bool final) { if (target == null) { throw new ArgumentNullException(nameof(target)); } var loggingRule = new LoggingRule(loggerNamePattern, target) { Final = final }; loggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); AddLoggingRulesThreadSafe(loggingRule); AddTargetThreadSafe(target.Name, target, false); } /// <summary> /// Finds the logging rule with the specified name. /// </summary> /// <param name="ruleName">The name of the logging rule to be found.</param> /// <returns>Found logging rule or <see langword="null"/> when not found.</returns> public LoggingRule FindRuleByName(string ruleName) { if (ruleName == null) return null; var loggingRules = GetLoggingRulesThreadSafe(); for (int i = loggingRules.Count - 1; i >= 0; i--) { if (string.Equals(loggingRules[i].RuleName, ruleName, StringComparison.OrdinalIgnoreCase)) { return loggingRules[i]; } } return null; } /// <summary> /// Removes the specified named logging rule. /// </summary> /// <param name="ruleName">The name of the logging rule to be removed.</param> /// <returns>Found one or more logging rule to remove, or <see langword="false"/> when not found.</returns> public bool RemoveRuleByName(string ruleName) { if (ruleName == null) return false; HashSet<LoggingRule> removedRules = new HashSet<LoggingRule>(); var loggingRules = GetLoggingRulesThreadSafe(); foreach (var loggingRule in loggingRules) { if (string.Equals(loggingRule.RuleName, ruleName, StringComparison.OrdinalIgnoreCase)) { removedRules.Add(loggingRule); } } if (removedRules.Count > 0) { lock (LoggingRules) { for (int i = LoggingRules.Count - 1; i >= 0; i--) { if (removedRules.Contains(LoggingRules[i])) { LoggingRules.RemoveAt(i); } } } } return removedRules.Count > 0; } /// <summary> /// Called by LogManager when one of the log configuration files changes. /// </summary> /// <returns> /// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration. /// </returns> public virtual LoggingConfiguration Reload() { return this; } internal LoggingConfiguration ReloadNewConfig() { var newConfig = Reload(); if (newConfig != null) { //problem: XmlLoggingConfiguration.Initialize eats exception with invalid XML. ALso XmlLoggingConfiguration.Reload never returns null. //therefor we check the InitializeSucceeded property. if (newConfig is XmlLoggingConfiguration xmlConfig && xmlConfig.InitializeSucceeded != true) { InternalLogger.Warn("NLog Config Reload() failed. Invalid XML?"); return null; } if (LogFactory.KeepVariablesOnReload) { var currentConfig = LogFactory._config ?? this; if (!ReferenceEquals(newConfig, currentConfig)) { newConfig.CopyVariables(currentConfig.Variables); } } } return newConfig; } /// <summary> /// Removes the specified named target. /// </summary> /// <param name="name">Name of the target.</param> public void RemoveTarget(string name) { HashSet<Target> removedTargets = new HashSet<Target>(); Target removedTarget = RemoveTargetThreadSafe(name); if (removedTarget != null) { removedTargets.Add(removedTarget); } if (!string.IsNullOrEmpty(name) || removedTarget != null) { CleanupRulesForRemovedTarget(name, removedTarget, removedTargets); } if (removedTargets.Count > 0) { ValidateConfig(); // Refresh internal list of configurable items (_configItems) // Refresh active logger-objects, so they stop using the removed target // - Can be called even if no LoggingConfiguration is loaded (will not trigger a config load) LogFactory.ReconfigExistingLoggers(); // Perform flush and close after having stopped logger-objects from using the target ManualResetEvent flushCompleted = new ManualResetEvent(false); foreach (var target in removedTargets) { flushCompleted.Reset(); target.Flush((ex) => flushCompleted.Set()); flushCompleted.WaitOne(TimeSpan.FromSeconds(15)); target.Close(); } } } private void CleanupRulesForRemovedTarget(string name, Target removedTarget, HashSet<Target> removedTargets) { var loggingRules = GetLoggingRulesThreadSafe(); foreach (var rule in loggingRules) { var targetList = rule.GetTargetsThreadSafe(); foreach (var target in targetList) { if (ReferenceEquals(removedTarget, target) || (!string.IsNullOrEmpty(name) && target.Name == name)) { removedTargets.Add(target); rule.RemoveTargetThreadSafe(target); } } } } /// <summary> /// Installs target-specific objects on current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Installation typically runs with administrative permissions. /// </remarks> public void Install(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException(nameof(installationContext)); } InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Installing '{0}'", installable); try { installable.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Install of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately() || installationContext.ThrowExceptions) { throw; } installationContext.Error("Install of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException(nameof(installationContext)); } InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Uninstall of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately()) { throw; } installationContext.Error("Uninstall of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Closes all targets and releases any unmanaged resources. /// </summary> internal void Close() { InternalLogger.Debug("Closing logging configuration..."); var supportsInitializesList = GetSupportsInitializes(); foreach (ISupportsInitialize initialize in supportsInitializesList) { InternalLogger.Trace("Closing {0}", initialize); try { initialize.Close(); } catch (Exception exception) { InternalLogger.Warn(exception, "Exception while closing."); if (exception.MustBeRethrown()) { throw; } } } InternalLogger.Debug("Finished closing logging configuration."); } /// <summary> /// Log to the internal (NLog) logger the information about the <see cref="Target"/> and <see /// cref="LoggingRule"/> associated with this <see cref="LoggingConfiguration"/> instance. /// </summary> /// <remarks> /// The information are only recorded in the internal logger if Debug level is enabled, otherwise nothing is /// recorded. /// </remarks> internal void Dump() { if (!InternalLogger.IsDebugEnabled) { return; } InternalLogger.Debug("--- NLog configuration dump ---"); InternalLogger.Debug("Targets:"); var targetList = GetAllTargetsThreadSafe(); foreach (Target target in targetList) { InternalLogger.Debug("{0}", target); } InternalLogger.Debug("Rules:"); foreach (LoggingRule rule in GetLoggingRulesThreadSafe()) { InternalLogger.Debug("{0}", rule); } InternalLogger.Debug("--- End of NLog configuration dump ---"); } internal List<Target> GetAllTargetsToFlush() { var uniqueTargets = new List<Target>(); foreach (var rule in GetLoggingRulesThreadSafe()) { var targetList = rule.GetTargetsThreadSafe(); foreach (var target in targetList) { if (!uniqueTargets.Contains(target)) { uniqueTargets.Add(target); } } } return uniqueTargets; } /// <summary> /// Validates the configuration. /// </summary> internal void ValidateConfig() { var roots = new List<object>(); foreach (LoggingRule rule in GetLoggingRulesThreadSafe()) { roots.Add(rule); } var targetList = GetAllTargetsThreadSafe(); foreach (Target target in targetList) { roots.Add(target); } _configItems = ObjectGraphScanner.FindReachableObjects<object>(true, roots.ToArray()); InternalLogger.Info("Validating config: {0}", this); foreach (object o in _configItems) { try { if (o is ISupportsInitialize) continue; // Target + Layout + LayoutRenderer validate on Initialize() PropertyHelper.CheckRequiredParameters(o); } catch (Exception ex) { if (ex.MustBeRethrown()) throw; } } } internal void InitializeAll() { bool firstInitializeAll = _configItems.Count == 0; if (firstInitializeAll && (LogFactory.ThrowExceptions || LogManager.ThrowExceptions)) { InternalLogger.Info("LogManager.ThrowExceptions = true can crash the application! Use only for unit-testing and last resort troubleshooting."); } ValidateConfig(); if (firstInitializeAll && _targets.Count > 0) { CheckUnusedTargets(); } // initialize all config items starting from most nested first // so that whenever the container is initialized its children have already been var supportsInitializes = GetSupportsInitializes(true); foreach (ISupportsInitialize initialize in supportsInitializes) { InternalLogger.Trace("Initializing {0}", initialize); try { initialize.Initialize(this); } catch (Exception exception) { if (exception.MustBeRethrown(initialize as IInternalLoggerContext)) { throw; } if (LogManager.ThrowExceptions) { throw new NLogConfigurationException($"Error during initialization of {initialize}", exception); } } } } private List<IInstallable> GetInstallableItems() { return _configItems.OfType<IInstallable>().ToList(); } private List<ISupportsInitialize> GetSupportsInitializes(bool reverse = false) { var items = _configItems.OfType<ISupportsInitialize>(); if (reverse) { items = items.Reverse(); } return items.ToList(); } /// <summary> /// Copies all variables from provided dictionary into current configuration variables. /// </summary> /// <param name="masterVariables">Master variables dictionary</param> internal void CopyVariables(IDictionary<string, SimpleLayout> masterVariables) { _variables.CopyFrom(masterVariables); } /// <summary> /// Replace a simple variable with a value. The original value is removed and thus we cannot redo this in a later stage. /// </summary> /// <param name="input"></param> /// <returns></returns> [NotNull] internal string ExpandSimpleVariables(string input) { string output = input; if (Variables.Count > 0 && output?.IndexOf('$') >= 0) { // TODO - make this case-insensitive, will probably require a different approach var variables = Variables.ToList(); foreach (var kvp in variables) { var layout = kvp.Value; //this value is set from xml and that's a string. Because of that, we can use SimpleLayout here. if (layout != null) output = output.Replace(string.Concat("${", kvp.Key, "}"), layout.OriginalText); } } return output ?? string.Empty; } /// <summary> /// Checks whether unused targets exist. If found any, just write an internal log at Warn level. /// <remarks>If initializing not started or failed, then checking process will be canceled</remarks> /// </summary> internal void CheckUnusedTargets() { if (!InternalLogger.IsWarnEnabled) return; var configuredNamedTargets = GetAllTargetsThreadSafe(); //assign to variable because `GetAllTargetsThreadSafe` computes a new list every time. InternalLogger.Debug("Unused target checking is started... Rule Count: {0}, Target Count: {1}", LoggingRules.Count, configuredNamedTargets.Count); var targetNamesAtRules = new HashSet<string>(GetLoggingRulesThreadSafe().SelectMany(r => r.Targets).Select(t => t.Name)); var allTargets = AllTargets; var wrappedTargets = allTargets.OfType<WrapperTargetBase>().ToLookup(wt => wt.WrappedTarget, wt => wt); var compoundTargets = allTargets.OfType<CompoundTargetBase>().SelectMany(wt => wt.Targets.Select(t => new KeyValuePair<Target, Target>(t, wt))).ToLookup(p => p.Key, p => p.Value); bool IsUnusedInList<T>(Target target1, ILookup<Target, T> targets) where T:Target { if (targets.Contains(target1)) { foreach (var wrapperTarget in targets[target1]) { if (targetNamesAtRules.Contains(wrapperTarget.Name)) return false; if (wrappedTargets.Contains(wrapperTarget)) return false; if (compoundTargets.Contains(wrapperTarget)) return false; } } return true; } int unusedCount = configuredNamedTargets.Count((target) => { if (targetNamesAtRules.Contains(target.Name)) return false; if (!IsUnusedInList(target, wrappedTargets)) return false; if (!IsUnusedInList(target, compoundTargets)) return false; InternalLogger.Warn("Unused target detected. Add a rule for this target to the configuration. TargetName: {0}", target.Name); return true; }); InternalLogger.Debug("Unused target checking is completed. Total Rule Count: {0}, Total Target Count: {1}, Unused Target Count: {2}", LoggingRules.Count, configuredNamedTargets.Count, unusedCount); } /// <inheritdoc /> public override string ToString() { var targets = GetAllTargetsToFlush(); if (targets.Count == 0) targets = GetAllTargetsThreadSafe(); if (targets.Count == 0) targets = AllTargets.ToList(); if (targets.Count > 0 && targets.Count < 5) return $"TargetNames={string.Join(", ", targets.Select(t => t.Name).Where(n => !string.IsNullOrEmpty(n)).ToArray())}, ConfigItems={_configItems.Count}"; else return $"Targets={targets.Count}, ConfigItems={_configItems.Count}"; } } }
41.11039
209
0.567735
[ "BSD-3-Clause" ]
aTiKhan/NLog
src/NLog/Config/LoggingConfiguration.cs
37,986
C#
using System; namespace SolutionLauncher { public enum SlnOpenWith { Ask = 0, VisualStudio, XamarinStudio } }
13.363636
27
0.585034
[ "MIT" ]
Redth/MSSolutionLauncher
MSSolutionLauncher/SlnOpenWith.cs
149
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Unity.Animations.SpringBones { public static class SpringColliderSetup { public static IEnumerable<System.Type> GetColliderTypes() { return new System.Type[] { typeof(SpringSphereCollider), typeof(SpringCapsuleCollider), typeof(SpringPanelCollider) }; } public static void DestroySpringColliders(GameObject colliderRoot) { DestroyComponentsOfType<SpringSphereCollider>(colliderRoot); DestroyComponentsOfType<SpringCapsuleCollider>(colliderRoot); DestroyComponentsOfType<SpringPanelCollider>(colliderRoot); var springBones = colliderRoot.GetComponentsInChildren<SpringBone>(true); foreach (var springBone in springBones) { springBone.sphereColliders = springBone.sphereColliders.Where(collider => collider != null).ToArray(); springBone.capsuleColliders = springBone.capsuleColliders.Where(collider => collider != null).ToArray(); springBone.panelColliders = springBone.panelColliders.Where(collider => collider != null).ToArray(); } } // private private static void DestroyComponentsOfType<T>(GameObject rootObject) where T : Component { var components = rootObject.GetComponentsInChildren<T>(true); foreach (var component in components) { DestroyUnityObject(component); } } private static void DestroyUnityObject(UnityEngine.Object objectToDestroy) { #if UNITY_EDITOR UnityEditor.Undo.DestroyObjectImmediate(objectToDestroy); #else Object.DestroyImmediate(objectToDestroy); #endif } } }
36.092593
121
0.623397
[ "MIT" ]
cyriaca/UnityChanSpringBone
Runtime/Setup/SpringColliderSetup.cs
1,951
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// LolLobbyAutoFillQueueDto /// </summary> [DataContract] public partial class LolLobbyAutoFillQueueDto : IEquatable<LolLobbyAutoFillQueueDto>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LolLobbyAutoFillQueueDto" /> class. /// </summary> /// <param name="AutoFillEligible">AutoFillEligible.</param> /// <param name="AutoFillProtectedForPromos">AutoFillProtectedForPromos.</param> /// <param name="AutoFillProtectedForStreaking">AutoFillProtectedForStreaking.</param> /// <param name="QueueId">QueueId.</param> public LolLobbyAutoFillQueueDto(bool? AutoFillEligible = default(bool?), bool? AutoFillProtectedForPromos = default(bool?), bool? AutoFillProtectedForStreaking = default(bool?), int? QueueId = default(int?)) { this.AutoFillEligible = AutoFillEligible; this.AutoFillProtectedForPromos = AutoFillProtectedForPromos; this.AutoFillProtectedForStreaking = AutoFillProtectedForStreaking; this.QueueId = QueueId; } /// <summary> /// Gets or Sets AutoFillEligible /// </summary> [DataMember(Name="autoFillEligible", EmitDefaultValue=false)] public bool? AutoFillEligible { get; set; } /// <summary> /// Gets or Sets AutoFillProtectedForPromos /// </summary> [DataMember(Name="autoFillProtectedForPromos", EmitDefaultValue=false)] public bool? AutoFillProtectedForPromos { get; set; } /// <summary> /// Gets or Sets AutoFillProtectedForStreaking /// </summary> [DataMember(Name="autoFillProtectedForStreaking", EmitDefaultValue=false)] public bool? AutoFillProtectedForStreaking { get; set; } /// <summary> /// Gets or Sets QueueId /// </summary> [DataMember(Name="queueId", EmitDefaultValue=false)] public int? QueueId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LolLobbyAutoFillQueueDto {\n"); sb.Append(" AutoFillEligible: ").Append(AutoFillEligible).Append("\n"); sb.Append(" AutoFillProtectedForPromos: ").Append(AutoFillProtectedForPromos).Append("\n"); sb.Append(" AutoFillProtectedForStreaking: ").Append(AutoFillProtectedForStreaking).Append("\n"); sb.Append(" QueueId: ").Append(QueueId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LolLobbyAutoFillQueueDto); } /// <summary> /// Returns true if LolLobbyAutoFillQueueDto instances are equal /// </summary> /// <param name="other">Instance of LolLobbyAutoFillQueueDto to be compared</param> /// <returns>Boolean</returns> public bool Equals(LolLobbyAutoFillQueueDto other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AutoFillEligible == other.AutoFillEligible || this.AutoFillEligible != null && this.AutoFillEligible.Equals(other.AutoFillEligible) ) && ( this.AutoFillProtectedForPromos == other.AutoFillProtectedForPromos || this.AutoFillProtectedForPromos != null && this.AutoFillProtectedForPromos.Equals(other.AutoFillProtectedForPromos) ) && ( this.AutoFillProtectedForStreaking == other.AutoFillProtectedForStreaking || this.AutoFillProtectedForStreaking != null && this.AutoFillProtectedForStreaking.Equals(other.AutoFillProtectedForStreaking) ) && ( this.QueueId == other.QueueId || this.QueueId != null && this.QueueId.Equals(other.QueueId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AutoFillEligible != null) hash = hash * 59 + this.AutoFillEligible.GetHashCode(); if (this.AutoFillProtectedForPromos != null) hash = hash * 59 + this.AutoFillProtectedForPromos.GetHashCode(); if (this.AutoFillProtectedForStreaking != null) hash = hash * 59 + this.AutoFillProtectedForStreaking.GetHashCode(); if (this.QueueId != null) hash = hash * 59 + this.QueueId.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
39.339181
215
0.588227
[ "MIT" ]
wildbook/LeagueClientApi
Model/LolLobbyAutoFillQueueDto.cs
6,727
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.NetworkFirewall.Outputs { [OutputType] public sealed class RuleGroupRuleGroupRulesSourceStatefulRule { /// <summary> /// Action to take with packets in a traffic flow when the flow matches the stateful rule criteria. For all actions, AWS Network Firewall performs the specified action and discontinues stateful inspection of the traffic flow. Valid values: `ALERT`, `DROP` or `PASS`. /// </summary> public readonly string Action; /// <summary> /// A configuration block containing the stateful 5-tuple inspection criteria for the rule, used to inspect traffic flows. See Header below for details. /// </summary> public readonly Outputs.RuleGroupRuleGroupRulesSourceStatefulRuleHeader Header; /// <summary> /// Set of configuration blocks containing additional settings for a stateful rule. See Rule Option below for details. /// </summary> public readonly ImmutableArray<Outputs.RuleGroupRuleGroupRulesSourceStatefulRuleRuleOption> RuleOptions; [OutputConstructor] private RuleGroupRuleGroupRulesSourceStatefulRule( string action, Outputs.RuleGroupRuleGroupRulesSourceStatefulRuleHeader header, ImmutableArray<Outputs.RuleGroupRuleGroupRulesSourceStatefulRuleRuleOption> ruleOptions) { Action = action; Header = header; RuleOptions = ruleOptions; } } }
42.069767
274
0.70702
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/NetworkFirewall/Outputs/RuleGroupRuleGroupRulesSourceStatefulRule.cs
1,809
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace PaperMarioBattleSystem { public class SpikedGoomba : Goomba, ITattleableEntity { public SpikedGoomba() { Name = "Spiked Goomba"; BattleStats = new Stats(1, 2, 0, 1, 0); EntityProperties.AddPhysAttribute(Enumerations.PhysicalAttributes.Spiked); EntityProperties.AddPayback(new StatusGlobals.PaybackHolder(StatusGlobals.PaybackTypes.Constant, Enumerations.PhysicalAttributes.Spiked, Enumerations.Elements.Sharp, new Enumerations.ContactTypes[] { Enumerations.ContactTypes.TopDirect }, new Enumerations.ContactProperties[] { Enumerations.ContactProperties.None }, Enumerations.ContactResult.Failure, Enumerations.ContactResult.Failure, 1, null)); } public override void LoadAnimations() { base.LoadAnimations(); Texture2D spriteSheet = AssetManager.Instance.LoadRawTexture2D($"{ContentGlobals.SpriteRoot}/Enemies/SpikedGoomba.png"); AnimManager.SetSpriteSheet(spriteSheet); AnimManager.AddAnimation(AnimationGlobals.IdleName, new ReverseAnimation(spriteSheet, AnimationGlobals.InfiniteLoop, new Animation.Frame(new Rectangle(34, 153, 28, 39), 1000d), new Animation.Frame(new Rectangle(67, 152, 26, 40), 150d), new Animation.Frame(new Rectangle(67, 110, 26, 42), 1000d, new Vector2(0, -1)))); AnimManager.AddAnimation(AnimationGlobals.HurtName, new Animation(spriteSheet, new Animation.Frame(new Rectangle(32, 68, 31, 36), 80d), new Animation.Frame(new Rectangle(128, 108, 31, 36), 80d))); AnimManager.AddAnimation(AnimationGlobals.DeathName, new Animation(spriteSheet, new Animation.Frame(new Rectangle(128, 108, 31, 36), 300d))); AnimManager.AddAnimation(AnimationGlobals.RunningName, new ReverseAnimation(spriteSheet, AnimationGlobals.InfiniteLoop, new Animation.Frame(new Rectangle(98, 153, 29, 39), 150d), new Animation.Frame(new Rectangle(34, 153, 28, 39), 100d), new Animation.Frame(new Rectangle(34, 110, 30, 42), 150d, new Vector2(0, -1)))); AnimManager.AddAnimation(AnimationGlobals.JumpStartName, new Animation(spriteSheet, new Animation.Frame(new Rectangle(98, 113, 28, 39), 400d))); } #region Tattle Information public new string[] GetTattleLogEntry() { return new string[] { $"HP: {BattleStats.MaxHP} Attack: {BattleStats.BaseAttack}\nDefense: {BattleStats.BaseDefense}", $"A Goomba that wears a\nspiked helmet. Slightly", "higher attack power than\n a typical Goomba." }; } public new string GetTattleDescription() { return "That's a Spiky Goomba.\n<wait value=\"250\">...A spiky-headed Goomba.\n<wait value=\"250\">What a creative name.\n<k><p>" + "That spike is super-pointy, so\nit's better to hit it with a\nhammer than jump on it.\n<k><p>" + "Maximum HP is 2, Attack is 2,\nand Defense is 0.\n<k><p>" + "The addition of the spike\nmeans you'll hurt your feet\nif you jump on it. <wait value=\"100\">Duh!<k>"; } #endregion } }
50.472222
154
0.630985
[ "Unlicense" ]
kimimaru4000/PaperMarioBattleSystem
PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/BattleEntities/Enemies/SpikedGoomba.cs
3,636
C#
using eFormCore; using eFormSDK.Wrapper; using RGiesecke.DllExport; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Microting.eForm.Wrapper { public static class AdminToolsW { private static AdminTools program; [DllExport("AdminTools_Create")] public static int AdminTools_Create([MarshalAs(UnmanagedType.BStr)]String serverConnectionString) { int result = 0; try { program = new AdminTools(serverConnectionString); } catch (Exception ex) { LastError.Value = ex.Message; result = 1; } return result; } [DllExport("AdminTools_DbSetup")] public static int AdminTools_DbSetup([MarshalAs(UnmanagedType.BStr)]String token, [MarshalAs(UnmanagedType.BStr)] ref string reply) { int result = 0; try { reply = program.DbSetup(token); } catch (Exception ex) { LastError.Value = ex.Message; result = 1; } return result; } [DllExport("AdminTools_DbSetupCompleted")] public static int AdminTools_DbSetupCompleted([MarshalAs(UnmanagedType.BStr)] ref string reply) { int result = 0; try { List<string> checkResult = program.DbSetupCompleted(); if (checkResult.Count == 1) { if (checkResult[0] == "NO SETTINGS PRESENT, NEEDS PRIMING!") reply = checkResult[0]; else reply = "Settings table is incomplete, please fix the following settings: " + String.Join(",", checkResult); } } catch (Exception ex) { LastError.Value = ex.Message; result = 1; } return result; } } }
27.910256
132
0.517226
[ "MIT" ]
microting/eform-sdk-delphi-wrapper
eFormSDK.Wrapper/AdminToolsW.cs
2,179
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; namespace JRunner.Panels { public partial class XeBuildPanel : UserControl { List<String> patches = new List<string>(new string[8]); // -a nofcrt // -a noSShdd // -a nointmu // -a nohdd // -a nohdmiwait // -a nolan // -r WB/WB4G/13182 public XeBuildPanel() { InitializeComponent(); checkDevGL("None"); } #region delegates public delegate void ClickedGetMB(); public event ClickedGetMB Getmb; public delegate void ChangedHack(); public event ChangedHack HackChanged; public delegate void DashAdded(); public event DashAdded AddedDash; public delegate void DashDeleted(); public event DashDeleted DeletedDash; public delegate void CallMotherboards(); public event CallMotherboards CallMB; public delegate void loadFile(ref string filename, bool erase = false); public event loadFile loadFil; public delegate void updateProgress(int progress); public event updateProgress UpdateProgres; public delegate void updateSource(string filename); public event updateSource updateSourc; public delegate void ModeDrive(); public event ModeDrive DriveMode; #endregion #region getters/setters public DataSet1 getDataSet() { return dataSet1; } public ComboBox getComboDash() { return comboDash; } // Hack Getters public bool getRbtnRetailChecked() { return rbtnRetail.Checked; } public bool getRbtnGlitchChecked() { return rbtnGlitch.Checked; } public bool getRbtnGlitch2Checked() { return rbtnGlitch2.Checked; } public bool getRbtnGlitch2mChecked() { return rbtnGlitch2m.Checked; } public bool getRbtnJtagChecked() { return rbtnJtag.Checked; } public bool getRbtnDevGLChecked() { return rbtnDevGL.Checked; } public string getRbtnChecked() { if (rbtnRetail.Checked) return "Retail"; else if (rbtnGlitch.Checked) return "Glitch"; else if (rbtnGlitch2.Checked) return "Glitch2"; else if (rbtnGlitch2m.Checked) return "Glitch2m"; else if (rbtnJtag.Checked) { if (chkRJtag.Checked) return "R-JTAG"; else return "JTAG"; } else if (rbtnDevGL.Checked) return "DEVGL"; else return ""; } // Hack Setters - invoke is in references, so no cross thread public void setRbtnRetailChecked(bool check) { if (check && !rbtnRetail.Enabled) return; rbtnRetail.Checked = check; } public void setRbtnGlitchChecked(bool check) { if (check && !rbtnGlitch.Enabled) return; rbtnGlitch.Checked = check; } public void setRbtnGlitch2Checked(bool check) { if (check && !rbtnGlitch2.Enabled) return; rbtnGlitch2.Checked = check; } public void setRbtnGlitch2mChecked(bool check) { if (check && !rbtnGlitch2m.Enabled) return; rbtnGlitch2m.Checked = check; } public void setRbtnJtagChecked(bool check) { if (check && !rbtnJtag.Enabled) return; rbtnJtag.Checked = check; } public void setRbtnDevGLChecked(bool check) { if (check && !rbtnDevGL.Enabled) return; rbtnDevGL.Checked = check; } // Checkbox Getters public bool getCleanSMCChecked() { return chkCleanSMC.Checked; } public bool getCR4Checked() { return chkCR4.Checked; } public bool getSMCPChecked() { return chkSMCP.Checked; } public bool getRgh3Checked() { return chkRgh3.Checked; } public int getRgh3Mhz() { return int.Parse(Rgh3Mhz.Text); } public bool getAudClampChecked() { return chkAudClamp.Checked; } public bool getRJtagChecked() { return chkRJtag.Checked; } public int getWBChecked() { if (chkWB.Checked) return 1; else if (chkWB4G.Checked) return 2; else return 0; } // Checkbox Setters public void setCleanSMCChecked(bool check) { if (check && !chkCleanSMC.Enabled) return; chkCleanSMC.Checked = check; } public void setNoFcrt(bool check) { chkListBoxPatches.SetItemChecked(0, check); } public void clear() { txtMBname.Text = "None Selected"; if (rbtnRetail.Enabled == true) rbtnRetail.Checked = true; else if (rbtnGlitch.Checked) rbtnGlitch.Checked = false; else if (rbtnGlitch2.Checked) rbtnGlitch2.Checked = false; else if (rbtnGlitch2m.Checked) rbtnGlitch2m.Checked = false; else if (rbtnJtag.Checked) rbtnJtag.Checked = false; else if (rbtnDevGL.Checked) rbtnDevGL.Checked = false; checkAvailableHackTypes(); tabControl1.SelectedTab = Xebuild; for (int i = 0; i < chkListBoxPatches.Items.Count; i++) { chkListBoxPatches.SetItemChecked(i, false); } chkxesettings.Checked = false; } public void setMBname(string txt) { txtMBname.BeginInvoke(new Action(() => { txtMBname.Text = txt; variables.boardtype = txt; checkAvailableHackTypes(); checkWB(txt); checkBigffs(txt); if (txt.Contains("Xenon")) { chkCR4.Checked = false; chkCR4.Enabled = false; chkSMCP.Checked = false; chkSMCP.Enabled = false; chkAudClamp.Checked = false; chkAudClamp.Enabled = false; } else { chkCR4.Enabled = true; chkSMCP.Enabled = true; chkAudClamp.Enabled = true; } checkRgh3(txt); })); } #endregion #region UI private void rbtn_CheckedChanged(object sender, EventArgs e) { if (rbtnRetail.Checked) { if (checkDLPatches.Checked) variables.DashLaunchE = checkDLPatches.Checked; checkDLPatches.Enabled = chkLaunch.Visible = false; if (sender.Equals(rbtnRetail)) Console.WriteLine("Retail Selected"); } else if (rbtnJtag.Checked) { checkDLPatches.Enabled = true; checkDLPatches.Checked = chkLaunch.Visible = variables.DashLaunchE; if (sender.Equals(rbtnJtag)) Console.WriteLine("JTAG Selected"); } else if (rbtnGlitch.Checked || rbtnGlitch2.Checked || rbtnGlitch2m.Checked) { checkDLPatches.Enabled = true; checkDLPatches.Checked = chkLaunch.Visible = variables.DashLaunchE; if (rbtnGlitch.Checked && sender.Equals(rbtnGlitch)) Console.WriteLine("Glitch Selected"); else if (rbtnGlitch2.Checked && sender.Equals(rbtnGlitch2)) Console.WriteLine("Glitch2 Selected"); else if (rbtnGlitch2m.Checked && sender.Equals(rbtnGlitch2m)) Console.WriteLine("Glitch2m Selected"); } else if (rbtnDevGL.Checked) { checkDLPatches.Enabled = true; checkDLPatches.Checked = chkLaunch.Visible = variables.DashLaunchE; if (sender.Equals(rbtnDevGL)) Console.WriteLine("DEVGL Selected"); } labelCB.Visible = comboCB.Visible = rbtnRetail.Checked; chkCleanSMC.Visible = rbtnRetail.Checked || rbtnGlitch.Checked || rbtnGlitch2.Checked || rbtnGlitch2m.Checked || rbtnDevGL.Checked; chkCR4.Visible = rbtnGlitch2.Checked || rbtnGlitch2m.Checked; chkSMCP.Visible = rbtnGlitch2.Checked || rbtnGlitch2m.Checked; chkRgh3.Visible = rbtnGlitch2.Checked || rbtnGlitch2m.Checked; chkAudClamp.Visible = rbtnJtag.Checked; chkRJtag.Visible = rbtnJtag.Checked; chk0Fuse.Visible = rbtnDevGL.Checked; checkWBXdkBuild(); checkBigffs(variables.boardtype); checkXLUsb(); if (!rbtnRetail.Checked && !rbtnGlitch.Checked && !rbtnGlitch2.Checked && !rbtnGlitch2m.Checked && !rbtnDevGL.Checked) chkCleanSMC.Checked = false; if (!rbtnGlitch2.Checked && !rbtnGlitch2m.Checked) { chkCR4.Checked = false; chkSMCP.Checked = false; chkRgh3.Checked = false; chkWB.Checked = false; chkWB4G.Checked = false; } if (!rbtnJtag.Checked) { chkAudClamp.Checked = false; chkRJtag.Checked = false; } checkRgh3(variables.boardtype); if (!rbtnDevGL.Checked) chk0Fuse.Checked = false; checkWB(variables.boardtype); try { HackChanged(); } catch (Exception) { } updateCommand(); setComboCB(rbtnRetail.Checked); } private void btnXeBuildOptions_Click(object sender, EventArgs e) { XBOptions xb = new XBOptions(); xb.ShowDialog(); chkxesettings.Checked = true; } private void btnLaunch_Click(object sender, EventArgs e) { DashLaunch myNewForm3 = new DashLaunch(); myNewForm3.ShowDialog(); } private void txtMBname_Click(object sender, EventArgs e) { CallMB(); } private void comboDash_SelectedIndexChanged(object sender, EventArgs e) { if (comboDash.SelectedIndex == comboDash.Items.Count - 2) { add_dash(); } else if (comboDash.SelectedIndex == comboDash.Items.Count - 1) { del_dash(); } else if (comboDash.SelectedIndex == comboDash.Items.Count - 3) { checkAvailableHackTypes(); // will set all false } else if (comboDash.SelectedIndex >= 0) { variables.preferredDash = comboDash.Text; variables.dashversion = Convert.ToInt32(comboDash.Text); lblDash.Text = comboDash.Text; } if (comboDash.SelectedIndex < comboDash.Items.Count - 3) { checkAvailableHackTypes(); } checkWBXdkBuild(); checkXLUsb(); updateCommand(); setComboCB(); } public void checkAvailableHackTypes() { if (comboDash.SelectedValue == null || comboDash.SelectedValue.ToString().Contains("-")) { rbtnRetail.Enabled = rbtnRetail.Checked = false; rbtnGlitch.Enabled = rbtnGlitch.Checked = false; rbtnGlitch2.Enabled = rbtnGlitch2.Checked = false; rbtnGlitch2m.Enabled = rbtnGlitch2m.Checked = false; rbtnJtag.Enabled = rbtnJtag.Checked = false; rbtnDevGL.Enabled = rbtnDevGL.Checked = false; return; } if (variables.debugme) Console.WriteLine(Path.Combine(variables.update_path, comboDash.SelectedValue + "\\_file.ini")); if (!File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + "\\_glitch2.ini"))) { rbtnGlitch2.Enabled = rbtnGlitch2.Checked = false; } else { checkGlitch2(variables.boardtype); } if (!File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + "\\_glitch2m.ini"))) { rbtnGlitch2m.Enabled = rbtnGlitch2m.Checked = false; } else { checkGlitch2m(variables.boardtype); } if (!File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + "\\_glitch.ini"))) { rbtnGlitch.Enabled = rbtnGlitch.Checked = false; } else { checkGlitch(variables.boardtype); } if (!File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + "\\_jtag.ini"))) { rbtnJtag.Enabled = rbtnJtag.Checked = false; } else { checkJtag(variables.boardtype); } if (!File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + "\\_retail.ini"))) { rbtnRetail.Checked = rbtnRetail.Enabled = false; } else { rbtnRetail.Enabled = true; } if (!File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + "\\_devgl.ini"))) { rbtnDevGL.Enabled = rbtnDevGL.Checked = false; } else { checkDevGL(variables.boardtype); } } private void checkJtag(string board) { if (board == null) board = "None"; if (board.Contains("Corona") || board.Contains("Trinity")) rbtnJtag.Enabled = rbtnJtag.Checked = false; else rbtnJtag.Enabled = true; } public void checkGlitch(string board) { if (board == null) board = "None"; if (variables.rghable) { if (board.Contains("Corona") || board.Contains("Trinity")) rbtnGlitch.Enabled = rbtnGlitch.Checked = false; else if (!variables.rgh1able) rbtnGlitch.Enabled = rbtnGlitch.Checked = false; else rbtnGlitch.Enabled = true; } else rbtnGlitch.Enabled = rbtnGlitch.Checked = false; } private void checkGlitch2(string board) { if (board == null) board = "None"; //if (board.Contains("Xenon")) rbtnGlitch2.Enabled = rbtnGlitch2.Checked = false; //else rbtnGlitch2.Enabled = true; } private void checkGlitch2m(string board) { if (board == null) board = "None"; if (variables.dashversion == 17489) { rbtnGlitch2m.Enabled = true; } else { if (board.Contains("Corona") || board.Contains("Trinity") || board.Contains("None")) rbtnGlitch2m.Enabled = true; else rbtnGlitch2m.Enabled = rbtnGlitch2m.Checked = false; } } private void checkDevGL(string board) { if (canDevGL(board)) rbtnDevGL.Enabled = true; else rbtnDevGL.Enabled = rbtnDevGL.Checked = false; } public bool canDevGL(string board) { if (board == null) board = "None"; if (File.Exists(Path.Combine(variables.rootfolder, @"xebuild\common\" + "sb_priv.bin"))) { if (board.Contains("Jasper") || board.Contains("Corona") || board.Contains("Trinity") || board.Contains("None")) return true; else return false; } else return false; } public void checkBigffs(string board) { if ((rbtnGlitch.Checked || rbtnGlitch2.Checked || rbtnGlitch2m.Checked || rbtnJtag.Checked || rbtnDevGL.Checked) && !chkXdkBuild.Checked) { if (board == null) board = "None"; if (board.Contains("Trinity BB")) chkBigffs.Enabled = true; else if (board.Contains("Xenon") || board.Contains("Zephyr") || board.Contains("Falcon") || board.Contains("Jasper 16MB") || board.Contains("Jasper SB") || board.Contains("Trinity") || board.Contains("Corona")) { chkBigffs.Checked = false; chkBigffs.Enabled = false; } else { chkBigffs.Enabled = true; } } else { chkBigffs.Checked = false; chkBigffs.Enabled = false; } } private void checkXLUsb() { if (File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + @"\bin\xl_usb.bin"))) { if (rbtnRetail.Checked) chkXLUsb.Checked = chkXLUsb.Enabled = false; else chkXLUsb.Enabled = true; } else chkXLUsb.Checked = chkXLUsb.Enabled = false; } bool chkWB4GVis = false; bool chkWB4GEn = true; public void checkWBXdkBuild() { if (rbtnGlitch2m.Checked && variables.dashversion == 17489 && File.Exists(variables.rootfolder + @"\xeBuild\17489\!XDKbuild Only!.txt")) { chkWB.Visible = false; chkWB.Checked = false; //chkWB4G.Visible = false; // chkWB4G.Checked = false; chkWB4GVis = false; chkXdkBuild.Visible = true; chkXdkBuild.Checked = true; } else { if (rbtnGlitch2.Checked || rbtnGlitch2m.Checked) { chkWB.Visible = true; //chkWB4G.Visible = true; chkWB4GVis = true; } else { chkWB.Visible = false; chkWB.Checked = false; //chkWB4G.Visible = false; //chkWB4G.Checked = false; chkWB4GVis = false; } chkXdkBuild.Visible = false; chkXdkBuild.Checked = false; } checkWB4G(); } private void checkWB(string board) { if (board == null) board = "None"; if ((board.Contains("Corona") || board.Contains("None")) && (rbtnGlitch2.Checked || rbtnGlitch2m.Checked) && !chkXdkBuild.Checked) { chkWB.Enabled = true; //chkWB4G.Enabled = true; chkWB4GEn = true; } else { chkWB.Checked = false; chkWB.Enabled = false; //chkWB4G.Checked = false; //chkWB4G.Enabled = false; chkWB4GEn = false; } checkWB4G(); } private void checkWB4G() { if (chkWB4GVis && chkWB4GEn) chkWB4G.Enabled = true; else { chkWB4G.Checked = false; chkWB4G.Enabled = false; } } private void checkDLPatches_CheckedChanged(object sender, EventArgs e) { variables.DashLaunchE = checkDLPatches.Checked; if (!checkDLPatches.Checked || !checkDLPatches.Enabled) { chkLaunch.Visible = false; chkLaunch.Checked = false; } else if (checkDLPatches.Checked && checkDLPatches.Enabled) chkLaunch.Visible = true; } public void setDLPatches(bool checkd) { checkDLPatches.Checked = chkLaunch.Checked = checkd; } private void btnDrive_Click(object sender, EventArgs e) { try { DriveMode(); } catch (Exception) { } } private void checkDLPatches_EnabledChanged(object sender, EventArgs e) { if (!checkDLPatches.Enabled) chkLaunch.Visible = false; else if (checkDLPatches.Checked) chkLaunch.Visible = true; } private void chkListBoxPatches_SelectedIndexChanged(object sender, EventArgs e) { int selected = chkListBoxPatches.SelectedIndex; if (selected >= 0 && selected <= 5) { if (chkListBoxPatches.GetItemChecked(selected)) { Console.WriteLine(chkListBoxPatches.Items[selected].ToString() + " Enabled"); if (selected == 0) patches[selected + 1] = "-a nofcrt"; else if (selected == 1) patches[selected + 1] = "-a noSShdd"; else if (selected == 2) patches[selected + 1] = "-a nointmu"; else if (selected == 3) patches[selected + 1] = "-a nohdd"; else if (selected == 4) patches[selected + 1] = "-a nohdmiwait"; else if (selected == 5) patches[selected + 1] = "-a nolan"; } else { Console.WriteLine(chkListBoxPatches.Items[selected].ToString() + " Disabled"); patches[selected + 1] = ""; } } updateCommand(); } private void chkRJtag_CheckedChanged(object sender, EventArgs e) { if (chkRJtag.Checked) Console.WriteLine("R-JTAG Selected"); else Console.WriteLine("R-JTAG Deselected"); } // Handling checkboxes allows us to only have one selected at time without extra stuff happening private void chkCleanSMC_CheckedChanged(object sender, EventArgs e) { if (chkCleanSMC.Checked) { Console.WriteLine("Clean SMC Selected"); chkCR4.Checked = false; chkSMCP.Checked = false; chkRgh3.Checked = false; } else if (!chkCR4.Checked && !chkSMCP.Checked && !chkRgh3.Checked) // Don't uselessly spam the console { Console.WriteLine("Clean SMC Deselected"); } if (chkCleanSMC.Checked) { if (File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin"))) { if (MessageBox.Show("smc.bin found. Delete it?\nUnless you put it there, delete it!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { File.Delete(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin")); } } } } private void chkCR4_CheckedChanged(object sender, EventArgs e) { if (chkCR4.Checked) { Console.WriteLine("CR4 Selected"); chkCleanSMC.Checked = false; chkSMCP.Checked = false; chkRgh3.Checked = false; } else if (!chkCleanSMC.Checked && !chkSMCP.Checked && !chkRgh3.Checked) // Don't uselessly spam the console { Console.WriteLine("CR4 Deselected"); } if (chkCR4.Checked) { if (File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin"))) { if (MessageBox.Show("smc.bin found. Delete it?\nUnless you put it there, delete it!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { File.Delete(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin")); } } } } private void chkSMCP_CheckedChanged(object sender, EventArgs e) { if (chkSMCP.Checked) { Console.WriteLine("SMC+ Selected"); chkCleanSMC.Checked = false; chkCR4.Checked = false; chkRgh3.Checked = false; } else if (!chkCleanSMC.Checked && !chkCR4.Checked && !chkRgh3.Checked) // Don't uselessly spam the console { Console.WriteLine("SMC+ Deselected"); } if (chkSMCP.Checked) { if (File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin"))) { if (MessageBox.Show("smc.bin found. Delete it?\nUnless you put it there, delete it!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { File.Delete(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin")); } } } } private void chkRgh3_CheckedChanged(object sender, EventArgs e) { if (chkRgh3.Checked) { Console.WriteLine("RGH3 Selected"); chkCleanSMC.Checked = false; chkCR4.Checked = false; chkSMCP.Checked = false; } else if (!chkCleanSMC.Checked && !chkCR4.Checked && !chkSMCP.Checked) // Don't uselessly spam the console { Console.WriteLine("RGH3 Deselected"); } if (chkRgh3.Checked) { if (File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin"))) { if (MessageBox.Show("smc.bin found. Delete it?\nUnless you put it there, delete it!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { File.Delete(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin")); } } } else Rgh3Mhz.SelectedIndex = 1; checkRgh3(variables.boardtype); } private void checkRgh3(string board) { if (board == null) board = "None"; if (board.Contains("Falcon") || board.Contains("Jasper")) { Rgh3Label.Visible = Rgh3Mhz.Visible = chkRgh3.Checked; Rgh3Label2.Visible = false; } else if (board.Contains("Trinity")) { Rgh3Label2.Text = "27"; Rgh3Label.Visible = Rgh3Label2.Visible = chkRgh3.Checked; Rgh3Mhz.Visible = false; } else if (board.Contains("Corona")) { Rgh3Label2.Text = "25"; Rgh3Label.Visible = Rgh3Label2.Visible = chkRgh3.Checked; Rgh3Mhz.Visible = false; } else { Rgh3Label.Visible = Rgh3Label2.Visible = Rgh3Mhz.Visible = false; } if (board.Contains("Xenon") || board.Contains("Zephyr") || board.Contains("Jasper SB") || board.Contains("Trinity BB")) { chkRgh3.Checked = false; chkRgh3.Enabled = false; } else chkRgh3.Enabled = true; } private void chkWB_CheckedChanged(object sender, EventArgs e) { if (chkWB.Checked) { Console.WriteLine("Winbond 2K Selected"); chkWB4G.Checked = false; } else if (!chkWB4G.Checked) // Don't uselessly spam the console { Console.WriteLine("Winbond 2K Deselected"); } // Don't do it twice if (!chkWB4G.Checked && chkWB.Checked) { updateWB(); } else if (!chkWB.Checked && !chkWB4G.Checked) { updateWB(); } } private void chkWB4G_CheckedChanged(object sender, EventArgs e) { if (chkWB4G.Checked) { MessageBox.Show("Warning: This function is for advanced users only\n\nIf you don't understand what this is for, use WB 2K on the XeBuild tab instead", "Steep Hill Ahead", MessageBoxButtons.OK, MessageBoxIcon.Information); Console.WriteLine("Winbond 2K Buffer Selected"); chkWB.Checked = false; } else if (!chkWB.Checked) // Don't uselessly spam the console { Console.WriteLine("Winbond 2K Buffer Deselected"); } // Don't do it twice if (!chkWB.Checked && chkWB4G.Checked) { updateWB(); } else if (!chkWB.Checked && !chkWB4G.Checked) { updateWB(); } } private void updateWB() { if (chkWB.Checked) patches[7] = "-r WB"; else if (chkWB4G.Checked) patches[7] = "-r WB4G"; else patches[7] = ""; updateCommand(); } private void chkBigffs_CheckedChanged(object sender, EventArgs e) { if (chkBigffs.Checked) Console.WriteLine("bigffs Selected"); else Console.WriteLine("bigffs Deselected"); } private void chkXdkBuild_CheckedChanged(object sender, EventArgs e) { checkWB(variables.boardtype); checkBigffs(variables.boardtype); if (chkXdkBuild.Checked) Console.WriteLine("XDKbuild Selected"); else Console.WriteLine("XDKbuild Deselected"); checkRgh3(variables.boardtype); } private void chkAudClamp_CheckedChanged(object sender, EventArgs e) { if (chkAudClamp.Checked) Console.WriteLine("Aud_Clamp Selected"); else Console.WriteLine("Aud_Clamp Deselected"); } private void chk0Fuse_CheckedChanged(object sender, EventArgs e) { if (chk0Fuse.Checked) Console.WriteLine("0 Fuse Selected"); else Console.WriteLine("0 Fuse Deselected"); } private void chkXLUsb_CheckedChanged(object sender, EventArgs e) { if (chkXLUsb.Checked) { Console.WriteLine("XL USB (BETA) Selected"); if (DialogResult.Cancel == MessageBox.Show("XL USB requires HDDs to be formatted via FATXplorer, normal Xbox 360 storage devices will no longer work", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)) { chkXLUsb.Checked = false; } } else Console.WriteLine("XL USB (BETA) Deselected"); } private void btnGetMB_Click(object sender, EventArgs e) { Getmb(); } private void btnXEUpdate_Click(object sender, EventArgs e) { ThreadStart starter = delegate { xe_update(); }; new Thread(starter).Start(); } private void btnRead_Click(object sender, EventArgs e) { if (File.Exists(Path.Combine(variables.outfolder, "consoleDump.bin"))) { MessageBox.Show("consoleDump.bin already exists"); return; } string arguments; if (!String.IsNullOrWhiteSpace(txtOffset.Text)) { arguments = "-rb " + "\"" + Path.Combine(variables.outfolder, "consoleDump.bin") + "\""; arguments += " " + txtOffset.Text; if (!String.IsNullOrWhiteSpace(txtLength.Text)) { arguments += " " + txtLength.Text; } } else { arguments = "-r " + "\"" + Path.Combine(variables.outfolder, "consoleDump.bin") + "\""; } if (chkShutdown.Checked) arguments += " -s"; if (chkReboot.Checked) arguments += " -reboot"; if (chkForceIP.Checked) arguments += " -ip " + txtIP2.Text; Console.WriteLine("Starting Read - please wait......"); ThreadStart starter = delegate { xe_client(arguments); }; new Thread(starter).Start(); } private void btnWrite_Click(object sender, EventArgs e) { string arguments; if (!String.IsNullOrWhiteSpace(txtOffset.Text)) { arguments = "-wb " + "\"" + variables.filename1 + "\""; arguments += " " + txtOffset.Text; if (!String.IsNullOrWhiteSpace(txtLength.Text)) { arguments += " " + txtLength.Text; } } else { arguments = "-w " + "\"" + variables.filename1 + "\""; } if (chkShutdown.Checked) arguments += " -s"; if (chkReboot.Checked) arguments += " -reboot"; if (chkForceIP.Checked) arguments += " -ip " + txtIP2.Text; Console.WriteLine("Starting Write - please wait......"); ThreadStart starter = delegate { xe_client(arguments); }; new Thread(starter).Start(); } private void btnErase_Click(object sender, EventArgs e) { string arguments = "-eb " + txtOffset.Text; if (chkShutdown.Checked) arguments += " -s"; if (chkReboot.Checked) arguments += " -reboot"; if (chkForceIP.Checked) arguments += " -ip " + txtIP2.Text; ThreadStart starter = delegate { xe_client(arguments); }; new Thread(starter).Start(); } private void btnPatches_Click(object sender, EventArgs e) { string arguments = "-p"; if (!String.IsNullOrWhiteSpace(variables.filename1)) { if (MessageBox.Show("Make sure that source file is a patch file.", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel) return; arguments += " \"" + variables.filename1 + "\""; } if (chkShutdown.Checked) arguments += " -s"; if (chkReboot.Checked) arguments += " -reboot"; if (chkForceIP.Checked) arguments += " -ip " + txtIP2.Text; ThreadStart starter = delegate { xe_client(arguments); }; new Thread(starter).Start(); } private void btnAvatar_Click(object sender, EventArgs e) { if (variables.debugme) Console.WriteLine(Path.Combine(variables.update_path, comboDash.Text + @"\$systemupdate")); if (Directory.Exists(Path.Combine(variables.update_path, comboDash.Text + @"\$systemupdate"))) { Console.WriteLine("Starting, please wait!"); string upPath = Path.Combine(variables.update_path, comboDash.Text, @"\$systemupdate"); //Path.Combine(upPath, @"\$systemupdate"); // Console.WriteLine(Path.Combine(variables.update_path, comboDash.Text + @"\$systemupdate")); ThreadStart starter = delegate { xe_compatibilityAvatar(Path.Combine(variables.update_path, (comboDash.Text)), "-e "); }; new Thread(starter).Start(); } else { FolderBrowserDialog fd = new FolderBrowserDialog(); if (fd.ShowDialog() == DialogResult.Cancel) return; Console.WriteLine("Starting, please wait!"); ThreadStart starter = delegate { xe_compatibilityAvatar(fd.SelectedPath, "-e "); }; new Thread(starter).Start(); } } private void btnComp_Click(object sender, EventArgs e) { FolderBrowserDialog fd = new FolderBrowserDialog(); if (fd.ShowDialog() == DialogResult.Cancel) return; ThreadStart starter = delegate { xe_compatibilityAvatar(fd.SelectedPath, "-c "); }; new Thread(starter).Start(); } private void chkForceIP_CheckedChanged(object sender, EventArgs e) { if (chkForceIP.Checked) { txtIP.Enabled = txtIP2.Enabled = chkForceIP2.Checked = true; txtIP.Text = txtIP2.Text = ""; Console.WriteLine("ForceIP Selected"); } else { txtIP.Enabled = txtIP2.Enabled = chkForceIP2.Checked = false; txtIP.Text = txtIP2.Text = "Autoscan LAN"; Console.WriteLine("ForceIP Deselected"); } } private void txtIP2_TextChanged(object sender, EventArgs e) { txtIP.Text = txtIP2.Text; } private void chkForceIP2_CheckedChanged(object sender, EventArgs e) { if (chkForceIP2.Checked) { txtIP.Enabled = txtIP2.Enabled = chkForceIP.Checked = true; txtIP.Text = txtIP2.Text = ""; } else { txtIP.Enabled = txtIP2.Enabled = chkForceIP.Checked = false; txtIP.Text = txtIP2.Text = "Autoscan LAN"; } } private void txtIP_TextChanged(object sender, EventArgs e) { txtIP2.Text = txtIP.Text; } private void XeBuildPanel_Load(object sender, EventArgs e) { chkCR4.Visible = false; chkSMCP.Visible = false; chkRgh3.Visible = false; Rgh3Label.Visible = false; Rgh3Label2.Visible = false; Rgh3Mhz.Visible = false; chkWB.Visible = false; chkWB4G.Enabled = false; chkXdkBuild.Visible = false; chkRJtag.Visible = false; chkAudClamp.Visible = false; chkBigffs.Enabled = false; chk0Fuse.Visible = false; setComboCB(); } private void chkNoWrite_CheckedChanged(object sender, EventArgs e) { if (chkNoWrite.Checked) Console.WriteLine("nowrite Selected"); else Console.WriteLine("nowrite Deselected"); } private void chkNoAva_CheckedChanged(object sender, EventArgs e) { if (chkNoAva.Checked) Console.WriteLine("noava Selected"); else Console.WriteLine("noava Deselected"); } private void chkClean_CheckedChanged(object sender, EventArgs e) { if (chkClean.Checked) Console.WriteLine("clean Selected"); else Console.WriteLine("clean Deselected"); } private void chkNoReeb_CheckedChanged(object sender, EventArgs e) { if (chkNoReeb.Checked) Console.WriteLine("noreeb Selected"); else Console.WriteLine("noreeb Deselected"); } private void chkShutdown_CheckedChanged(object sender, EventArgs e) { if (chkShutdown.Checked) Console.WriteLine("shutdown Selected"); else Console.WriteLine("shutdown Deselected"); } private void chkReboot_CheckedChanged(object sender, EventArgs e) { if (chkReboot.Checked) Console.WriteLine("reboot Selected"); else Console.WriteLine("reboot Deselected"); } private void chkxesettings_CheckedChanged(object sender, EventArgs e) { if (chkxesettings.Checked) Console.WriteLine("Use Edited Options Selected"); else Console.WriteLine("Use Edited Options Deselected"); } #endregion #region code void xe_update() { Classes.xebuild xe = new Classes.xebuild(); xe.Uloadvariables(variables.dashversion, (variables.hacktypes)variables.ttyp, patches, chkxesettings.Checked, chkNoWrite.Checked, chkNoAva.Checked, chkClean.Checked, chkNoReeb.Checked, checkDLPatches.Checked, chkLaunch.Checked); File.Delete(Path.Combine(variables.rootfolder, @"xebuild\data\" + "smc.bin")); try { string[] files = { "kv.bin", "smc.bin", "smc_config.bin", "fcrt.bin" }; foreach (string file in files) { if (File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\" + file))) { if (MessageBox.Show(file + " found. Delete it?\nUnless you put it there, delete it!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { File.Delete(Path.Combine(variables.rootfolder, @"xebuild\data\" + file)); } } } } catch (Exception ex) { if (variables.debugme) Console.WriteLine(ex.ToString()); } Classes.xebuild.XebuildError er = xe.createxebuild(); if (er == Classes.xebuild.XebuildError.none) { xe.xeExit += xe_xeUExit; xe.update(); } else if (er == Classes.xebuild.XebuildError.nodash) { MessageBox.Show("No Kernel Selected"); return; } else { MessageBox.Show("Something Bad Happened"); return; } } void xe_client(string arguments) { Classes.xebuild xe = new Classes.xebuild(); xe.client(arguments); } void xe_compatibilityAvatar(string path, string command) { Classes.xebuild xe = new Classes.xebuild(); string arguments = command + path + "\\"; if (chkShutdown.Checked) arguments += " -s"; if (chkReboot.Checked) arguments += " -reboot"; if (chkForceIP.Checked) arguments += " -ip " + txtIP2.Text; xe.client(arguments); } void add_dash() { addDash newdash = new addDash(); if (newdash.ShowDialog() == DialogResult.Cancel) { DeletedDash(); // Yes this is correct, it just refreshes the list return; } try { AddedDash(); } catch (Exception) { } } void del_dash() { Dashes.delDash deldash = new Dashes.delDash(); deldash.ShowDialog(); try { DeletedDash(); } catch (Exception) { } } public void createxebuild_v2(bool custom, Nand.PrivateN nand, bool fullDataClean) { Classes.xebuild xe = new Classes.xebuild(); xe.loadvariables(nand._cpukey, (variables.hacktypes)variables.ttyp, variables.dashversion, variables.ctyp, patches, nand, chkxesettings.Checked, checkDLPatches.Checked, chkLaunch.Checked, chkAudClamp.Checked, chkRJtag.Checked, chkCleanSMC.Checked, chkCR4.Checked, chkSMCP.Checked, chkRgh3.Checked, chkBigffs.Checked, chk0Fuse.Checked, chkXdkBuild.Checked, chkXLUsb.Checked, fullDataClean); string ini = (variables.launchpath + @"\" + variables.dashversion + @"\_" + variables.ttyp + ".ini"); if (!custom) { if (String.IsNullOrWhiteSpace(variables.filename1)) { loadFil(ref variables.filename1, true); if (String.IsNullOrWhiteSpace(variables.filename1)) { MessageBox.Show("No file was selected!", "Can't", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } if (!File.Exists(variables.filename1)) { MessageBox.Show("File is missing. Ensure it wasn't moved and app can access it.", "Can't", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (Path.GetExtension(variables.filename1) != ".bin") { MessageBox.Show("You must select a .bin file", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); return; } try { string[] files = { "kv.bin", "smc.bin", "smc_config.bin", "fcrt.bin" }; foreach (string file in files) { if (File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\" + file))) { if (MessageBox.Show(file + " found. Delete it?\nUnless you put it there, delete it!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { File.Delete(Path.Combine(variables.rootfolder, @"xebuild\data\" + file)); } } } } catch (Exception ex) { if (variables.debugme) Console.WriteLine(ex.ToString()); } if (!nand.cpukeyverification(nand._cpukey)) { Console.WriteLine("Wrong CPU Key"); return; } } else { string[] filesa = { "kv.bin", "smc.bin", "smc_config.bin" }; foreach (string file in filesa) { if (file == "smc.bin" && (chkCleanSMC.Checked || chkCR4.Checked || chkSMCP.Checked || rbtnJtag.Checked)) // Options that put in an SMC { // Skip because we put our own SMC in } else { if (!File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\" + file))) { MessageBox.Show(file + " is missing", "Can't", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } Regex objAlphaPattern = new Regex("[a-fA-F0-9]{32}$"); bool sts = objAlphaPattern.IsMatch(variables.cpkey); if ((variables.cpkey.Length == 32 && sts)) { if (variables.debugme) Console.WriteLine("Key verification"); long size = 0; if (Nand.Nand.cpukeyverification(Oper.openfile(Path.Combine(variables.rootfolder, @"xebuild\data\kv.bin"), ref size, 0), variables.cpkey)) { if (variables.debugme) Console.WriteLine("CPU Key is Correct"); if (Nand.Nand.getfcrtflag(File.ReadAllBytes(Path.Combine(variables.rootfolder, @"xebuild\data\kv.bin")), variables.cpkey)) { if (!File.Exists(Path.Combine(variables.rootfolder, @"xebuild\data\fcrt.bin"))) { MessageBox.Show("fcrt.bin is missing"); Process.Start(Path.Combine(variables.rootfolder, @"xebuild\data")); return; } } } else Console.WriteLine("Wrong CPU Key"); } string cba = "", cbb = ""; string[] files = parse_ini.parselabel(ini, variables.ctyp.Ini + "bl"); if (files.Length >= 2) { if (files[0].Contains("cb")) cba = files[0].Substring(files[0].IndexOf("_") + 1, files[0].IndexOf(".bin") - 4); if (files[1].Contains("cbb")) cbb = files[1].Substring(files[1].IndexOf("cbb_") + 4, files[1].IndexOf(".bin") - 4); } if (variables.changeldv == 0) { Forms.xeBuildOptions ldv = new Forms.xeBuildOptions(); ldv.enumeratecbs(cba, cbb); ldv.ShowDialog(); } } Start: switch (xe.createxebuild(custom)) { case Classes.xebuild.XebuildError.nocpukey: MessageBox.Show("CPU Key is Missing"); return; case Classes.xebuild.XebuildError.nodash: MessageBox.Show("No Kernel Selected"); return; case Classes.xebuild.XebuildError.noinis: MessageBox.Show("Ini's are Missing"); return; case Classes.xebuild.XebuildError.nobootloaders: Console.WriteLine("The specified console bootloader list ({0}) is missing from the ini ({1})", variables.ctyp.Ini + "bl", ini); Console.WriteLine("You can either add it manually or ask for it get added if its possible"); return; case Classes.xebuild.XebuildError.wrongcpukey: MessageBox.Show("Wrong CPU Key"); return; case Classes.xebuild.XebuildError.noconsole: variables.ctyp = callconsoletypes(ConsoleTypes.Selected.All); if (variables.ctyp.ID == -1) return; else { Console.WriteLine((variables.hacktypes)variables.ttyp); xe.loadvariables(nand._cpukey, (variables.hacktypes)variables.ttyp, variables.dashversion, variables.ctyp, patches, nand, chkxesettings.Checked, checkDLPatches.Checked, chkLaunch.Checked, chkAudClamp.Checked, chkRJtag.Checked, chkCleanSMC.Checked, chkCR4.Checked, chkSMCP.Checked, chkRgh3.Checked, chkBigffs.Checked, chk0Fuse.Checked, chkXdkBuild.Checked, chkXLUsb.Checked, fullDataClean); goto Start; } case Classes.xebuild.XebuildError.none: copyfiles(nand._cpukey); xe.xeExit += xe_xeExit; xe.build(); break; default: break; } } public void xe_xeExit(object sender, EventArgs e) { xeExitActual(); } public void xeExitActual() { variables.changeldv = 0; UpdateProgres(100); try { File.Copy(Path.Combine(variables.rootfolder, @"xebuild\options.ini"), Path.Combine(variables.rootfolder, @"xebuild\data\options.ini"), true); chkxesettings.Checked = false; File.Move(Path.Combine(variables.xefolder, variables.nandflash + ".log"), Path.Combine(variables.xefolder, variables.nandflash.Substring(0, variables.nandflash.IndexOf(".")) + "(" + DateTime.Now.ToString("ddMMyyyyHHmm") + ").bin.log")); } catch (Exception ex) { if (variables.debugme) Console.WriteLine(ex.ToString()); } try { if (File.Exists(Path.Combine(variables.rootfolder, @"build.log"))) File.Delete(Path.Combine(variables.rootfolder, @"build.log")); } catch { } if (variables.xefinished) { Console.WriteLine("Saved to {0}", variables.xefolder); Console.WriteLine("Image is Ready"); variables.filename1 = Path.Combine(variables.xefolder, variables.nandflash); updateSourc(variables.filename1); //Process.Start(variables.xefolder); } else { Console.WriteLine("Failed"); } try { delfiles(); } catch (Exception ex) { if (variables.debugme) Console.WriteLine(ex.ToString()); } if (variables.debugme) Console.WriteLine("Deleted Files Successfully"); variables.xefinished = false; } private void copyfiles(string cpukey) { string targetkey = System.IO.Path.Combine(variables.xePath, variables.cpukeypath); string targetnand = System.IO.Path.Combine(variables.xePath, variables.nanddump); File.WriteAllText(targetkey, cpukey); if (String.IsNullOrEmpty(variables.filename1)) return; // FileInfo fi = new FileInfo(variables.filename1); if (fi.Length == 0xE0400000) { if (MessageBox.Show("Copy all 4GB data?", "Copy", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { JRunner.Functions.Copy c = new JRunner.Functions.Copy(variables.filename1, targetnand); c.ShowDialog(); } else { try { FileStream fr = new FileStream(variables.filename1, FileMode.Open); FileStream fw = new FileStream(targetnand, FileMode.Create); int buffersize = 0x200; byte[] buffer = new byte[buffersize]; for (int i = 0; i < 0x3000000; i += buffersize) { fr.Read(buffer, 0, buffersize); fw.Write(buffer, 0, buffersize); } fr.Close(); fw.Close(); } catch (Exception ex) { if (variables.debugme) Console.WriteLine(ex.ToString()); } } } /**/ else /**/File.Copy(variables.filename1, targetnand, true); } private void delfiles() { if (File.Exists(variables.xePath + variables.nanddump)) { try { File.Delete(variables.xePath + variables.nanddump); if (variables.debugme) Console.WriteLine("Deleted {0}", variables.xePath + variables.nanddump); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } if (File.Exists(variables.xePath + variables.cpukeypath)) { try { File.Delete(variables.xePath + variables.cpukeypath); if (variables.debugme) Console.WriteLine("Deleted {0}", variables.xePath + variables.cpukeypath); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } if (File.Exists(variables.launchpath + @"\" + variables.dashversion + @"\launch.ini")) { try { File.Delete(variables.launchpath + @"\" + variables.dashversion + @"\launch.ini"); if (variables.debugme) Console.WriteLine("Deleted launch.ini"); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } if (File.Exists(Path.Combine(variables.xePath, "SMC.bin")) && (variables.copiedSMC || variables.fullDataClean)) // Only Delete SMCs it puts there { try { File.Delete(Path.Combine(variables.xePath, "SMC.bin")); if (variables.debugme) Console.WriteLine("Deleted SMC.bin"); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } if (File.Exists(Path.Combine(variables.xePath, "KV.bin")) && variables.fullDataClean) { try { File.Delete(Path.Combine(variables.xePath, "KV.bin")); if (variables.debugme) Console.WriteLine("Deleted KV.bin"); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } if (File.Exists(Path.Combine(variables.xePath, "fcrt.bin")) && variables.fullDataClean) { try { File.Delete(Path.Combine(variables.xePath, "fcrt.bin")); if (variables.debugme) Console.WriteLine("Deleted fcrt.bin"); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } if (File.Exists(Path.Combine(variables.xePath, "smc_config.bin")) && variables.fullDataClean) { try { File.Delete(Path.Combine(variables.xePath, "smc_config.bin")); if (variables.debugme) Console.WriteLine("Deleted KV.bin"); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } if (File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + @"\xam.xex")) && variables.copiedXLUsb) { try { File.Delete(Path.Combine(variables.update_path, comboDash.SelectedValue + @"\xam.xex")); if (variables.debugme) Console.WriteLine("Deleted XL USB xam.xex"); if (File.Exists(Path.Combine(variables.update_path, comboDash.SelectedValue + @"\xam.xex.tmp"))) { File.Move(Path.Combine(variables.update_path, comboDash.SelectedValue + @"\xam.xex.tmp"), Path.Combine(variables.update_path, comboDash.SelectedValue + @"\xam.xex")); } if (variables.debugme) Console.WriteLine("Restored non XL USB xam.xex"); string buildIni = Path.Combine(variables.update_path, comboDash.SelectedValue + @"\_" + variables.ttyp.ToString() + ".ini"); if (File.Exists(buildIni + ".tmp")) { File.Delete(buildIni); File.Move(buildIni + ".tmp", buildIni); } if (variables.debugme) Console.WriteLine("Restored non XL USB ini"); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); return; } } } consoles callconsoletypes(ConsoleTypes.Selected selec, bool twomb = false, bool full = false) { ConsoleTypes myNewForm = new ConsoleTypes(); myNewForm.sel = selec; myNewForm.twombread = twomb; myNewForm.sfulldump = full; myNewForm.ShowDialog(); if (myNewForm.DialogResult == DialogResult.Cancel) return (variables.ctypes[0]); if (myNewForm.heResult().ID == -1) return variables.ctypes[0]; variables.fulldump = myNewForm.fulldump(); variables.twombread = myNewForm.twombdump(); if (variables.debugme) Console.WriteLine("fulldump variable = {0}", variables.fulldump); setMBname(myNewForm.heResult().Text); return (myNewForm.heResult()); } public void xe_xeUExit(object sender, EventArgs e) { variables.changeldv = 0; UpdateProgres(100); if (variables.xefinished) { Console.WriteLine("Saved to {0}", variables.xefolder); Console.WriteLine("Image is Ready"); variables.filename1 = Path.Combine(variables.xefolder, variables.nandflash); updateSourc(variables.filename1); //Process.Start(variables.xefolder); } else { Console.WriteLine("Failed"); } variables.xefinished = false; } #endregion private void btnInfo_Click(object sender, EventArgs e) { ThreadStart starter = delegate { xe_compatibilityAvatar(variables.outfolder, "-i "); }; new Thread(starter).Start(); } private void updateCommand(bool wait = false) { if (wait) Thread.Sleep(100); string c = ""; c = "-t " + variables.ttyp; c += " -c " + variables.ctyp.XeBuild; foreach (String patch in patches) { c += " " + patch; } c += " -f " + variables.dashversion; c += " -d data"; c += " \"" + variables.xefolder + "\\" + variables.nandflash + "\" "; RegexOptions options = RegexOptions.None; Regex regex = new Regex(@"[ ]{2,}", options); c = regex.Replace(c, @" "); try { txtCommand.Text = c; } catch (Exception) { } } private void txtMBname_TextChanged(object sender, EventArgs e) { new Thread(new ThreadStart(delegate { updateCommand(true); })).Start(); new Thread(new ThreadStart(delegate { setComboCB(false, true); })).Start(); } private void setComboCB(bool erase = false, bool wait = false) { if (erase) { patches[7] = ""; return; } if (wait) Thread.Sleep(100); try { comboCB.Items.Clear(); if (variables.dashversion != 0) { string ini = (variables.launchpath + @"\" + variables.dashversion + @"\_retail.ini"); List<string> labels = parse_ini.getlabels(ini); foreach (string s in labels) { if (!s.Contains("bl")) continue; if (variables.ctyp.ID == -1) { if (s.Contains("_")) comboCB.Items.Add(new CB(s.Substring(s.IndexOf("_") + 1), true)); else { comboCB.Items.Add(new CB(Nand.ntable.getCBFromDash(getConsoleFromIni(s.Substring(0, s.IndexOf("bl"))), variables.dashversion), false)); } } else { if (s.Contains(variables.ctyp.Ini)) { if (s.Contains("_")) comboCB.Items.Add(new CB(s.Substring(s.IndexOf("_") + 1), true)); else comboCB.Items.Add(new CB(Nand.ntable.getCBFromDash(getConsoleFromIni(variables.ctyp.Ini), variables.dashversion), false)); } } } if (comboCB.Items.Count > 0) comboCB.SelectedIndex = 0; } } catch (Exception) { } } private void comboCB_SelectedIndexChanged(object sender, EventArgs e) { if (comboCB.Items.Count > 0) { CB c = (CB)comboCB.SelectedItem; if (c.Patch) patches[7] = "-r " + c.Version; else patches[7] = ""; updateCommand(); } } private consoles getConsoleFromIni(string ini) { foreach (consoles c in variables.ctypes) { if (c.ID == -1) continue; if (ini == c.Ini) return c; } return variables.ctypes[0]; } class CB { public string Version { get; set; } public bool Patch { get; set; } public CB(string v, bool p) { Version = v; Patch = p; } public CB(int v, bool p) { Version = v.ToString(); Patch = p; } public override string ToString() { return Version; } } } }
38.662901
252
0.511402
[ "MIT" ]
Octal450/J-Runner-with-Extras
J-Runner/Panels/XeBuildPanel.cs
65,033
C#
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vulcan.Wpf.Core { /// <summary> /// Imports View subclasses and distributes them. /// This class is imported and used in FrameworkApp. /// </summary> [Export(typeof(ViewLocator))] public class ViewLocator : DynamicObject, IPartImportsSatisfiedNotification { [ImportMany] private IEnumerable<Lazy<View, IViewMetadata>> views { get; set; } [Import(typeof(ILogger), AllowDefault = true)] private ILogger logger; public override bool TryGetMember(GetMemberBinder binder, out object result) { string name = binder.Name; var lazy = views?.FirstOrDefault(v => v.Metadata.Alias == name); result = lazy?.Value; // Error handling if (null == views) logger?.Log("views is null at TryGetMember", this.GetType(), LogCategory.Error, LogPriority.High); if (null == lazy) logger?.Log($"View not found: {name}", this.GetType(), LogCategory.Warning, LogPriority.High); return null != result; } public void OnImportsSatisfied() { logger?.Log("Composition complete", this.GetType()); } } }
30.586957
114
0.624023
[ "MIT" ]
Vanlalhriata/Vulcan.Wpf
Vulcan.Wpf/Vulcan.Wpf.Core/View/ViewLocator.cs
1,409
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type GroupConversationsCollectionResponse. /// </summary> [DataContract] public class GroupConversationsCollectionResponse { /// <summary> /// Gets or sets the <see cref="IGroupConversationsCollectionPage"/> value. /// </summary> [DataMember(Name = "value", EmitDefaultValue = false, IsRequired = false)] public IGroupConversationsCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
37.5625
153
0.575707
[ "MIT" ]
MIchaelMainer/GraphAPI
src/Microsoft.Graph/Requests/Generated/GroupConversationsCollectionResponse.cs
1,202
C#
using Newtonsoft.Json; namespace Bt.IPay.Net.Responses.GetOrderStatusExtended { public class BindingInfo { /// <summary> /// Numărul clientului (ID) în sistemul comerciantului, transferat în timpul înregistrării comenzii. /// Disponibil doar pentru comercianții cu drepturi corespunzătoare. /// </summary> [JsonProperty("clientId")] public string ClientId { get; set; } /// <summary> /// Identificatorul binding creat în timpul plății comenzii sau utilizat pentru plată. /// Disponibil doar pentru comercianții cu drepturi corespunzătoare. /// </summary> [JsonProperty("bindingId")] public string BindingId { get; set; } } }
35
108
0.651701
[ "Apache-2.0" ]
sibies/Bt.IPay.Net
src/Bt.IPay.Net/Responses/GetOrderStatusExtended/BindingInfo.cs
750
C#
namespace SKIT.FlurlHttpClient.Wechat.Work.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/agent/set_workbench_data 接口的响应。</para> /// </summary> public class CgibinAgentSetWorkbenchDataResponse : WechatWorkResponse { } }
25
73
0.68
[ "MIT" ]
OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Work/Models/CgibinAgent/Workbench/CgibinAgentSetWorkbenchDataResponse.cs
268
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Apollo.Domain.Entity; using Apollo.Persistence.FluentEntity; using Apollo.Persistence.FluentEntity.Interfaces.Shared; using Apollo.Persistence.Util; using Apollo.Repository.Interfaces; using Apollo.Util; using Microsoft.Extensions.Configuration; namespace Apollo.Repository.Test { public class RepositoryHelper { public IFluentEntityFrom FluentEntity { get; } public IRepositoryFactory RepositoryFactory { get; } public ISet<EntityType> FillTypes { get; set; } public IEnumerable<Movie> Movies { get; private set; } public IEnumerable<MovieActor> MovieActors { get; private set; } public IEnumerable<Actor> Actors { get; private set; } public IEnumerable<CinemaHall> CinemaHalls { get; private set; } public IEnumerable<Row> Rows { get; private set; } public IEnumerable<RowCategory> RowCategories { get; private set; } public IEnumerable<User> Users { get; private set; } public IEnumerable<Role> Roles { get; private set; } public IEnumerable<Address> Addresses { get; private set; } public IEnumerable<Seat> Seats { get; private set; } public IEnumerable<SeatReservation> SeatReservations { get; private set; } public IEnumerable<Schedule> Schedules { get; private set; } public IEnumerable<Genre> Genres { get; private set; } public IEnumerable<City> Cities { get; private set; } public IEnumerable<Reservation> Reservations { get; private set; } public RepositoryHelper() { ConfigurationHelper.ConfigurationRoot = new ConfigurationBuilder() .AddJsonFile("testsettings.json") .Build(); var appSettings = ConfigurationHelper.GetValues("Apollo_Test"); var connectionFactory = new ConnectionFactory(appSettings[0]); FluentEntity = EntityManagerFactory.CreateEntityManager(connectionFactory).FluentEntity(); RepositoryFactory = new RepositoryFactory(connectionFactory); FillTypes = new HashSet<EntityType>(); } public async Task TearDown() { await FluentEntity.Delete<SeatReservation>().ExecuteAsync(); await FluentEntity.Delete<Reservation>().ExecuteAsync(); await FluentEntity.Delete<Ticket>().ExecuteAsync(); await FluentEntity.Delete<Schedule>().ExecuteAsync(); await FluentEntity.Delete<Seat>().ExecuteAsync(); await FluentEntity.Delete<Row>().ExecuteAsync(); await FluentEntity.Delete<RowCategory>().ExecuteAsync(); await FluentEntity.Delete<CinemaHall>().ExecuteAsync(); await FluentEntity.Delete<MovieActor>().ExecuteAsync(); await FluentEntity.Delete<Actor>().ExecuteAsync(); await FluentEntity.Delete<Movie>().ExecuteAsync(); await FluentEntity.Delete<Genre>().ExecuteAsync(); await FluentEntity.Delete<User>().ExecuteAsync(); await FluentEntity.Delete<Address>().ExecuteAsync(); await FluentEntity.Delete<City>().ExecuteAsync(); await FluentEntity.Delete<Role>().ExecuteAsync(); } public async Task SeedDatabase() { if (EntityDependsOnRole()) { Roles = CreateRoles(); await FluentEntity.InsertInto(Roles).ExecuteAsync(); } if (EntityDependsOnCity()) { Cities = CreateCities(); await FluentEntity.InsertInto(Cities).ExecuteAsync(); } if (EntityDependsOnAddress()) { Addresses = CreateAddresses(); await FluentEntity.InsertInto(Addresses).ExecuteAsync(); } if (EntityDependsOnUser()) { Users = CreateUsers(); await FluentEntity.InsertInto(Users).ExecuteAsync(); } if (EntityDependsOnGenre()) { Genres = CreateGenres(); await FluentEntity.InsertInto(Genres).ExecuteAsync(); } if (EntityDependsOnMovie()) { Movies = CreateMovies(); await FluentEntity.InsertInto(Movies).ExecuteAsync(); } if (EntityDependsOnActor()) { Actors = CreateActors(); await FluentEntity.InsertInto(Actors).ExecuteAsync(); } if (EntityDependsOnMovieActor()) { MovieActors = CreateMovieActors(); await FluentEntity.InsertInto(MovieActors).ExecuteAsync(); } if (EntityDependsOnCinemaHall()) { CinemaHalls = CreateCinemaHalls(); await FluentEntity.InsertInto(CinemaHalls).ExecuteAsync(); } if (EntityDependsOnRowCategory()) { RowCategories = CreateRowCategories(); await FluentEntity.InsertInto(RowCategories).ExecuteAsync(); } if (EntityDependsOnRow()) { Rows = CreateRows(); await FluentEntity.InsertInto(Rows).ExecuteAsync(); } if (EntityDependsOnSeat()) { Seats = CreateSeats(); await FluentEntity.InsertInto(Seats).ExecuteAsync(); } if (EntityDependsOnSchedule()) { Schedules = CreateSchedules(); await FluentEntity.InsertInto(Schedules).ExecuteAsync(); } if (EntityDependsOnReservation()) { Reservations = CreateReservations(); await FluentEntity.InsertInto(Reservations).ExecuteAsync(); } if (EntityDependsOnSeatReservation()) { SeatReservations = CreateSeatReservations(); await FluentEntity.InsertInto(SeatReservations).ExecuteAsync(); } } private bool EntityDependsOnSeatReservation() { return FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnReservation() { return FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnSchedule() { return FillTypes.Contains(EntityType.Schedule) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnSeat() { return FillTypes.Contains(EntityType.Seat) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnRow() { return FillTypes.Contains(EntityType.Row) || FillTypes.Contains(EntityType.Seat) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnRowCategory() { return FillTypes.Contains(EntityType.RowCategory) || FillTypes.Contains(EntityType.Row) || FillTypes.Contains(EntityType.Seat) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnCinemaHall() { return FillTypes.Contains(EntityType.CinemaHall) || FillTypes.Contains(EntityType.Row) || FillTypes.Contains(EntityType.Seat) || FillTypes.Contains(EntityType.Schedule) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnMovieActor() { return FillTypes.Contains(EntityType.MovieActor); } private bool EntityDependsOnActor() { return FillTypes.Contains(EntityType.Actor) || FillTypes.Contains(EntityType.MovieActor); } private bool EntityDependsOnMovie() { return FillTypes.Contains(EntityType.Movie) || FillTypes.Contains(EntityType.MovieActor) || FillTypes.Contains(EntityType.Schedule) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnGenre() { return FillTypes.Contains(EntityType.Genre) || FillTypes.Contains(EntityType.Movie) || FillTypes.Contains(EntityType.MovieActor) || FillTypes.Contains(EntityType.Schedule) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnUser() { return FillTypes.Contains(EntityType.User) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnAddress() { return FillTypes.Contains(EntityType.Address) || FillTypes.Contains(EntityType.User) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnCity() { return FillTypes.Contains(EntityType.City) || FillTypes.Contains(EntityType.Address) || FillTypes.Contains(EntityType.User) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private bool EntityDependsOnRole() { return FillTypes.Contains(EntityType.Role) || FillTypes.Contains(EntityType.City) || FillTypes.Contains(EntityType.Address) || FillTypes.Contains(EntityType.User) || FillTypes.Contains(EntityType.Reservation) || FillTypes.Contains(EntityType.SeatReservation); } private static IEnumerable<Reservation> CreateReservations() { return new List<Reservation> { new Reservation {Id = 1L, ScheduleId = 1L, UserId = 1000L} }; } private static IEnumerable<SeatReservation> CreateSeatReservations() { return new List<SeatReservation> { new SeatReservation {Id = 1L, ReservationId = 1L, SeatId = 1L}, new SeatReservation {Id = 2L, ReservationId = 1L, SeatId = 2L}, new SeatReservation {Id = 3L, ReservationId = 1L, SeatId = 3L}, }; } private static IEnumerable<Genre> CreateGenres() { return new List<Genre> { new Genre {Id = 1L, Name = "Horror"}, new Genre {Id = 2L, Name = "Romance"}, new Genre {Id = 3L, Name = "Action"}, new Genre {Id = 4L, Name = "Comedy"}, new Genre {Id = 5L, Name = "Sci-Fi"}, new Genre {Id = 6L, Name = "Action-Adventure"}, new Genre {Id = 7L, Name = "Fantasy"}, new Genre {Id = 8L, Name = "Splatter"} }; } private static IEnumerable<Actor> CreateActors() { return new List<Actor> { new Actor {Id = 1L, LastName = "Jolie", FirstName = "Angelina"}, new Actor {Id = 2L, LastName = "Pitt", FirstName = "Brad"}, new Actor {Id = 3L, LastName = "Cloney", FirstName = "George"}, new Actor {Id = 4L, LastName = "Diesel", FirstName = "Vin"}, new Actor {Id = 5L, LastName = "Depp", FirstName = "Jhonny"}, new Actor {Id = 6L, LastName = "Brosnan", FirstName = "Pierce"} }; } private static IEnumerable<MovieActor> CreateMovieActors() { return new List<MovieActor> { new MovieActor{Id = 1L, ActorId = 1L, MovieId = 1L}, new MovieActor{Id = 2L, ActorId = 2L, MovieId = 1L}, new MovieActor{Id = 3L, ActorId = 3L, MovieId = 1L}, new MovieActor{Id = 4L, ActorId = 4L, MovieId = 1L}, new MovieActor{Id = 5L, ActorId = 5L, MovieId = 1L}, new MovieActor{Id = 6L, ActorId = 6L, MovieId = 2L}, new MovieActor{Id = 7L, ActorId = 5L, MovieId = 3L}, }; } private static IEnumerable<Movie> CreateMovies() { return new List<Movie> { new Movie{Id = 1L, Duration = 1200, Description = "Pretty good movie...", GenreId = 3L, Title = "Salt", Trailer = "youtube.com/salt", Image= new byte[5], Rating = 1}, new Movie{Id = 2L, Duration = 1337, Description = "A secret agent saves the world...", GenreId = 3L, Title = "007-Golden Eye", Trailer = "youtube.com/james007" , Image= new byte[5], Rating = 3}, new Movie{Id = 3L, Duration = 4242, Description = "Something with ships in the caribbean...", GenreId = 3L, Title = "Pirates of the Caribbean", Trailer = "youtube.com/potc" , Image= new byte[5], Rating = 4}, new Movie{Id = 4L, Duration = 9120, Description = "Dummy Movie", GenreId = 3L, Title = "Dummy Title", Trailer = "dummy.com" , Image= new byte[5], Rating = 5}, }; } private static IEnumerable<Seat> CreateSeats() { return new List<Seat> { new Seat {Id = 1L, Number = 1, LayoutColumn = 0, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 2L , Number = 2, LayoutColumn = 1, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 3L, Number = 3, LayoutColumn = 2, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 4L, Number = 4, LayoutColumn = 3, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 5L, Number = 5, LayoutColumn = 4, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 6L, Number = 6, LayoutColumn = 5, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 7L, Number = 7, LayoutColumn = 6, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 8L, Number = 8, LayoutColumn = 7, LayoutRow = 0, Locked = false, RowId = 1L}, new Seat {Id = 9L, Number = 9, LayoutColumn = 0, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 10L , Number = 10, LayoutColumn = 1, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 11L, Number = 11, LayoutColumn = 2, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 12L, Number = 12, LayoutColumn = 3, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 13L, Number = 13, LayoutColumn = 4, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 14L, Number = 14, LayoutColumn = 5, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 15L, Number = 15, LayoutColumn = 6, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 16L, Number = 16, LayoutColumn = 7, LayoutRow = 1, Locked = false, RowId = 2L}, new Seat {Id = 17L, Number = 20, LayoutColumn = 0, LayoutRow = 2, Locked = false, RowId = 3L}, new Seat {Id = 18L , Number = 21, LayoutColumn = 1, LayoutRow = 2, Locked = false, RowId = 3L}, new Seat {Id = 19L, Number = 22, LayoutColumn = 2, LayoutRow = 2, Locked = false, RowId = 3L}, new Seat {Id = 20L, Number = 23, LayoutColumn = 3, LayoutRow = 2, Locked = true, RowId = 3L}, new Seat {Id = 21L, Number = 24, LayoutColumn = 4, LayoutRow = 2, Locked = false, RowId = 3L}, new Seat {Id = 22L, Number = 25, LayoutColumn = 5, LayoutRow = 2, Locked = true, RowId = 3L}, new Seat {Id = 23L, Number = 26, LayoutColumn = 6, LayoutRow = 2, Locked = false, RowId = 3L}, new Seat {Id = 24L, Number = 27, LayoutColumn = 7, LayoutRow = 2, Locked = true, RowId = 3L}, }; } private static IEnumerable<Row> CreateRows() { return new List<Row> { new Row { Id = 1L, Number = 1, CategoryId = 1L, CinemaHallId = 1L }, new Row { Id = 2L, Number = 2, CategoryId = 2L, CinemaHallId = 1L }, new Row { Id = 3L, Number = 3, CategoryId = 4L, CinemaHallId = 1L }, }; } private static IEnumerable<RowCategory> CreateRowCategories() { return new List<RowCategory> { new RowCategory {Id = 1L, Name = "Silver", PriceFactor = 1.0}, new RowCategory {Id = 2L, Name = "Gold", PriceFactor = 1.25}, new RowCategory {Id = 3L, Name = "Platinum", PriceFactor = 1.75}, new RowCategory {Id = 4L, Name = "Diamond", PriceFactor = 2.0}, }; } private static IEnumerable<CinemaHall> CreateCinemaHalls() { return new List<CinemaHall> { new CinemaHall {Id = 1L, Label = "Apollo 1", SizeRow = 3, SizeColumn = 8}, new CinemaHall {Id = 2L, Label = "Apollo 2", SizeRow = 5, SizeColumn = 6} }; } private static IEnumerable<Role> CreateRoles() { return new List<Role> { new Role {Id = 1L, Label = "Role 1", MaxReservations = 10}, new Role {Id = 2L, Label = "Role 2", MaxReservations = 20}, new Role {Id = 3L, Label = "Role 3", MaxReservations = 30}, new Role {Id = 4L, Label = "Role 4", MaxReservations = 40}, new Role {Id = 5L, Label = "Role 5", MaxReservations = 50} }; } private static IEnumerable<City> CreateCities() { return new List<City> { new City {Id = 10L, PostalCode = "1111", Name = "City 1"}, new City {Id = 20L, PostalCode = "2222", Name = "City 2"}, new City {Id = 30L, PostalCode = "3333", Name = "City 3"}, new City {Id = 40L, PostalCode = "4444", Name = "City 4"}, new City {Id = 50L, PostalCode = "5555", Name = "City 5"} }; } private static IEnumerable<Address> CreateAddresses() { return new List<Address> { new Address {Id = 100L, CityId = 10L, Street = "Street 1", Number = 10}, new Address {Id = 200L, CityId = 10L, Street = "Street 2", Number = 20}, new Address {Id = 300L, CityId = 20L, Street = "Street 3", Number = 30}, new Address {Id = 400L, CityId = 20L, Street = "Street 4", Number = 40}, new Address {Id = 500L, CityId = 30L, Street = "Street 5", Number = 50}, new Address {Id = 600L, CityId = 30L, Street = "Street 6", Number = 60}, new Address {Id = 700L, CityId = 40L, Street = "Street 7", Number = 70}, new Address {Id = 800L, CityId = 40L, Street = "Street 8", Number = 80}, new Address {Id = 900L, CityId = 50L, Street = "Street 9", Number = 90}, new Address {Id = 1000L, CityId = 50L, Street = "Street 10", Number = 100} }; } private static IEnumerable<User> CreateUsers() { return new List<User> { new User {Id = 1000L, Uuid = "724f75e6-71ce-45b0-8bb6-d3908cee727e", AddressId = 100L, Email = "mail_1@fh-ooe.at", FirstName = "First 1", LastName = "Last 1", Phone = "0664000000", RoleId = 1L}, new User {Id = 2000L, Uuid = "f7f57b3d-890f-4ba8-9c86-278c68ec1dad", AddressId = 200L, Email = "mail_2@fh-ooe.at", FirstName = "First 2", LastName = "Last 2", Phone = "0664111111", RoleId = 1L}, new User {Id = 3000L, Uuid = "b008704f-4bab-4f89-858b-dcd0c4a7ada1", AddressId = 300L, Email = "mail_3@fh-ooe.at", FirstName = "First 3", LastName = "Last 3", Phone = "0664222222", RoleId = 2L}, new User {Id = 4000L, Uuid = "26919ccb-a9ef-4efa-b92f-f70cac055e4c", AddressId = 400L, Email = "mail_4@fh-ooe.at", FirstName = "First 4", LastName = "Last 4", Phone = "0664333333", RoleId = 2L}, new User {Id = 5000L, Uuid = "92679fae-a543-49e9-bac6-3c34e176b205", AddressId = 500L, Email = "mail_5@fh-ooe.at", FirstName = "First 5", LastName = "Last 5", Phone = "0664444444", RoleId = 3L}, new User {Id = 6000L, Uuid = "87c629e3-053e-4a8f-a039-3953806d1bb8", AddressId = 600L, Email = "mail_6@fh-ooe.at", FirstName = "First 6", LastName = "Last 6", Phone = "0664555555", RoleId = 3L}, new User {Id = 7000L, Uuid = "f5476050-6bf5-488c-afa9-1197fd94e8e6", AddressId = 700L, Email = "mail_7@fh-ooe.at", FirstName = "First 7", LastName = "Last 7", Phone = "0664666666", RoleId = 4L}, new User {Id = 8000L, Uuid = "273cbeec-348e-4914-9160-5daddd194fdb", AddressId = 800L, Email = "mail_8@fh-ooe.at", FirstName = "First 8", LastName = "Last 8", Phone = "0664777777", RoleId = 4L}, new User {Id = 9000L, Uuid = "9e12e422-87cb-4168-b0d7-29cc7bd80cd7", AddressId = 900L, Email = "mail_9@fh-ooe.at", FirstName = "First 9", LastName = "Last 9", Phone = "0664888888", RoleId = 5L}, new User {Id = 10000L, Uuid = "32942e7f-da87-456e-ad3b-26afa7607880", AddressId = 1000L, Email = "mail_10@fh-ooe.at", FirstName = "First 10", LastName = "Last 10", Phone = "0664999999", RoleId = 5L} }; } private static IEnumerable<Schedule> CreateSchedules() { var startTime = new DateTime(2020, 11, 4, 20, 15, 00); var secondStartTime = new DateTime(2020, 11, 5, 19, 35, 00); var thirdStartTime = new DateTime(2020, 11, 4, 23, 15, 00); return new List<Schedule> { new Schedule {Id = 1L,StartTime = startTime, CinemaHallId = 1L, MovieId = 1L, Price = 12.50M}, new Schedule {Id = 2L,StartTime = startTime, CinemaHallId = 2L, MovieId = 1L, Price = 12.50M}, new Schedule {Id = 3L,StartTime = secondStartTime, CinemaHallId = 1L, MovieId = 1L, Price = 12.50M}, new Schedule {Id = 4L,StartTime = secondStartTime, CinemaHallId = 2L, MovieId = 1L, Price = 12.50M}, new Schedule {Id = 5L,StartTime = thirdStartTime, CinemaHallId = 1L, MovieId = 1L, Price = 12.50M}, new Schedule {Id = 6L, StartTime = thirdStartTime, CinemaHallId = 2L, MovieId = 1L, Price = 12.50M} }; } } }
50.606264
280
0.57398
[ "MIT" ]
EnvyIT/apollo
Apollo/Apollo.Repository.Test/RepositoryHelper.cs
22,623
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type AndroidForWorkScepCertificateProfileManagedDeviceCertificateStatesCollectionResponse. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class AndroidForWorkScepCertificateProfileManagedDeviceCertificateStatesCollectionResponse { /// <summary> /// Gets or sets the <see cref="IAndroidForWorkScepCertificateProfileManagedDeviceCertificateStatesCollectionPage"/> value. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)] public IAndroidForWorkScepCertificateProfileManagedDeviceCertificateStatesCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
45.911765
153
0.660474
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/AndroidForWorkScepCertificateProfileManagedDeviceCertificateStatesCollectionResponse.cs
1,561
C#
namespace Coimbra.Model { /// <summary> /// An ordered string. /// </summary> public class OrderedString { /// <summary> /// Initializes a new instance of the <see cref="OrderedString"/> class. /// </summary> /// <param name="position">Position this string should be ordered at.</param> /// <param name="value">String value of item.</param> public OrderedString(int position, string value) { this.Position = position; this.Value = value; } /// <summary> /// Gets position. /// </summary> public int Position { get; } /// <summary> /// Gets value. /// </summary> public string Value { get; } } }
25.766667
85
0.514877
[ "MIT" ]
EnableIrelandAT/Coimbra
ProjectCoimbra.UWP/Project.Coimbra.Model/OrderedString.cs
773
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using System.Linq; using System.Text; using Elastic.Transport; using FluentAssertions; using Nest; using Tests.Configuration; using Tests.Core.Client; using Tests.Core.Extensions; using Tests.Core.ManagedElasticsearch.Clusters; using Tests.Domain; using Tests.Framework.EndpointTests; using Tests.Framework.EndpointTests.TestState; using static Nest.Infer; namespace Tests.Indices.MappingManagement.GetMapping { public class GetMappingApiTests : ApiIntegrationTestBase<ReadOnlyCluster, GetMappingResponse, IGetMappingRequest, GetMappingDescriptor<Project>, GetMappingRequest> { public GetMappingApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override Func<GetMappingDescriptor<Project>, IGetMappingRequest> Fluent => d => d .IgnoreUnavailable(); protected override HttpMethod HttpMethod => HttpMethod.GET; protected override GetMappingRequest Initializer => new GetMappingRequest(Index<Project>()) { IgnoreUnavailable = true }; protected override string UrlPath => "/project/_mapping?ignore_unavailable=true"; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.Indices.GetMapping(f), (client, f) => client.Indices.GetMappingAsync(f), (client, r) => client.Indices.GetMapping(r), (client, r) => client.Indices.GetMappingAsync(r) ); protected override void ExpectResponse(GetMappingResponse response) { response.ShouldBeValid(); /** For backwards compatible reasons you can still ask per type mappings, this is obsolete and will be removed in 8.0 **/ #pragma warning disable 618 response.Indices["project"]["_doc"].Properties.Should().NotBeEmpty(); response.Indices[Index<Project>()].Mappings.Properties.Should().NotBeEmpty(); response.Indices[Index<Project>()]["_doc"].Properties.Should().NotBeEmpty(); #pragma warning restore 618 var mappings = response.Indices[Index<Project>()].Mappings; var properties = mappings.Properties; var leadDev = properties[Property<Project>(p => p.LeadDeveloper)]; leadDev.Should().NotBeNull(); var props = response.Indices["x"]?.Mappings.Properties; props.Should().BeNull(); //hide AssertExtensionMethods(response); //hide AssertVisitedProperties(response); } //hide private static void AssertExtensionMethods(GetMappingResponse response) { /** The `GetMappingFor` extension method can be used to get a type mapping easily and safely */ response.GetMappingFor<Project>().Should().NotBeNull(); response.GetMappingFor(typeof(Project)).Should().NotBeNull(); } //hide private static void AssertVisitedProperties(GetMappingResponse response) { var visitor = new TestVisitor(); var b = TestClient.Configuration.Random.SourceSerializer; var supportsFlattenedType = TestConfiguration.Instance.InRange(">=7.3.0"); var supportsConstantKeyword = TestConfiguration.Instance.InRange(">=7.7.0"); var keywordCount = b ? 19 : 18; if (!supportsConstantKeyword) keywordCount++; response.Accept(visitor); visitor.CountsShouldContainKeyAndCountBe("type", 1); visitor.CountsShouldContainKeyAndCountBe("text", b ? 18 : 17); visitor.CountsShouldContainKeyAndCountBe("keyword", keywordCount); visitor.CountsShouldContainKeyAndCountBe("object", supportsFlattenedType ? 8 : 9); visitor.CountsShouldContainKeyAndCountBe("number", 9); visitor.CountsShouldContainKeyAndCountBe("ip", 2); visitor.CountsShouldContainKeyAndCountBe("geo_point", 3); visitor.CountsShouldContainKeyAndCountBe("date", 4); visitor.CountsShouldContainKeyAndCountBe("join", 1); visitor.CountsShouldContainKeyAndCountBe("completion", 2); visitor.CountsShouldContainKeyAndCountBe("date_range", 1); visitor.CountsShouldContainKeyAndCountBe("double_range", 1); visitor.CountsShouldContainKeyAndCountBe("float_range", 1); visitor.CountsShouldContainKeyAndCountBe("integer_range", 1); visitor.CountsShouldContainKeyAndCountBe("long_range", 1); visitor.CountsShouldContainKeyAndCountBe("ip_range", 1); visitor.CountsShouldContainKeyAndCountBe("nested", 1); visitor.CountsShouldContainKeyAndCountBe("rank_feature", 1); if (supportsFlattenedType) visitor.CountsShouldContainKeyAndCountBe("flattened", 1); if (supportsConstantKeyword) visitor.CountsShouldContainKeyAndCountBe("constant_keyword", 1); } } public class GetMappingNonExistentIndexApiTests : ApiIntegrationTestBase<ReadOnlyCluster, GetMappingResponse, IGetMappingRequest, GetMappingDescriptor<Project>, GetMappingRequest> { private readonly string _nonExistentIndex = "non-existent-index"; public GetMappingNonExistentIndexApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => false; protected override int ExpectStatusCode => 404; protected override Func<GetMappingDescriptor<Project>, IGetMappingRequest> Fluent => d => d.Index(_nonExistentIndex); protected override HttpMethod HttpMethod => HttpMethod.GET; protected override GetMappingRequest Initializer => new GetMappingRequest(_nonExistentIndex); protected override string UrlPath => $"/{_nonExistentIndex}/_mapping"; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.Indices.GetMapping(f), (client, f) => client.Indices.GetMappingAsync(f), (client, r) => client.Indices.GetMapping(r), (client, r) => client.Indices.GetMappingAsync(r) ); protected override void ExpectResponse(GetMappingResponse response) { response.Indices.Should().BeEmpty(); response.ServerError.Should().NotBeNull(); } } internal class TestVisitor : IMappingVisitor { public TestVisitor() => Counts = new Dictionary<string, int>(); public Dictionary<string, int> Counts { get; } public int Depth { get; set; } public void Visit(IDateProperty mapping) => Increment("date"); public void Visit(IDateNanosProperty mapping) => Increment("date_nanos"); public void Visit(IBinaryProperty mapping) => Increment("binary"); public void Visit(INestedProperty mapping) => Increment("nested"); public void Visit(IGeoPointProperty mapping) => Increment("geo_point"); public void Visit(ICompletionProperty mapping) => Increment("completion"); public void Visit(ITokenCountProperty mapping) => Increment("token_count"); public void Visit(IPercolatorProperty property) => Increment("percolator"); public void Visit(IIntegerRangeProperty property) => Increment("integer_range"); public void Visit(IFloatRangeProperty property) => Increment("float_range"); public void Visit(ILongRangeProperty property) => Increment("long_range"); public void Visit(IDoubleRangeProperty property) => Increment("double_range"); public void Visit(IDateRangeProperty property) => Increment("date_range"); public void Visit(IIpRangeProperty property) => Increment("ip_range"); public void Visit(IJoinProperty property) => Increment("join"); public void Visit(IMurmur3HashProperty mapping) => Increment("murmur3"); public void Visit(INumberProperty mapping) => Increment("number"); public void Visit(IGeoShapeProperty mapping) => Increment("geo_shape"); public void Visit(IShapeProperty mapping) => Increment("shape"); public void Visit(IPointProperty mapping) => Increment("point"); public void Visit(IIpProperty mapping) => Increment("ip"); public void Visit(IObjectProperty mapping) => Increment("object"); public void Visit(IBooleanProperty mapping) => Increment("boolean"); public void Visit(ITextProperty mapping) => Increment("text"); public void Visit(IKeywordProperty mapping) => Increment("keyword"); public void Visit(ITypeMapping mapping) => Increment("type"); public void Visit(IRankFeatureProperty mapping) => Increment("rank_feature"); public void Visit(IRankFeaturesProperty mapping) => Increment("rank_features"); public void Visit(ISearchAsYouTypeProperty property) => Increment("search_as_you_type"); public void Visit(IFlattenedProperty property) => Increment("flattened"); public void Visit(IHistogramProperty property) => Increment("histogram"); public void Visit(IConstantKeywordProperty property) => Increment("constant_keyword"); public void Visit(IVersionProperty property) => Increment("version"); public void Visit(IDenseVectorProperty property) => Increment("dense_vector"); public void Visit(IMatchOnlyTextProperty property) => Increment("match_only_text"); private void Increment(string key) { if (!Counts.ContainsKey(key)) Counts.Add(key, 0); Counts[key] += 1; } public void CountsShouldContainKeyAndCountBe(string key, int count) { Counts.ContainsKey(key).Should().BeTrue($"did not see {key}"); var sb = new StringBuilder() .AppendLine($"because there should be {count} {key} properties"); var because = Counts.Aggregate(sb, (s, kv) => s.AppendLine($"{kv.Key} = {kv.Value}"), s => s.ToString()); Counts[key].Should().Be(count, because); } } }
37.2749
124
0.757696
[ "Apache-2.0" ]
Jiasyuan/elasticsearch-net
tests/Tests/Indices/MappingManagement/GetMapping/GetMappingApiTest.cs
9,356
C#
using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; namespace CsSolution { public partial class FormMain : Form { private const int numberOfPointsToGenerate = 100; private readonly Model solution; public FormMain() { InitializeComponent(); this.solution = new Model(numberOfPointsToGenerate); chartMain.Series[0].Points.Clear(); foreach (Point p in this.solution.PointsToDisplay) { chartMain.Series[0].Points.AddXY(p.X, p.Y); } chartMain.Series[0].ChartType = SeriesChartType.Point; chartMain.ChartAreas[0].AxisX.Minimum = -15; chartMain.ChartAreas[0].AxisX.Maximum = 15; chartMain.ChartAreas[0].AxisY.Minimum = -15; chartMain.ChartAreas[0].AxisY.Maximum = 15; } } }
29.83871
66
0.611892
[ "MIT" ]
mohenjo/AlgorithmTraining
RosettaCode/ConstrainedRandomPointsOnACircle/CsSolution/FormMain.cs
927
C#
using System.Collections.Generic; namespace StrategyPattern_EXER { public class AgeComparator : IComparer<Person> { public int Compare(Person first, Person second) { return first.Age.CompareTo(second.Age); } } }
21.75
55
0.643678
[ "MIT" ]
mayapeneva/C-Sharp-OOP-Advanced
03.IteratorsAndComparators/StrategyPattern_EXER/AgeComparator.cs
263
C#
//------------------------------------------------------------------------------ // <generado automáticamente> // Este código fue generado por una herramienta. // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </generado automáticamente> //------------------------------------------------------------------------------ namespace WebApplication3 { public partial class Correcto { } }
31.125
95
0.467871
[ "MIT" ]
jled7/HADS
WebApplication3/Correcto.aspx.designer.cs
506
C#
using System; using Octopus.Client.Model; namespace Octopus.Client.Repositories { public interface IUserRolesRepository : IFindByName<UserRoleResource>, IGet<UserRoleResource>, ICreate<UserRoleResource>, IModify<UserRoleResource> { } class UserRolesRepository : BasicRepository<UserRoleResource>, IUserRolesRepository { public UserRolesRepository(IOctopusClient client) : base(client, "UserRoles") { } } }
27.705882
151
0.711253
[ "Apache-2.0" ]
roederja/OctopusClients
source/Octopus.Client/Repositories/UserRolesRepository.cs
471
C#
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Denis Kuzmin <x-3F@outlook.com> github/3F // Copyright (c) IeXod contributors https://github.com/3F/IeXod/graphs/contributors // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.IO; using System.Globalization; using System.Reflection; using System.Resources; using System.Xml; using System.Text; using System.Security; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using System.Linq; using net.r_eg.IeXod.Construction; using net.r_eg.IeXod.Shared; using ProjectLoadSettings = net.r_eg.IeXod.BuildEngine.ProjectLoadSettings; using OldProject = net.r_eg.IeXod.BuildEngine.Project; using OldEngine = net.r_eg.IeXod.BuildEngine.Engine; using InvalidProjectFileException = net.r_eg.IeXod.Exceptions.InvalidProjectFileException; using ProjectXmlUtilities = net.r_eg.IeXod.Internal.ProjectXmlUtilities; using error = net.r_eg.IeXod.Shared.ErrorUtilities; using net.r_eg.IeXod.Evaluation; namespace net.r_eg.IeXod.Conversion { /*************************************************************************** * * An outline of the structure of a VS.NET 2002/2003 project file is shown * below: * * <VisualStudioProject> * <CSHARP, VisualBasic, or VISUALJSHARP attributes> * <Build> * <Settings attributes> * <Config Name="..." attributes> * <InteropRegistration attributes /> (.USER file only) * </Config> * <Config Name="..." attributes> * <InteropRegistration attributes /> (.USER file only) * </Config> * ... * </Settings> * * <References> * <Reference * Name="alias" (required) * Private="True/False" * Guid="guid" (COM2 references only) * VersionMinor="minorversion" (COM2 references only) * VersionMajor="majorversion" (COM2 references only) * Lcid="lcid" (COM2 references only) * WrapperTool="wrappertool" (COM2 references only) * Project="projectguid" (Project references only) * Package="packageguid" (Project references only) * AssemblyName="assembly" (.NET references only) * HintPath="hintpath" (.NET references only) * AssemblyFolderKey="asmfolder" (.NET references only) * /> * <Reference .../> * ... * </References> * * <Imports> * <Import Namespace="namespace" /> * <Import Namespace="namespace" /> * ... * </Imports> * </Build> * * <Files> * <Include> * <File * RelPath="project-relative path" * Link="path to actual file" (Linked files only) * SubType="subtype" * BuildAction="buildaction" * DesignTime="true/false" * AutoGen="true/false" * Generator="generator" * CustomToolNamespace="customtoolns" * LastGenOutputs="lastgenoutputs" * DependentUpon="dependentfile" * /> * <Folder * RelPath="relpath" * WebReferences="true" (Web reference folders only) * WebReferenceURL="url" (Web references only) * UrlBehavior="urlbehavior" (Web references only) * /> * ... * </Include> * </Files> * * <StartupServices> * <Service ID="id"/> * <Service ID="id"/> * ... * </StartupServices> * * <UserProperties attributes> * random goop? * </UserProperties> * * <OtherProjectSettings attributes /> (.USER file only) * * </CSHARP, /VisualBasic, or /VISUALJSHARP> * * </VisualStudioProject> * **************************************************************************/ /// <summary> /// This class performs a project file format conversion from Visual Studio /// .NET 2002 or 2003 to MSBuild format (for Whidbey). /// </summary> /// <owner>rgoel</owner> public sealed class ProjectFileConverter { // The filename of the old VS7/Everett project file. private string oldProjectFile = null; // The target Whidbey project file for the conversion. private string newProjectFile = null; // Is the project file we're converting a .USER file? private bool isUserFile = false; // Is the conversion a minor upgrade operation? // Minor upgrade also means the converted project file can be opened in old VS as well, so we won't update the tools version. private bool isMinorUpgrade = false; // The object representing the destination XMake project. private ProjectRootElement xmakeProject = null; // This is the XMake object representing the global property group // in the destination project file. private ProjectPropertyGroupElement globalPropertyGroup = null; // The language for the project we're converting -- CSHARP, VisualBasic, VISUALJSHARP private string language = null; // This is the project instance GUID for the project we're converting // (only if it's the main project file -- this doesn't apply for .USER // files). private string projectGuid = null; // This is the fullpath to the solution file that contains this project // being converted. When conversion is done from the IDE in-proc, this // information can be given to us unambiguously. However, in the command- // line case, we may have to use a heuristic to search for the containing // SLN ourselves. private string solutionFile = null; // This is the object representing the VS solution named above. private SolutionFile solution = null; // The PreBuildEvent and PostBuildEvent properties are handled specially. private string preBuildEvent = null; private string postBuildEvent = null; // If we see any web references in the project, we must add some new properties to the // Whidbey project file, in order to force the proxy generation code to mimic the // Everett behavior. private bool newWebReferencePropertiesAdded = false; // If this is a VSD ( devices ) project, this is the platform retrieved. It's needed in two places... private string platformForVSD = null; private string frameworkVersionForVSD = null; // Cache the assembly name (used for converting DocumentationFile property for VB) private string assemblyName = null; // Cache the output type (used for choosing the correct MyType for VB projects). private string outputType = null; // Whether or not System.Windows.Forms is present as a reference. private bool hasWindowsFormsReference = false; private bool isMyTypeAlreadySetInOriginalProject = false; // Internal collecction that collects the conversion warnings, // to be exposed through the ConversionWarnings property private ArrayList conversionWarnings = null; // A list of property names whose values we need to escape when converting to Whidbey. private Dictionary<string,string> propertiesToEscape = null; /// <summary> /// Default constructor. We need a constructor that takes zero parameters, /// because this class needs to be instantiated from COM. /// </summary> /// <owner>rgoel</owner> public ProjectFileConverter ( ) { this.oldProjectFile = null; this.newProjectFile = null; this.isUserFile = false; this.solutionFile = null; Initialize(); } /// <summary> /// The read/write accessor for the old project filename. This must be /// set by the consumer before calling Convert(). /// </summary> /// <owner>rgoel</owner> public string OldProjectFile { get { return oldProjectFile; } set { oldProjectFile = value; } } /// <summary> /// The read/write accessor for the new project filename. This must be /// set by the consumer before calling Convert(). /// </summary> /// <owner>rgoel</owner> public string NewProjectFile { get { return newProjectFile; } set { newProjectFile = value; } } /// <summary> /// The read/write accessor for the boolean which tells the converter /// whether the project file we're converting is a "main" project file /// or a .USER file. Most of the conversion logic is identical for /// both types of files, but for example, one difference is that the /// "main" project file gets an &lt;Import&gt; tag inserted at the end. /// </summary> /// <owner>rgoel</owner> public bool IsUserFile { get { return isUserFile; } set { isUserFile = value; } } /// <summary> /// The read/write accessor for the solution file which contains this /// project being converted. This is used to look up information about the /// project-to-project references. /// </summary> /// <owner>rgoel</owner> public string SolutionFile { get { return solutionFile; } set { solutionFile = Path.GetFullPath(value); } } /// <summary> /// Indicates if the last attempted conversion was skipped because the project is already in the latest format. /// This will always return false; /// </summary> /// <owner>SumedhK</owner> /// <value>true, if conversion was skipped</value> public bool ConversionSkippedBecauseProjectAlreadyConverted { get { return false; } } /// <summary> /// This property returns the list of warnings that were generated during the conversion /// </summary> /// <owner>faisalmo</owner> /// <value>true, if conversion was skipped</value> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Public interface that has shipped previously. ")] public string[] ConversionWarnings { get { return (string[]) conversionWarnings.ToArray(typeof(string)); } } /// <summary> /// Is the conversion a minor upgrade operation? /// Minor upgrade also means the converted project file can be opened in old VS as well, so we won't update the tools version. /// </summary> public bool IsMinorUpgrade { get { return this.isMinorUpgrade; } set { this.isMinorUpgrade = value; } } /// <summary> /// This is the entry point method, which performs the project file format /// conversion. This method will overwrite "newProjectFile" if it already /// exists, so the caller of this method should confirm with the user /// that that's what he really wants to do. /// </summary> /// <owner>rgoel</owner> public void Convert() { DoConvert(); } /// <summary> /// This is the entry point method, which performs the project file format /// conversion. This method will overwrite "newProjectFile" if it already /// exists, so the caller of this method should confirm with the user /// that that's what he really wants to do. /// </summary> /// <owner>rgoel</owner> [Obsolete("Use parameterless overload instead")] public void Convert(ProjectLoadSettings projectLoadSettings) { DoConvert(); } /// <summary> /// This is the entry point method, which performs the project file format /// conversion. This method will overwrite "newProjectFile" if it already /// exists, so the caller of this method should confirm with the user /// that that's what he really wants to do. /// </summary> /// <owner>rgoel</owner> [Obsolete("Use parameterless overload instead.")] public void Convert ( string msbuildBinPath ) { DoConvert(); } /// <summary> /// Helper method to convert given an engine /// </summary> private void DoConvert() { // Make sure we were passed in non-empty source and destination project // file names. error.VerifyThrowArgument((this.oldProjectFile != null) && (this.oldProjectFile.Length > 0), "MissingOldProjectFile"); error.VerifyThrowArgument((this.newProjectFile != null) && (this.newProjectFile.Length > 0), "MissingNewProjectFile"); ConvertInMemoryToMSBuildProject(); this.xmakeProject.Save(newProjectFile); } /// <summary> /// Initialize all member variables to get ready for a conversion. /// </summary> /// <owner>RGoel</owner> private void Initialize() { this.xmakeProject = null; this.globalPropertyGroup = null; this.language = null; this.projectGuid = null; this.preBuildEvent = null; this.postBuildEvent = null; this.solution = null; this.newWebReferencePropertiesAdded = false; this.platformForVSD = null; this.assemblyName = null; this.outputType = null; this.hasWindowsFormsReference = false; this.isMyTypeAlreadySetInOriginalProject = false; this.conversionWarnings = new ArrayList(); this.propertiesToEscape = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase); this.propertiesToEscape.Add("ApplicationIcon", null); this.propertiesToEscape.Add("AssemblyKeyContainerName", null); this.propertiesToEscape.Add("AssemblyName", null); this.propertiesToEscape.Add("AssemblyOriginatorKeyFile", null); this.propertiesToEscape.Add("RootNamespace", null); this.propertiesToEscape.Add("StartupObject", null); this.propertiesToEscape.Add("ConfigurationOverrideFile", null); this.propertiesToEscape.Add("DocumentationFile", null); this.propertiesToEscape.Add("OutputPath", null); } /// <summary> /// This is the entry point method, which performs the project file format /// conversion. This method will simply create a new XmlDocument /// in memory, instead of trying to write it to disk. /// </summary> /// <owner>RGoel</owner> private void ConvertInMemoryToMSBuildProject() { // Make sure we were passed in non-empty source and destination project // file names. error.VerifyThrowArgument((this.oldProjectFile != null) && (this.oldProjectFile.Length > 0), "MissingOldProjectFile"); // Make sure the source project file exists. error.VerifyThrowArgument(File.Exists(oldProjectFile), "ProjectFileNotFound", oldProjectFile); Initialize(); // Load the old project file as an XML document. XmlDocumentWithLocation oldProjectDocument = new XmlDocumentWithLocation(); oldProjectDocument.PreserveWhitespace = true; TextReader oldProjectFileReader = new OldVSProjectFileReader(oldProjectFile); try { // We have our own custom XML reader to read in the old VS7/Everett project // file. This is because the VS7/Everett project file format supported // having characters like <, >, &, etc. embedded inside XML attribute // values, but the default XmlTextReader won't handle this. using (XmlTextReader xmlReader = new XmlTextReader(oldProjectFileReader)) { xmlReader.DtdProcessing = DtdProcessing.Ignore; oldProjectDocument.Load(xmlReader); } } catch (Exception e) { throw new InvalidProjectFileException(e.Message); } finally { oldProjectFileReader.Close(); } // Get the top-level nodes from the XML. XmlNodeList rootNodes = oldProjectDocument.ChildNodes; XmlElementWithLocation visualStudioProjectElement = null; // The XML parser will guarantee that we only have one real root element, // but since XML comments may appear outside of the <VisualStudioProject> scope, // it's possible to get more than one child node. Just find the first // non-comment node. That should be the <VisualStudioProject> element. foreach(XmlNode childNode in rootNodes) { if ((childNode.NodeType != XmlNodeType.Comment) && (childNode.NodeType != XmlNodeType.XmlDeclaration) && (childNode.NodeType != XmlNodeType.Whitespace)) { visualStudioProjectElement = (XmlElementWithLocation) childNode; break; } } IElementLocation oldProjectDocumentLocation = ElementLocation.Create(oldProjectDocument.FullPath, 1, 1); // Verify that we found a non-comment root node. ProjectErrorUtilities.VerifyThrowInvalidProject(visualStudioProjectElement != null, oldProjectDocumentLocation, "NoRootProjectElement", VSProjectElements.visualStudioProject); // If the root element is <Project>, then assume that this project is // already in XMake format. if (visualStudioProjectElement.Name == XMakeProjectStrings.project) { this.xmakeProject = ProjectRootElement.Open(oldProjectFile); // For Whidbey project just need to set the "ToolsVersion" attribute for the main project file // and remove imports like <Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" /> // because the Fidalgo stuff is part of .NET Framework 3.5 // For upgraded workflow projects, the workflow targets need to reference the new v3.5 targets instead of v3.0 targets // this change is required to fix the msbuild break when building workflow rules. // e.g. before upgrade :<Import Project="$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\v3.0\Workflow.Targets" /> // after upgrade <Import Project="$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\v3.5\Workflow.Targets" /> string oldToolsVersion = xmakeProject.ToolsVersion; xmakeProject.ToolsVersion = XMakeProjectStrings.toolsVersion; List<ProjectImportElement> listOfImportsToBeDeleted = new List<ProjectImportElement>(); List<ProjectImportElement> listOfWFImportsToBeDeleted = new List<ProjectImportElement>(); List<string> workflowImportsToAdd = new List<string>(); string workflowTargetsBasePath = @"$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\"; string workflowOldWhidbeyTargetsPath = workflowTargetsBasePath + @"v3.0\"; string workflowOldOrcasTargetsPath = workflowTargetsBasePath + @"v3.5\"; string workflowNewTargetsPath = @"$(MSBuildToolsPath)\"; bool removedWFWhidbeyTargets = false; bool changedProject = false; // Find matching imports but don't delete whilst enumerating else it will throw an error foreach (ProjectImportElement nextImport in xmakeProject.Imports) { if (String.Compare(nextImport.Project, @"$(MSBuildBinPath)\Microsoft.WinFX.targets", StringComparison.OrdinalIgnoreCase) == 0) { listOfImportsToBeDeleted.Add(nextImport); } if (nextImport.Project.Contains(workflowOldWhidbeyTargetsPath)) { listOfWFImportsToBeDeleted.Add(nextImport); workflowImportsToAdd.Add(nextImport.Project.Replace(workflowOldWhidbeyTargetsPath, workflowNewTargetsPath)); removedWFWhidbeyTargets = true; } if (nextImport.Project.Contains(workflowOldOrcasTargetsPath)) { listOfWFImportsToBeDeleted.Add(nextImport); workflowImportsToAdd.Add(nextImport.Project.Replace(workflowOldOrcasTargetsPath, workflowNewTargetsPath)); } } // Now delete any matching imports foreach (ProjectImportElement importToDelete in listOfWFImportsToBeDeleted) { this.xmakeProject.RemoveChild(importToDelete); changedProject = true; } bool removedWinFXTargets = false; foreach (ProjectImportElement importToDelete in listOfImportsToBeDeleted) { this.xmakeProject.RemoveChild(importToDelete); removedWinFXTargets = true; changedProject = true; } // If we removed WinFX targets this is a sparkle project and should use v3.0 if (removedWinFXTargets) { xmakeProject.AddProperty(XMakeProjectStrings.TargetFrameworkVersion, "v3.0"); changedProject = true; } //If we removed WFWhidbey imports, we should target this project to v3.0 if (removedWFWhidbeyTargets) { xmakeProject.AddProperty(XMakeProjectStrings.TargetFrameworkVersion, "v3.0"); changedProject = true; } // Re-add the workflow imports with the v4.0 targets. foreach (string workflowImportToAdd in workflowImportsToAdd) { this.xmakeProject.AddImport(workflowImportToAdd); changedProject = true; } // Find all the XAML files in the project and give them the custom attributes // <Generator>MSBuild:Compile</Generator> (DevDiv Bugs bug 81222) // <SubType>Designer</SubType> (DevDiv Bugs bug 82748) // Find all references to old VC project files (.vcproj extension) and change the // extension to .vcxproj instead. NOTE: we assume that the actual .vcproj -> .vcxproj // conversion has already been / is being / will be done elsewhere. // Dev10 Bug 557388 foreach (ProjectItemElement nextItem in xmakeProject.Items) { if ((!nextItem.ItemType.Equals("Reference", StringComparison.OrdinalIgnoreCase)) && (nextItem.Include.Trim().EndsWith(".xaml", StringComparison.OrdinalIgnoreCase))) { if (!nextItem.Metadata.Any(m => String.Equals(m.Name, "Generator", StringComparison.OrdinalIgnoreCase))) { nextItem.AddMetadata("Generator", "MSBuild:Compile"); changedProject = true; } if (!nextItem.Metadata.Any(m => String.Equals(m.Name, "SubType", StringComparison.OrdinalIgnoreCase))) { nextItem.AddMetadata("SubType", "Designer"); changedProject = true; } } if (String.Equals(nextItem.ItemType, "ProjectReference", StringComparison.OrdinalIgnoreCase) && nextItem.Include.Trim().EndsWith(".vcproj", StringComparison.OrdinalIgnoreCase)) { nextItem.Include = Path.ChangeExtension(nextItem.Include, ".vcxproj"); changedProject = true; } } // DevDiv Bugs bug 100701: if we removed the Microsoft.WinFX.targets import, // and if there is no ProjectTypeGuids property, add the WPF flavor GUID if (removedWinFXTargets) { ProjectPropertyElement currentGuidsProperty = FindPropertyIfPresent(this.xmakeProject, XMakeProjectStrings.projectTypeGuids); string newGuids = "{" + XMakeProjectStrings.wpfFlavorGuid + "}"; if (currentGuidsProperty == null || currentGuidsProperty.Value.Length == 0) { string currentGuids = String.Empty; // To have a flavor GUID we need a base GUID. if (oldProjectFile.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) { currentGuids = "{" + XMakeProjectStrings.cSharpGuid + "}"; } if (oldProjectFile.EndsWith(".vbproj", StringComparison.OrdinalIgnoreCase)) { currentGuids = "{" + XMakeProjectStrings.visualBasicGuid + "}"; } xmakeProject.AddProperty(XMakeProjectStrings.projectTypeGuids, newGuids + ";" + currentGuids); changedProject = true; } } // Fix up TargetFrameworkSubset changedProject = FixTargetFrameworkSubset() || changedProject; var hasFSharpSpecificConversions = FSharpSpecificConversions(true); changedProject = hasFSharpSpecificConversions || changedProject; changedProject = VBSpecificConversions() || changedProject; // Do asset compat repair for any project that was previously a TV < 12.0 if ( String.IsNullOrEmpty(oldToolsVersion) || String.Equals(oldToolsVersion, "3.5", StringComparison.OrdinalIgnoreCase) || String.Equals(oldToolsVersion, "4.0", StringComparison.OrdinalIgnoreCase) ) { changedProject = DoRepairForAssetCompat() || changedProject; } // Remove any default fully qualified Code Analysis paths. // DevDiv bug 63415 changedProject = FixCodeAnalysisPaths() || changedProject; if (hasFSharpSpecificConversions && !String.IsNullOrEmpty(oldToolsVersion)) { // for Bug 609702:A ToolsVersion=12.0 F# project fails to load in VS 2012 // for F# project after upgrade we restore previous value of ToolsVersion so Dev11 still can load upgraded project // however if old ToolsVersion as 3.5 - it will be upgraded to 4.0 to avoid any unexpected behavior in Dev10\Dev11 xmakeProject.ToolsVersion = String.Equals(oldToolsVersion, "3.5", StringComparison.OrdinalIgnoreCase) ? "4.0" : oldToolsVersion; } else if (this.isMinorUpgrade || (!changedProject && !String.IsNullOrEmpty(oldToolsVersion) && !String.Equals(oldToolsVersion, "3.5", StringComparison.OrdinalIgnoreCase)) ) { // If it's minor upgrade, or nothing changed and the project was already TV 4.0 or higher, // set the ToolsVersion back to its old value. xmakeProject.ToolsVersion = oldToolsVersion; } } else { // OK, we have to start with a fresh project and assemble it this.xmakeProject = ProjectRootElement.Create(); // This root node must be a <VisualStudioProject> node. ProjectErrorUtilities.VerifyThrowInvalidProject(visualStudioProjectElement.Name == VSProjectElements.visualStudioProject, visualStudioProjectElement.Location, "UnrecognizedElement", visualStudioProjectElement.Name); // Set the "DefaultTargets" attribute for the main project file. if (!isUserFile) { xmakeProject.DefaultTargets = XMakeProjectStrings.defaultTargets; } // Set the "ToolsVersion" attribute for the main project file. if (!isUserFile) { xmakeProject.ToolsVersion = XMakeProjectStrings.toolsVersion; } // Process the <VisualStudioProject> element in the source project file, // adding the necessary stuff to the XMake project. this.ProcessVisualStudioProjectElement(visualStudioProjectElement); } } /// <summary> /// returns 'false' if there was no repair required /// else does a repair and returns 'true' /// </summary> /// <returns>bool</returns> private bool DoRepairForAssetCompat() { var toRepairImports = RequiresRepairForAssetCompat(); if (toRepairImports == null || toRepairImports.Count() == 0) { // no need to repair return false; } foreach (var toRepairImport in toRepairImports) { RepairImportForAssetCompat(toRepairImport); } // // Add PropertyGroup with Conditions right before where the Imports occur // <PropertyGroup> // <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> // <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath> // </PropertyGroup> // var vsToolsPathPropGroup = this.xmakeProject.CreatePropertyGroupElement(); var firstAmongImports = this.xmakeProject.Imports.First(); firstAmongImports.Parent.InsertBeforeChild(vsToolsPathPropGroup, firstAmongImports); var vsVersionProperty = this.xmakeProject.CreatePropertyElement(XMakeProjectStrings.visualStudioVersion); vsVersionProperty.Value = @"10.0"; vsVersionProperty.Condition = @"'$(VisualStudioVersion)' == ''"; vsToolsPathPropGroup.AppendChild(vsVersionProperty); var vsToolsPathProperty = this.xmakeProject.CreatePropertyElement(XMakeProjectStrings.vsToolsPath); vsToolsPathProperty.Value = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)"; vsToolsPathProperty.Condition = @"'$(VSToolsPath)' == ''"; vsToolsPathPropGroup.AppendChild(vsToolsPathProperty); // // Add a conditional import to Microsoft.Common.props at the beginning of project // <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"/> // var newImportElement = this.xmakeProject.CreateImportElement(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"); newImportElement.Condition = @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"; this.xmakeProject.InsertBeforeChild(newImportElement, this.xmakeProject.FirstChild); return true; } /// <summary> /// Repairs the given import element /// Change Import to use $(VSToolsPath), with Condition using $(VSToolsPath) /// e.g. From: Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" /// To: Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /// Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" /// $(VSToolsPath) will be defined elsewhere in this upgrade to be: $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) /// </summary> /// <param name="toRepairImport"></param> private void RepairImportForAssetCompat(ProjectImportElement toRepairImport) { // We shouldn't have this happen but check anyway: ErrorUtilities.VerifyThrowInternalNull(toRepairImport, "toRepairImport"); ErrorUtilities.VerifyThrow(!toRepairImport.Condition.Equals("false", StringComparison.OrdinalIgnoreCase), "RepairImportForAssetCompat should not receive imports with condition=false already"); var newImportElement = this.xmakeProject.CreateImportElement(toRepairImport.Project); newImportElement.Condition = "false"; newImportElement.Project = XMakeProjectStrings.toRepairPatternForAssetCompatV10 + ExtractImportTargetsString(newImportElement.Project); toRepairImport.Parent.InsertAfterChild(newImportElement, toRepairImport); toRepairImport.Project = @"$(VSToolsPath)\" + ExtractImportTargetsString(toRepairImport.Project); toRepairImport.Condition = @"'$(VSToolsPath)' != ''"; } /// <summary> /// Extracts the actual targets imported without the repair -pattern path /// e.g. from: $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets /// we will extract: WebApplications\Microsoft.WebApplication.targets /// </summary> /// <param name="importProjectValue"></param> /// <returns></returns> private string ExtractImportTargetsString(string importProjectValue) { // For VS2005 Office Targets return: OfficeTools\Microsoft.VisualStudio.Tools.Office.targets if (importProjectValue.Equals(XMakeProjectStrings.officeTargetsVS2005Import, StringComparison.OrdinalIgnoreCase) || importProjectValue.Equals(XMakeProjectStrings.officeTargetsVS2005Import2, StringComparison.OrdinalIgnoreCase)) { return XMakeProjectStrings.officeTargetsVS2005Repair; } string startString; if (importProjectValue.StartsWith(XMakeProjectStrings.toRepairPatternForAssetCompat, StringComparison.OrdinalIgnoreCase)) { startString = XMakeProjectStrings.toRepairPatternForAssetCompat; } else { startString = XMakeProjectStrings.toRepairPatternForAssetCompatBeforeV10; } string result = importProjectValue.Remove(0, startString.Length); // Extract the version string Match m = Regex.Match(result, XMakeProjectStrings.repairHardCodedPathPattern); return result.Remove(0, m.Length); } /// <summary> /// Checks if repair is required /// </summary> /// <returns>bool</returns> private IEnumerable<ProjectImportElement> RequiresRepairForAssetCompat() { // check if the project has the to-repair pattern in the Imports // pattern: $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\ var toRepairImports = from import in xmakeProject.Imports where HasRepairPattern(import) select import; return toRepairImports; } /// <summary> /// Check if the Import element has a repair pattern: /// $(MSBuildExtensionsPath)\Microsoft\VisualStudio\vX.X /// or $(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools.targets /// </summary> /// <param name="importElement"></param> /// <returns></returns> private bool HasRepairPattern(ProjectImportElement importElement) { bool bHasRepairPattern = false; // in case of an already repaired project the repair pattern will exist with Condition="false" if (!String.Equals(importElement.Condition, "false", StringComparison.OrdinalIgnoreCase)) { if ((importElement.Project.StartsWith(XMakeProjectStrings.toRepairPatternForAssetCompat, StringComparison.OrdinalIgnoreCase)) || (importElement.Project.StartsWith(XMakeProjectStrings.toRepairPatternForAssetCompatBeforeV10, StringComparison.OrdinalIgnoreCase))) { string startString; if (importElement.Project.StartsWith(XMakeProjectStrings.toRepairPatternForAssetCompat, StringComparison.OrdinalIgnoreCase)) { startString = XMakeProjectStrings.toRepairPatternForAssetCompat; } else { startString = XMakeProjectStrings.toRepairPatternForAssetCompatBeforeV10; } Match m = Regex.Match(importElement.Project.Substring(startString.Length), XMakeProjectStrings.repairHardCodedPathPattern); if (m.Success) { bHasRepairPattern = true; } } else { // Check for VS2003/2005 Office Targets // $(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools.targets if (importElement.Project.Equals(XMakeProjectStrings.officeTargetsVS2005Import, StringComparison.OrdinalIgnoreCase) || importElement.Project.Equals(XMakeProjectStrings.officeTargetsVS2005Import2, StringComparison.OrdinalIgnoreCase)) bHasRepairPattern = true; } } return bHasRepairPattern; } /// <summary> /// Fixes <TargetFrameworkSubset/> properties in the project file. This was the Orcas SP1 way of /// handling framework profiles, and that way is now incompatible with the VS 2010 way of handling /// profiles. /// </summary> /// <returns>true if changes were required, false otherwise</returns> private bool FixTargetFrameworkSubset() { bool changedProject = false; foreach (ProjectPropertyElement propertyElement in xmakeProject.Properties) { if (String.Equals(propertyElement.Name , XMakeProjectStrings.TargetFrameworkSubset, StringComparison.OrdinalIgnoreCase)) { // For the Client profile, which was the only profile supported in Orcas SP1, we want to replace // <TargetFrameworkSubset/> with <TargetFrameworkProfile/>. if (String.Equals(propertyElement.Value, XMakeProjectStrings.ClientProfile, StringComparison.OrdinalIgnoreCase)) { ProjectPropertyGroupElement parentGroup = (ProjectPropertyGroupElement) propertyElement.Parent; parentGroup.SetProperty(XMakeProjectStrings.TargetFrameworkProfile, XMakeProjectStrings.ClientProfile); changedProject = true; } // In all cases, <TargetFrameworkSubset/> is no longer supported. If it comes from the project // that we're converting, then we forcibly remove it. If it comes from some import... the user is // on their own. if (propertyElement.ContainingProject == xmakeProject) { propertyElement.Parent.RemoveChild(propertyElement); changedProject = true; } break; } } return changedProject; } /// <summary> /// Performs conversions specific to F# projects (VS2008 CTP -> VS2012) and (VS2010 -> VS2012). /// This involves: changing the location of FSharp targets, /// and for 2008CTP, adding explicit mscorlib and FSharp.Core references. /// </summary> /// <param name="actuallyMakeChanges">if true, make the changes, otherwise, don't actually make any changes, but do report the return boolean as to whether you would make changes</param> /// <returns>true if anything was (would be) changed, false otherwise</returns> public bool FSharpSpecificConversions(bool actuallyMakeChanges) { // For FSharp projects, should import different location of FSharp targets const string fsharpFS10TargetsPath = @"$(MSBuildExtensionsPath)\FSharp\1.0\Microsoft.FSharp.Targets"; const string fsharpFS10TargetsPath32 = @"$(MSBuildExtensionsPath32)\FSharp\1.0\Microsoft.FSharp.Targets"; const string fsharpFS40TargetsPath = @"$(MSBuildExtensionsPath32)\..\Microsoft F#\v4.0\Microsoft.FSharp.Targets"; const string fsharpFS45TargetsPath = @"$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets"; const string fsharpPortableDev11TargetsPath = @"$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.Portable.FSharp.Targets"; const string fsharpDev12PlusProperty = "FSharpTargetsPath"; // Dev12+ projects import *.targets files using property const string fsharpDev12PlusImportsValue = @"$(" + fsharpDev12PlusProperty + ")"; // Q: do we need to distinguish between different versions of F# for the same version of VS const string fsharpDev12PlusTargetsPath = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets"; const string fsharpDev12PlusPortableTargetsPath = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.Portable.FSharp.Targets"; bool isAtLeastDev10Project = false; ProjectImportElement fsharpTargetsFS10Import = null; ProjectImportElement fsharpTargetsFS40Import = null; ProjectImportElement fsharpTargetsFS45Import = null; ProjectImportElement fsharpTargetsDev12PlusImport = null; ProjectImportElement fsharpTargetsDev11PortableImport = null; if (actuallyMakeChanges == false && this.xmakeProject == null) { // when coming down the actuallyMakeChanges==false code path (from the F# project system's UpgradeProject_CheckOnly method), we may not have loaded the Xml yet, so do that now this.xmakeProject = ProjectRootElement.Open(oldProjectFile); } // local function: string equality check using OrdinalIgnoreCase comparison Func<string, string, bool> equals = (s1, s2) => String.Equals(s1, s2, StringComparison.OrdinalIgnoreCase); // local function: wraps specified string value into Exists('value') Func<string, string> exists = s => string.Format(CultureInfo.InvariantCulture, "Exists('{0}')", s); // local function: // Creates property group element containing one property fsharpDev12PlusProperty with value 'path'. // If addCondition is true, property group will have Exists(path) condition Action<string, ProjectElementContainer> appendPropertyGroupForDev12PlusTargetsPath = (path, parent) => { var propGroup = xmakeProject.CreatePropertyGroupElement(); parent.AppendChild(propGroup); var prop = xmakeProject.CreatePropertyElement(fsharpDev12PlusProperty); prop.Value = path; propGroup.AppendChild(prop); }; foreach (ProjectImportElement importElement in xmakeProject.Imports) { if (equals(importElement.Project, fsharpFS10TargetsPath) || equals(importElement.Project, fsharpFS10TargetsPath32)) { fsharpTargetsFS10Import = importElement; if (equals(@"!Exists('$(MSBuildToolsPath)\net.r_eg.IeXod.Tasks.v4.0.dll')", fsharpTargetsFS10Import.Condition) || equals(@"!Exists('$(MSBuildBinPath)\net.r_eg.IeXod.Tasks.v4.0.dll')", fsharpTargetsFS10Import.Condition)) { isAtLeastDev10Project = true; } } else if (equals(importElement.Project, fsharpFS40TargetsPath)) { fsharpTargetsFS40Import = importElement; isAtLeastDev10Project = true; } else if (equals(importElement.Project, fsharpFS45TargetsPath)) { fsharpTargetsFS45Import = importElement; isAtLeastDev10Project = true; } else if (equals(importElement.Project, fsharpDev12PlusImportsValue)) { fsharpTargetsDev12PlusImport = importElement; isAtLeastDev10Project = true; } else if (equals(importElement.Project, fsharpPortableDev11TargetsPath)) { fsharpTargetsDev11PortableImport = importElement; isAtLeastDev10Project= true; } } if (fsharpTargetsDev12PlusImport != null) { // if project already contains version independent import - then assume it is already at least dev12 - do nothing return false; } // no other F# imports - do nothing if (fsharpTargetsFS10Import == null && fsharpTargetsFS40Import == null && fsharpTargetsFS45Import == null && fsharpTargetsDev11PortableImport == null) return false; if (!actuallyMakeChanges) return true; // both branches adds this elements to the project var chooseElement = xmakeProject.CreateChooseElement(); // (1) if (fsharpTargetsDev11PortableImport != null) { // Dev11 portable library // Expected fragment of the project file after upgrade //<Choose> // <When Condition="'$(VisualStudioVersion)' == '11.0'"> (2) // <PropertyGroup> // <FSharpTargetsPath>$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.Portable.FSharp.Targets</FSharpTargetsPath> // </PropertyGroup> // </When> // <Otherwise> (3) // <PropertyGroup> // <FSharpTargetsPath>$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.Portable.FSharp.Targets</FSharpTargetsPath> // </PropertyGroup> // </Otherwise> //</Choose> //<Import Project=""$(FSharpTargetsPath)"" Condition="Exists('$(FSharpTargetsPath)')"/> fsharpTargetsDev11PortableImport.Parent.InsertBeforeChild(chooseElement, fsharpTargetsDev11PortableImport); // portable libraries are supported since Dev11 var whenVsVersionIsDev11 = xmakeProject.CreateWhenElement("'$(VisualStudioVersion)' == '11.0'"); // (2) chooseElement.AppendChild(whenVsVersionIsDev11); appendPropertyGroupForDev12PlusTargetsPath(fsharpPortableDev11TargetsPath, whenVsVersionIsDev11); var otherwiseIfVsVersionIsDev12Plus = xmakeProject.CreateOtherwiseElement(); // (3) chooseElement.AppendChild(otherwiseIfVsVersionIsDev12Plus); appendPropertyGroupForDev12PlusTargetsPath(fsharpDev12PlusPortableTargetsPath, otherwiseIfVsVersionIsDev12Plus); } else { // This is an FSharp project, and it does not already have a 4.5 import, and thus it needs repair. // one of these elements should be non-null, otherwise we'll exit based on the check above var someNonNullImportElement = fsharpTargetsFS10Import ?? fsharpTargetsFS40Import ?? fsharpTargetsFS45Import; someNonNullImportElement.Parent.InsertBeforeChild(chooseElement, someNonNullImportElement); // Expected fragment of the project file after upgrade //<Choose> // <When Condition="'$(VisualStudioVersion)' == '11.0'"> // <PropertyGroup> // <FSharpTargetsPath>$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets</FSharpTargetsPath> // </PropertyGroup> // </When> // <Otherwise> // <PropertyGroup> // <FSharpTargetsPath>$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets</FSharpTargetsPath> // </PropertyGroup> // </Otherwise> //</Choose> //<Import Project="$(FSharpTargetsPath)" Condition="Exists('$(FSharpTargetsPath)')" /> var whenVsVersionIsDev11 = xmakeProject.CreateWhenElement("'$(VisualStudioVersion)' == '11.0'"); chooseElement.AppendChild(whenVsVersionIsDev11); { appendPropertyGroupForDev12PlusTargetsPath(fsharpFS45TargetsPath, whenVsVersionIsDev11); } var otherwiseIfVsVersionIsDev12Plus = xmakeProject.CreateOtherwiseElement(); chooseElement.AppendChild(otherwiseIfVsVersionIsDev12Plus); { // Dev12+ projects - import target file based on property 'fsharpDev12PlusProperty' appendPropertyGroupForDev12PlusTargetsPath(fsharpDev12PlusTargetsPath, otherwiseIfVsVersionIsDev12Plus); } } // add Dev12 specific Imports element var dev12PlusImportElement = xmakeProject.CreateImportElement(fsharpDev12PlusImportsValue); dev12PlusImportElement.Condition = exists(fsharpDev12PlusImportsValue); chooseElement.Parent.InsertAfterChild(dev12PlusImportElement, chooseElement); if (fsharpTargetsFS10Import != null) xmakeProject.RemoveChild(fsharpTargetsFS10Import); if (fsharpTargetsFS40Import != null) xmakeProject.RemoveChild(fsharpTargetsFS40Import); if (fsharpTargetsFS45Import != null) xmakeProject.RemoveChild(fsharpTargetsFS45Import); if (fsharpTargetsDev11PortableImport != null) xmakeProject.RemoveChild(fsharpTargetsDev11PortableImport); const string ReferenceItemType = "Reference"; // find ItemGroup for Reference items ProjectItemGroupElement referencesItemGroup = xmakeProject.Items .Where(projectItem => projectItem.ItemType == ReferenceItemType && projectItem.Parent is ProjectItemGroupElement) .Select(projectItem => (ProjectItemGroupElement)projectItem.Parent) .FirstOrDefault(); if (referencesItemGroup == null) { referencesItemGroup = this.xmakeProject.AddItemGroup(); } var targetFrameworkVersionProperty = xmakeProject.Properties.FirstOrDefault(p => equals(p.Name, "TargetFrameworkVersion")); // fix FSharp.Core reference const string TargetFSharpCoreVersionProperty = "TargetFSharpCoreVersion"; // by default import with minimal possible version const string DefaultFSharpCoreVersionFor40 = "4.3.0.0"; const string DefaultFSharpCoreVersionFor20 = "2.3.0.0"; const string DefaultPortableFSharpCoreVersion = "2.3.5.0"; const string FSharpCoreName = "FSharp.Core"; if (!isAtLeastDev10Project) { bool hasMscorlibReference = xmakeProject.Items.Any(projectItem => projectItem.ItemType == ReferenceItemType && equals(projectItem.Include, "mscorlib")); // It appears pre-dev10, so add explicit references to mscorlib if (!hasMscorlibReference) { referencesItemGroup.AddItem(ReferenceItemType, "mscorlib"); } } // try to find reference to FSharp.Core ProjectItemElement fsharpCoreItem = null; foreach (var item in xmakeProject.Items.Where(x => x.ItemType == ReferenceItemType)) { try { var name = new AssemblyName(item.Include); if (name.Name == FSharpCoreName) { fsharpCoreItem = item; break; } } catch (FileLoadException) { // Include contains not AssemblyName but rather something else - not the case for F# projects } } const string Dev11PortableFSharpCoreLocation = @"$(MSBuildExtensionsPath32)\..\Reference Assemblies\Microsoft\FSharp\3.0\Runtime\.NETPortable\FSharp.Core.dll"; const string Dev12PortableFSharpCoreLocationForDev11Projects = @"$(MSBuildExtensionsPath32)\..\Reference Assemblies\Microsoft\FSharp\.NETPortable\$(" + TargetFSharpCoreVersionProperty + @")\FSharp.Core.dll"; const string HintPath = "HintPath"; ProjectItemElement newFSharpCoreItem = null; string targetFSharpCoreVersionValue = null; var hintPathValue = fsharpCoreItem != null ? fsharpCoreItem.Metadata.FirstOrDefault(metadata => metadata.Name == HintPath) : null; if (hintPathValue != null) { if (equals(hintPathValue.Value, Dev11PortableFSharpCoreLocation)) { // Reference to Dev11 portable library newFSharpCoreItem = referencesItemGroup.AddItem(ReferenceItemType, FSharpCoreName); newFSharpCoreItem.AddMetadata(HintPath, Dev12PortableFSharpCoreLocationForDev11Projects); targetFSharpCoreVersionValue = DefaultPortableFSharpCoreVersion; } } else if (!isAtLeastDev10Project || fsharpCoreItem != null) { newFSharpCoreItem = referencesItemGroup.AddItem(ReferenceItemType, string.Format("FSharp.Core, Version=$({0}), Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", TargetFSharpCoreVersionProperty)); if (targetFrameworkVersionProperty == null || string.IsNullOrEmpty(targetFrameworkVersionProperty.Value) || !targetFrameworkVersionProperty.Value.StartsWith("v")) { targetFSharpCoreVersionValue = DefaultFSharpCoreVersionFor40; } else { var versionStr = targetFrameworkVersionProperty.Value.Substring(1); // strip 'v' Version version; targetFSharpCoreVersionValue = Version.TryParse(versionStr, out version) ? version.Major < 4 ? DefaultFSharpCoreVersionFor20 : DefaultFSharpCoreVersionFor40 : DefaultFSharpCoreVersionFor40; } } if (newFSharpCoreItem != null) { newFSharpCoreItem.AddMetadata("Private", "True"); } const string MinimumVisualStudioVersionProperty = "MinimumVisualStudioVersion"; var hasMinimumVSVersion = xmakeProject.Properties.Any(prop => prop.Name == MinimumVisualStudioVersionProperty); foreach(var group in xmakeProject.PropertyGroups) { // find first non-conditional property group to add TargetFSharpCoreVersion property if (string.IsNullOrEmpty(group.Condition)) { if (targetFSharpCoreVersionValue != null) { group.AddProperty(TargetFSharpCoreVersionProperty, targetFSharpCoreVersionValue); } if (!hasMinimumVSVersion) { var prop = group.AddProperty(MinimumVisualStudioVersionProperty, "11"); prop.Condition = "'$(" + MinimumVisualStudioVersionProperty + ")' == ''"; } break; } } // new FSharp.Core was added - can delete the old reference if (newFSharpCoreItem != null && fsharpCoreItem != null) { fsharpCoreItem.Parent.RemoveChild(fsharpCoreItem); } return true; } /// <summary> /// Performs conversions specific to VB projects (VS2008 and VS2008 -> VS2010). /// This involves: Adding a set of nowarn settings to disable warnings added /// in VS2010 that break customers upgrading from previous releases. /// </summary> /// <returns>true if changes were required, false otherwise</returns> private bool VBSpecificConversions() { // Are we upgrading a VB project? // We are if the project file imports: // "$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" (VS2008) // "$(MSBuildBinPath)\Microsoft.VisualBasic.targets" (VS2005) bool vbProject = false; bool changedProject = false; foreach (var import in xmakeProject.Imports) { if (String.Equals(import.Project, XMakeProjectStrings.vbTargetsVS2008, StringComparison.OrdinalIgnoreCase) || String.Equals(import.Project, XMakeProjectStrings.vbTargetsVS2005, StringComparison.OrdinalIgnoreCase)) { vbProject = true; break; } } // Not a VB project -> no work to do. if (!vbProject) { return changedProject; } // Any property group with a condition is of interest. // If we find it and it has "NoWarn" property, we add our warnings into it. // If it doesn't, we create new NoWarn property with the initial value foreach (var group in xmakeProject.PropertyGroups) { if (String.IsNullOrEmpty(group.Condition)) { continue; } string noWarn = null; foreach (var property in group.Properties) { if (String.Equals(property.Name, XMakeProjectStrings.noWarn, StringComparison.OrdinalIgnoreCase)) { noWarn = property.Value; break; } } if (String.IsNullOrWhiteSpace(noWarn)) { noWarn = String.Empty; } else { noWarn = noWarn.Trim(); } string originalNoWarnValue = noWarn; // // Split the no warning string and trim the results // string[] oldWarnings = noWarn.Split(','); for (var oi = 0; oi < oldWarnings.Length; oi++) { oldWarnings[oi] = oldWarnings[oi].Trim(); } // // Add the new warnings specific to Dev10: 42353,42354,42355 // (if we don't have them already) // string[] newWarnings = new[] { "42353", "42354", "42355" }; foreach (var newWarn in newWarnings) { bool found = false; foreach (var oldWarn in oldWarnings) { if (String.Equals(newWarn, oldWarn, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } if (!found) { // append the new warning if (!String.IsNullOrEmpty(noWarn) && !noWarn.EndsWith(",", StringComparison.OrdinalIgnoreCase)) { noWarn += ","; } noWarn += newWarn; } } // Set the property value. If it doesn't exist, it will be added. if (!String.Equals(originalNoWarnValue, noWarn, StringComparison.OrdinalIgnoreCase)) { group.SetProperty(XMakeProjectStrings.noWarn, noWarn); changedProject = true; } } return changedProject; } /// <summary> /// This is the entry point method, which performs the project file format /// conversion. This method will simply create a new MSBuild Project object /// in memory, instead of trying to write it to disk. /// </summary> public ProjectRootElement ConvertInMemory() { ConvertInMemoryToMSBuildProject(); return xmakeProject; } /// <summary> /// This is the entry point method, which performs the project file format /// conversion. This method will simply create a new MSBuild Project object /// in memory, instead of trying to write it to disk. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> [Obsolete("Use parameterless ConvertInMemory() method instead")] public OldProject ConvertInMemory ( OldEngine engine ) { return ConvertInMemory(engine, ProjectLoadSettings.None); } /// <summary> /// This is the entry point method, which performs the project file format /// conversion. This method will simply create a new MSBuild Project object /// in memory, instead of trying to write it to disk. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> [Obsolete("Use parameterless ConvertInMemory() method instead")] public OldProject ConvertInMemory ( OldEngine engine, ProjectLoadSettings projectLoadSettings ) { this.ConvertInMemoryToMSBuildProject(); OldProject oldProject = new OldProject(engine); using (StringReader reader = new StringReader(xmakeProject.RawXml)) { oldProject.Load(reader); } return oldProject; } /// <summary> /// Takes an XML element from an Everett project file, and loops through /// all its attributes. For each attribute, it adds a new XMake property /// to the destination project file in the property group passed in. /// </summary> /// <owner>RGoel</owner> private void AddXMakePropertiesFromXMLAttributes ( ProjectPropertyGroupElement propertyGroup, XmlElement xmlElement ) { error.VerifyThrow(propertyGroup != null, "Expected valid ProjectPropertyElementGroup to add properties to."); foreach (XmlAttribute xmlAttribute in xmlElement.Attributes) { // Add this as a property to the MSBuild project file. If the property is one of those // that contains an identifier or a path, we must escape it to treat it as a literal. string value = xmlAttribute.Value; if (this.propertiesToEscape.ContainsKey(xmlAttribute.Name)) { value = ProjectCollection.Escape(value); } propertyGroup.AddProperty(xmlAttribute.Name, value); } } /// <summary> /// Processes the &lt;VisualStudioProject&gt; XML element, and everything /// within it. As it is doing this, it will add stuff to the xmakeProject. /// </summary> /// <owner>RGoel</owner> private void ProcessVisualStudioProjectElement ( XmlElementWithLocation visualStudioProjectElement ) { // Make sure this is the <VisualStudioProject> element. error.VerifyThrow((visualStudioProjectElement != null) && (visualStudioProjectElement.Name == VSProjectElements.visualStudioProject), "Expected <VisualStudioProject> element."); // Make sure the caller has given us a valid xmakeProject object. error.VerifyThrow(xmakeProject != null, "Expected valid XMake project object."); // This is just about better error reporting. Detect if the user tried // to convert a VC++ or some other type of project, and give a more friendly // error message. string projectType = visualStudioProjectElement.GetAttribute(VSProjectAttributes.projectType); ProjectErrorUtilities.VerifyThrowInvalidProject((projectType == null) || (projectType.Length == 0), visualStudioProjectElement.Location, "ProjectTypeCannotBeConverted", projectType); // Make sure the <VisualStudioProject> tag doesn't have any attributes. ProjectErrorUtilities.VerifyThrowInvalidProject(!visualStudioProjectElement.HasAttributes, visualStudioProjectElement.Location, "NoAttributesExpected", VSProjectElements.visualStudioProject); bool languageFound = false; // Loop through all the direct children of the <VisualStudioProject> element. foreach(XmlNode visualStudioProjectChildNode in visualStudioProjectElement) { // Handle XML comments under the <VisualStudioProject> node (just ignore them) if ((visualStudioProjectChildNode.NodeType == XmlNodeType.Comment) || (visualStudioProjectChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (visualStudioProjectChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation visualStudioProjectChildElement = (XmlElementWithLocation)visualStudioProjectChildNode; switch (visualStudioProjectChildElement.Name) { // See if we have a <CSHARP>, <VisualBasic>, or <VISUALJSHARP> element. case VSProjectElements.cSharp: case VSProjectElements.visualJSharp: case VSProjectElements.visualBasic: case VSProjectElements.ECSharp: case VSProjectElements.EVisualBasic: // Make sure this is the first language node we're encountering. ProjectErrorUtilities.VerifyThrowInvalidProject(!languageFound, visualStudioProjectChildElement.Location, "MultipleLanguageNodesNotAllowed", VSProjectElements.visualStudioProject); languageFound = true; this.language = visualStudioProjectChildNode.Name; this.ProcessLanguageElement((XmlElementWithLocation)visualStudioProjectChildElement); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, visualStudioProjectChildElement.Location, "UnrecognizedChildElement", visualStudioProjectChildElement.Name, VSProjectElements.visualStudioProject); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(visualStudioProjectChildNode.Name, visualStudioProjectElement.Name, visualStudioProjectElement.Location); } } } /// <summary> /// Processes the language (e.g. &lt;CSHARP&gt;) XML element, and everything /// within it. As it is doing this, it will add stuff to the xmakeProject. /// </summary> /// <owner>RGoel</owner> private void ProcessLanguageElement ( XmlElementWithLocation languageElement ) { // Make sure we have a valid XML element to process. error.VerifyThrow(languageElement != null, "Expected valid XML language element."); // Make sure the caller has given us a valid xmakeProject object. error.VerifyThrow(xmakeProject != null, "Expected valid XMake project object."); // Get the project instance GUID for this project file. It is required for // the main project file, but not for the .USER file. this.projectGuid = languageElement.GetAttribute(VSProjectAttributes.projectGuid); ProjectErrorUtilities.VerifyThrowInvalidProject((this.projectGuid != null) || (this.isUserFile == true), languageElement.Location, "MissingAttribute", languageElement.Name, VSProjectAttributes.projectGuid); // Get the project type for this project file. We only support "Local". We do not // convert web projects -- that's Venus's job. string projectType = languageElement.GetAttribute(VSProjectAttributes.projectType); ProjectErrorUtilities.VerifyThrowInvalidProject(projectType == null || projectType.Length == 0 || (String.Compare(projectType, VSProjectAttributes.local, StringComparison.OrdinalIgnoreCase) == 0), languageElement.Location, "ProjectTypeCannotBeConverted", projectType); // All of the attributes on the language tag get converted to XMake // properties. A couple exceptions ... for the "ProductVersion" // and "SchemaVersion" properties, we don't just copy the previous // value; we actually set it to 8.0.##### and 2.0 respectively. // In addition, we also add a default value for the "Configuration" // property. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <CSHARP // ProjectType = "Local" // ProductVersion = "7.10.2284" // SchemaVersion = "1.0" // ProjectGuid = "{71F4C768-901B-4027-BD9D-378665D6C0B2}" // > // ... // ... // ... // </CSHARP> // ----------------------------------------------------------------------- // XMake format: // ============= // <PropertyGroup> // <ProjectType>Local</ProjectType> // <ProductVersion>8.0.31031</ProductVersion> // <SchemaVersion>2.0</SchemaVersion> // <ProjectGuid>{71F4C768-901B-4027-BD9D-378665D6C0B2}</ProjectGuid> // <Configuration Condition = " '$(Configuration)' == '' ">Debug</Configuration> // </PropertyGroup> // ----------------------------------------------------------------------- // For Dev11, we are removing "ProductVersion" and "SchemaVersion" from all // project templates. Thus, eliminated writing these tags from this method. // ----------------------------------------------------------------------- string originalMyType = languageElement.GetAttribute(XMakeProjectStrings.myType); if ((originalMyType != null) && (originalMyType.Length != 0)) { // Flag the fact that the Everett project already had a MyType property in there, // so we don't try to override it later. this.isMyTypeAlreadySetInOriginalProject = true; } // Copy over all the other properties. this.globalPropertyGroup = xmakeProject.AddPropertyGroup(); this.AddXMakePropertiesFromXMLAttributes(this.globalPropertyGroup, languageElement); // Add the "Configuration" property. Put a condition on it so it only gets // set to the default if the user doesn't have an environment variable called // "Configuration". The final XML looks something like this: // <Configuration Condition = " '$(Configuration)' == '' ">Debug</Configuration> ProjectPropertyElement configurationProperty = this.globalPropertyGroup.AddProperty( XMakeProjectStrings.configuration, XMakeProjectStrings.defaultConfiguration); configurationProperty.Condition = XMakeProjectStrings.configurationPrefix + XMakeProjectStrings.configurationSuffix; // Add the "Platform" property. Put a condition on it so it only gets // set to the default if the user doesn't have an environment variable called // "Platform". The final XML looks something like this: // <Property Platform = "AnyCPU" Condition = " '$(Platform)' == '' " /> // Platform of course depends on the language we are dealing with - J# in whidbey supports only x86 string platform = (this.language != VSProjectElements.visualJSharp) ? XMakeProjectStrings.defaultPlatform : XMakeProjectStrings.x86Platform; ProjectPropertyElement platformProperty = this.globalPropertyGroup.AddProperty( XMakeProjectStrings.platform, platform); platformProperty.Condition = XMakeProjectStrings.platformPrefix + XMakeProjectStrings.platformSuffix; bool isTriumphProject = false; // For SDE projects, we need to add a special <ProjectTypeGuids> property to // the project file. This will contain the project types for both the // flavor and the main language project type. In addition, SDE projects // need to have the host process disabled. if (!this.isUserFile) { if (languageElement.Name == VSProjectElements.ECSharp) { this.globalPropertyGroup.AddProperty ( XMakeProjectStrings.projectTypeGuids, "{" + XMakeProjectStrings.VSDCSProjectTypeGuid + "};{" + XMakeProjectStrings.cSharpGuid + "}" ); string visualStudioProjectExtensions = GetProjectExtensionsString(XMakeProjectStrings.visualStudio); visualStudioProjectExtensions += XMakeProjectStrings.disableCSHostProc; SetProjectExtensionsString(XMakeProjectStrings.visualStudio, visualStudioProjectExtensions); } else if (languageElement.Name == VSProjectElements.EVisualBasic) { this.globalPropertyGroup.AddProperty ( XMakeProjectStrings.projectTypeGuids, "{" + XMakeProjectStrings.VSDVBProjectTypeGuid + "};{" + XMakeProjectStrings.visualBasicGuid + "}" ); string visualStudioProjectExtensions = GetProjectExtensionsString(XMakeProjectStrings.visualStudio); visualStudioProjectExtensions += XMakeProjectStrings.disableVBHostProc; SetProjectExtensionsString(XMakeProjectStrings.visualStudio, visualStudioProjectExtensions); } } // Loop through all the direct child elements of the language element. foreach(XmlNode languageChildNode in languageElement) { // Handle XML comments under the the language node (just ignore them). if ((languageChildNode.NodeType == XmlNodeType.Comment) || (languageChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (languageChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation languageChildElement = (XmlElementWithLocation)languageChildNode; switch (languageChildElement.Name) { // The <Build> element. case VSProjectElements.build: this.ProcessBuildElement((XmlElementWithLocation)languageChildElement); break; case VSProjectElements.files: this.ProcessFilesElement((XmlElementWithLocation)languageChildElement); break; case VSProjectElements.startupServices: this.ProcessStartupServicesElement((XmlElementWithLocation)languageChildElement); break; case VSProjectElements.userProperties: this.ProcessUserPropertiesElement((XmlElementWithLocation)languageChildElement, out isTriumphProject); break; case VSProjectElements.otherProjectSettings: this.ProcessOtherProjectSettingsElement((XmlElementWithLocation)languageChildElement); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, languageChildElement.Location, "UnrecognizedChildElement", languageChildNode.Name, languageElement.Name); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(languageChildNode.Name, languageElement.Name, languageElement.Location); } } AddFinalPropertiesAndImports(languageElement, isTriumphProject); } /// <summary> /// Adds any last-minute additional properties such as FileUpgradeFlags and MyType, /// and also adds in the necessary Import tags. /// </summary> /// <param name="languageElement"></param> /// <param name="isTriumphProject"></param> private void AddFinalPropertiesAndImports(XmlElementWithLocation languageElement, bool isTriumphProject) { // For the main project file only, add a line at the end of the new XMake // project file to import the appropriate .TARGETS file. if (!this.isUserFile) { // We set a property called "FileUpgradeFlags", so that for command-line conversions, // if this project is ever loaded into the IDE, the file upgrade (.VB code, etc.) will kick in. // The "20" means SxS upgrade. For IDE conversions, the project system will itself set // this property immediately after the MSBuild conversion returns, so this value will // be overwritten. this.globalPropertyGroup.AddProperty(XMakeProjectStrings.fileUpgradeFlags, "20"); // VisualBasic projects need MyType set. if ( ( (this.language == VSProjectElements.visualBasic) || ( (this.language == VSProjectElements.EVisualBasic) && (this.frameworkVersionForVSD == XMakeProjectStrings.vTwo) ) ) && (!this.isMyTypeAlreadySetInOriginalProject) && !isTriumphProject // Doesn't apply to Triumph->Trinity conversions. ) { if (this.outputType != null && this.outputType.Length > 0) { if (String.Compare(this.outputType, XMakeProjectStrings.winExe, StringComparison.OrdinalIgnoreCase) == 0) { if (this.hasWindowsFormsReference) { // Only applies if there's a System.Windows.Forms reference. this.globalPropertyGroup.AddProperty(XMakeProjectStrings.myType, XMakeProjectStrings.windowsFormsWithCustomSubMain); } else { this.globalPropertyGroup.AddProperty(XMakeProjectStrings.myType, XMakeProjectStrings.console); } } else if (String.Compare(this.outputType, XMakeProjectStrings.exe, StringComparison.OrdinalIgnoreCase) == 0) { this.globalPropertyGroup.AddProperty(XMakeProjectStrings.myType, XMakeProjectStrings.console); } else if (String.Compare(this.outputType, XMakeProjectStrings.library, StringComparison.OrdinalIgnoreCase) == 0) { this.globalPropertyGroup.AddProperty(XMakeProjectStrings.myType, XMakeProjectStrings.windows); } } } else if (this.language == VSProjectElements.EVisualBasic) { // For Devices, we always want a MyType of "Empty," as projects // are converted into v1 .NETCF, which doesn't support My.NET this.globalPropertyGroup.AddProperty(XMakeProjectStrings.myType, XMakeProjectStrings.empty); } // We need to handle the SDE scenarios for C# and VB if (languageElement.Name == VSProjectElements.ECSharp) { xmakeProject.AddImport(XMakeProjectStrings.importPrefix + XMakeProjectStrings.SDECSTargets); } else if (languageElement.Name == VSProjectElements.EVisualBasic) { xmakeProject.AddImport(XMakeProjectStrings.importPrefix + XMakeProjectStrings.SDEVBTargets); } else if (languageElement.Name == VSProjectElements.cSharp) { xmakeProject.AddImport(XMakeProjectStrings.importPrefix + XMakeProjectStrings.targetsFilenamePrefix + XMakeProjectStrings.csharpTargets + XMakeProjectStrings.importSuffix); } else if (languageElement.Name == VSProjectElements.visualBasic) { xmakeProject.AddImport(XMakeProjectStrings.importPrefix + XMakeProjectStrings.targetsFilenamePrefix + XMakeProjectStrings.visualBasicTargets + XMakeProjectStrings.importSuffix); } else if (languageElement.Name == VSProjectElements.visualJSharp) { xmakeProject.AddImport(XMakeProjectStrings.importPrefix + XMakeProjectStrings.targetsFilenamePrefix + XMakeProjectStrings.visualJSharpTargets + XMakeProjectStrings.importSuffix); } else { xmakeProject.AddImport(XMakeProjectStrings.importPrefix + XMakeProjectStrings.targetsFilenamePrefix + languageElement.Name + XMakeProjectStrings.importSuffix); } // [ancrider] VSTO project migration will handle the import target changes. //if (isTriumphProject) //{ // xmakeProject.AddImport(XMakeProjectStrings.triumphImport, null); //} // Also add the PreBuildEvent and PostBuildEvent properties to the end // of the project file. The reason is that they can contain embedded // macros that are defined in the .TARGETS file that was imported // above. if ((this.preBuildEvent != null) || (this.postBuildEvent != null)) { // In this case, we specifically need the property group at the end, so we can't just call AddPropertyGroup(..), // but instead must do it ourselves ProjectPropertyGroupElement preAndPostBuildEvents = xmakeProject.CreatePropertyGroupElement(); xmakeProject.AppendChild(preAndPostBuildEvents); // Add the "PreBuildEvent" property. if (this.preBuildEvent != null) { // We must escape the percent-sign in order to handle cases like // "echo %DEBUGGER%". We don't want MSBuild to treat the "%DE" as // an escaped character. preAndPostBuildEvents.AddProperty(VSProjectAttributes.preBuildEvent, this.preBuildEvent.Replace("%", "%25")); } // Add the "PostBuildEvent" property. if (this.postBuildEvent != null) { // We must escape the percent-sign in order to handle cases like // "echo %DEBUGGER%". We don't want MSBuild to treat the "%DE" as // an escaped character. preAndPostBuildEvents.AddProperty(VSProjectAttributes.postBuildEvent, this.postBuildEvent.Replace("%", "%25")); } } } } /// <summary> /// Processes the &lt;Build&gt; element, and everything within it. As it is /// doing this, it will add stuff to the xmakeProject. /// </summary> /// <owner>RGoel</owner> private void ProcessBuildElement ( XmlElementWithLocation buildElement ) { // Make sure this is the <Build> element. error.VerifyThrow((buildElement != null) && (buildElement.Name == VSProjectElements.build), "Expected <Build> element."); // Make sure the caller has given us a valid xmakeProject object. error.VerifyThrow(xmakeProject != null, "Expected valid XMake project object."); // Make sure the caller has given us a valid globalPropertyGroup object. error.VerifyThrow(globalPropertyGroup != null, "Expected valid global ProjectPropertyElementGroup."); // The <Build> element should not have any attributes on it. ProjectErrorUtilities.VerifyThrowInvalidProject(!buildElement.HasAttributes, buildElement.Location, "NoAttributesExpected", VSProjectElements.build); // Loop through all the direct child elements of the <Build> element. foreach(XmlNode buildChildNode in buildElement) { // Handle XML comments under the the <Build> node (just ignore them). if ((buildChildNode.NodeType == XmlNodeType.Comment) || (buildChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (buildChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation buildChildElement = (XmlElementWithLocation)buildChildNode; switch (buildChildElement.Name) { // The <Settings> element. case VSProjectElements.settings: this.ProcessSettingsElement((XmlElementWithLocation)buildChildElement); break; // The <References> element. case VSProjectElements.references: this.ProcessReferencesElement((XmlElementWithLocation)buildChildElement); break; // The <Imports> element. case VSProjectElements.imports: this.ProcessImportsElement((XmlElementWithLocation)buildChildElement); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, buildChildElement.Location, "UnrecognizedChildElement", buildChildNode.Name, VSProjectElements.build); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(buildChildNode.Name, buildElement.Name, buildElement.Location); } } } /// <summary> /// Processes the &lt;Settings&gt; element, and everything within it. As it is /// doing this, it will add stuff to the xmakeProject. /// </summary> /// <owner>RGoel</owner> private void ProcessSettingsElement ( XmlElementWithLocation settingsElement ) { // Make sure this is the <Settings> element. error.VerifyThrow((settingsElement != null) && (settingsElement.Name == VSProjectElements.settings), "Expected <Settings> element."); // Make sure the caller has given us a valid xmakeProject object. error.VerifyThrow(xmakeProject != null, "Expected valid XMake project object."); // Make sure the caller has given us a valid globalPropertyGroup object. error.VerifyThrow(globalPropertyGroup != null, "Expected valid global ProjectPropertyElementGroup."); // All of the attributes on the <Settings> tag get converted to XMake // properties, except for PreBuildEvent and PostBuildEvent. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Settings // ApplicationIcon = "" // AssemblyKeyContainerName = "" // AssemblyName = "XMakeBuildEngine" // AssemblyOriginatorKeyFile = "" // DefaultClientScript = "JScript" // DefaultHTMLPageLayout = "Grid" // DefaultTargetSchema = "IE50" // DelaySign = "false" // OutputType = "Library" // PreBuildEvent = "" // PostBuildEvent = "..\..\PostBuildEvent.bat" // RootNamespace = "XMakeBuildEngine" // RunPostBuildEvent = "OnBuildSuccess" // StartupObject = "" // > // ... // ... // ... // </Settings> // ----------------------------------------------------------------------- // XMake format: // ============= // <PropertyGroup> // <ApplicationIcon></ApplicationIcon> // <AssemblyKeyContainerName></AssemblyKeyContainerName> // <AssemblyName>XMakeBuildEngine</AssemblyName> // <AssemblyOriginatorKeyFile></AssemblyOriginatorKeyFile> // <DefaultClientScript>JScript</DefaultClientScript> // <DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout> // <DefaultTargetSchema>IE50</DefaultTargetSchema> // <DelaySign>false</DelaySign> // <OutputType>Library</OutputType> // <RootNamespace>XMakeBuildEngine</RootNamespace> // <RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent> // <StartupObject></StartupObject> // </PropertyGroup> // ----------------------------------------------------------------------- // The "PreBuildEvent" and "PostBuildEvent" properties need to be handled // specially. These can contain references to predefined macros, such // as "$(ProjectDir)". But these get defined in Microsoft.CSharp.targets, so the // "PreBuildEvent" and "PostBuildEvent" properties need to get added to // the project file *after* the <Import> for Microsoft.CSharp.targets. For now, // just save the values of these two properties. this.preBuildEvent = settingsElement.GetAttribute(VSProjectAttributes.preBuildEvent); settingsElement.RemoveAttribute(VSProjectAttributes.preBuildEvent); this.postBuildEvent = settingsElement.GetAttribute(VSProjectAttributes.postBuildEvent); settingsElement.RemoveAttribute(VSProjectAttributes.postBuildEvent); // cache the assembly name in case its needed to upgrade the // documentation file property) this.assemblyName = settingsElement.GetAttribute(VSProjectAttributes.assemblyName); // cache the output type. this.outputType = settingsElement.GetAttribute(XMakeProjectStrings.outputType); // Take care of copying all the other normal properties. this.AddXMakePropertiesFromXMLAttributes(this.globalPropertyGroup, settingsElement); // Loop through all the direct child elements of the <Build> element. foreach(XmlNode settingsChildNode in settingsElement) { // Handle XML comments under the the <Settings> node (just ignore them). if ((settingsChildNode.NodeType == XmlNodeType.Comment) || (settingsChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (settingsChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation settingsChildElement = (XmlElementWithLocation)settingsChildNode; switch (settingsChildElement.Name) { // The <Config> element. case VSProjectElements.config: this.ProcessConfigElement(settingsChildElement); break; // In the case of a VSD project, the <Platform> element case VSProjectElements.platform: this.ProcessPlatformElement(settingsChildElement); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, settingsChildElement.Location, "UnrecognizedChildElement", settingsChildElement.Name, VSProjectElements.settings); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(settingsChildNode.Name, settingsElement.Name, settingsElement.Location); } } } /// <summary> /// Processes the &lt;Config&gt; element, and everything within it. As it is /// doing this, it will add stuff to the xmakeProject, including new /// configuration-specific property groups. /// </summary> /// <owner>RGoel</owner> private void ProcessConfigElement ( XmlElementWithLocation configElement ) { // Make sure this is the <Config> element. error.VerifyThrow((configElement != null) && (configElement.Name == VSProjectElements.config), "Expected <Config> element."); // Make sure the caller has given us a valid xmakeProject object. error.VerifyThrow(xmakeProject != null, "Expected valid XMake project object."); // All of the attributes on the <Config> tag get converted to XMake // properties, except for the "Name" attribute which becomes part of // the "Condition" on the <PropertyGroup>. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Config // Name = "Debug" // AllowUnsafeBlocks = "false" // BaseAddress = "285212672" // CheckForOverflowUnderflow = "false" // ConfigurationOverrideFile = "" // DefineConstants = "DEBUG;TRACE" // DocumentationFile = "" // DebugSymbols = "true" // FileAlignment = "4096" // IncrementalBuild = "true" // NoStdLib = "false" // NoWarn = "" // Optimize = "false" // OutputPath = "bin\Debug\" // RegisterForComInterop = "false" // RemoveIntegerChecks = "false" // TreatWarningsAsErrors = "true" // WarningLevel = "4" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> // <AllowUnsafeBlocks>false</AllowUnsafeBlocks> // <BaseAddress>285212672</BaseAddress> // <CheckForOverflowUnderflow>false</CheckForOverflowUnderflow> // <ConfigurationOverrideFile></ConfigurationOverrideFile> // <DefineConstants>DEBUG;TRACE</DefineConstants> // <DocumentationFile></DocumentationFile> // <DebugSymbols>true</DebugSymbols> // <FileAlignment>4096</FileAlignment> // <NoStdLib>false</NoStdLib> // <NoWarn></NoWarn> // <Optimize>false</Optimize> // <OutputPath>bin\Debug\</OutputPath> // <RegisterForComInterop>false</RegisterForComInterop> // <RemoveIntegerChecks>false</RemoveIntegerChecks> // <TreatWarningsAsErrors>true</TreatWarningsAsErrors> // <WarningLevel>4</WarningLevel> // </PropertyGroup> // ----------------------------------------------------------------------- // Get the "Name" attribute of the <Config> element. string configName = configElement.GetAttribute(VSProjectAttributes.name); ProjectErrorUtilities.VerifyThrowInvalidProject((configName != null) && (configName.Length > 0), configElement.Location, "MissingAttribute", VSProjectElements.config, VSProjectAttributes.name); // In the case of VSD projects, the "Name" attribute will have a pipe in it, // followed by the device platform. This last part needs to be removed, // leaving just the config name. if ( ( this.language == VSProjectElements.ECSharp ) || ( this.language == VSProjectElements.EVisualBasic ) ) { int pipeLocation = configName.IndexOf ( '|' ); if ( pipeLocation != -1 ) { configName = configName.Remove ( pipeLocation, configName.Length - pipeLocation ); } } // Remove the "Name" attribute from the <Config> element, so it doesn't get // added as an XMake property. configElement.RemoveAttribute(VSProjectAttributes.name); // PPD@31111: J# Only: We need to remove the AdditionalOptions attribute // (and note it down) before we create the property group out of the configElement string additionalOptionsValue = null; if (VSProjectElements.visualJSharp == this.language) { additionalOptionsValue = configElement.GetAttribute(VSProjectAttributes.additionalOptions); // Dont bother about getting a null value for additionalOptionsValue // GetAttribute return String.Empty if the attribute is not present configElement.RemoveAttribute(VSProjectAttributes.additionalOptions); } // Create a new property group, and add all of the XML attributes as XMake // properties. ProjectPropertyGroupElement configPropertyGroup = xmakeProject.AddPropertyGroup(); // Process OutputPath attribute separately to ensure it contains trailing backslash string outputPath = configElement.GetAttribute(VSProjectAttributes.outputPath); if (outputPath != null && outputPath.Length > 0) { if (outputPath[outputPath.Length-1] != Path.DirectorySeparatorChar) outputPath += Path.DirectorySeparatorChar; configElement.RemoveAttribute(VSProjectAttributes.outputPath); configPropertyGroup.AddProperty(VSProjectAttributes.outputPath, ProjectCollection.Escape(outputPath)); } // If the "SelectedDevice" or "DeploymentPlatform" attributes exist in the per-user // project file, we should get rid of them. string selectedDevice = configElement.GetAttribute ( VSProjectAttributes.selectedDevice ); if ( isUserFile && ( selectedDevice != null ) && ( selectedDevice.Length > 0 ) ) { configElement.RemoveAttribute ( VSProjectAttributes.selectedDevice ); } string deploymentPlatform = configElement.GetAttribute ( VSProjectAttributes.deploymentPlatform ); if ( isUserFile && ( deploymentPlatform != null ) && ( deploymentPlatform.Length > 0 ) ) { configElement.RemoveAttribute ( VSProjectAttributes.deploymentPlatform ); } // Get rid of the "IncrementalBuild" attribute string incrementalBuild = configElement.GetAttribute ( VSProjectAttributes.incrementalBuild ); if (incrementalBuild != null && incrementalBuild.Length > 0) { configElement.RemoveAttribute ( VSProjectAttributes.incrementalBuild ); } // VSWhidbey bug 261464. For VB projects migrated from VS7/Everett, the VB team would // like to enable XML documentation by default (this feature was unavailable to VB users // in VS7/Everett. To enable for VB, set the DocumentationFile property to <assemblyname>.xml if ((!this.isUserFile) && (VSProjectElements.visualBasic == this.language)) { string documentationFile = this.assemblyName + XMakeProjectStrings.xmlFileExtension; configPropertyGroup.AddProperty(VSProjectAttributes.documentationFile, ProjectCollection.Escape(documentationFile)); } // process the rest of Config attributes this.AddXMakePropertiesFromXMLAttributes(configPropertyGroup, configElement); // PPD@31111: J# Only: We now need to parse the additionalOptionsValue for properties and // add the individual properties to configPropertyGroup. // This needs to be done after the AddXMakePropertiesFromXMLAttributes call above since // an property defined in the AdditionalOptions takes precedence. if (VSProjectElements.visualJSharp == this.language) { AdditionalOptionsParser addnlOptParser = new AdditionalOptionsParser(); addnlOptParser.ProcessAdditionalOptions(additionalOptionsValue, configPropertyGroup); } // VSWhidbey bug 302946. For VB projects migrated from VS7/Everett, the VB team would // like to disable the following new warnings for Whidbey: 42016,42017,42018,42019,42032 // New projects created in Whidbey already have these warnings disabled by default. if ((!this.isUserFile) && (VSProjectElements.visualBasic == this.language)) { configPropertyGroup.AddProperty(XMakeProjectStrings.noWarn, XMakeProjectStrings.disabledVBWarnings); } // VSWhidbey bug 472064. For all projects that are converted, if "DebugSymbols" is set for a // particular platform/configuration, we set a "DebugType" property if and only if "DebugType" property // is not already there. DebugType is set to "full" for DebugSymbols=true, DebugType is set to "none" // if DebugSymbols=false, and we don't do anything if DebugSymbols is not present in the source project. if (!this.isUserFile) { string debugType = configElement.GetAttribute(VSProjectAttributes.debugType); if (String.IsNullOrEmpty(debugType)) { string debugSymbols = configElement.GetAttribute(XMakeProjectStrings.debugSymbols); if ( 0 == String.Compare ( debugSymbols, "true", StringComparison.OrdinalIgnoreCase ) ) { configPropertyGroup.AddProperty(VSProjectAttributes.debugType, VSProjectAttributes.debugTypeFull); } else if ( 0 == String.Compare(debugSymbols, "false", StringComparison.OrdinalIgnoreCase) ) { configPropertyGroup.AddProperty(VSProjectAttributes.debugType, VSProjectAttributes.debugTypeNone); } } } // VSWhidbey bug 472064. For all VC# projects that are converted, we add an ErrorReport // property, always set to "prompt" if ( !this.isUserFile && this.language == VSProjectElements.cSharp ) { configPropertyGroup.AddProperty(VSProjectAttributes.errorReport, VSProjectAttributes.errorReportPrompt); } // Platform of course depends on the language we are dealing with - J# in whidbey supports only x86 string platform = (this.language != VSProjectElements.visualJSharp) ? XMakeProjectStrings.defaultPlatform : XMakeProjectStrings.x86Platform; // Add the "Condition" to the new <PropertyGroup>. configPropertyGroup.Condition = XMakeProjectStrings.configplatformPrefix + ProjectCollection.Escape(configName) + XMakeProjectStrings.configplatformSeparator + ProjectCollection.Escape(platform) + XMakeProjectStrings.configplatformSuffix; // Loop through all the direct child elements of the <Config> element. foreach(XmlNode configChildNode in configElement) { // Handle XML comments under the the <Config> node (just ignore them). if ((configChildNode.NodeType == XmlNodeType.Comment) || (configChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (configChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation configChildElement = (XmlElementWithLocation)configChildNode; switch (configChildElement.Name) { // The <InteropRegistration> element. case VSProjectElements.interopRegistration: this.ProcessInteropRegistrationElement((XmlElementWithLocation)configChildElement, configPropertyGroup); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, configChildElement.Location, "UnrecognizedChildElement", configChildElement.Name, VSProjectElements.config); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(configChildNode.Name, configElement.Name, configElement.Location); } } } /// <summary> /// Processes the &lt;Platform&gt; element, and everything within it. As it is /// doing this, it will add stuff to the xmakeProject, including new /// configuration-specific property groups. /// </summary> /// <owner>BCham</owner> private void ProcessPlatformElement ( XmlElementWithLocation platformElement ) { if ( !IsUserFile ) { // Make sure this is the <Platform> element. error.VerifyThrow((platformElement != null) && (platformElement.Name == VSProjectElements.platform), "Expected <Platform> element."); // Make sure the caller has given us a valid xmakeProject object. error.VerifyThrow(xmakeProject != null, "Expected valid XMake project object."); // The platform listed in the <Platform> element will be the platform // used for the Whidbey project. // ----------------------------------------------------------------------- // Everett format: // =============== // <Platform Name = "Pocket PC" /> // ----------------------------------------------------------------------- // XMake format: // ============= // <PropertyGroup> // <Property PlatformFamilyName="PocketPC"/> // <Property PlatformID="3C41C503-53EF-4c2a-8DD4-A8217CAD115E"/> // </PropertyGroup> // ----------------------------------------------------------------------- // Get the "Name" attribute of the <Platform> element. platformForVSD = platformElement.GetAttribute(VSProjectAttributes.name); ProjectErrorUtilities.VerifyThrowInvalidProject((platformForVSD != null) && (platformForVSD.Length > 0), platformElement.Location, "MissingAttribute", VSProjectElements.platform, VSProjectAttributes.name); // Create a new property group, and add all of the XML attributes as XMake // properties. ProjectPropertyGroupElement platformPropertyGroup = xmakeProject.AddPropertyGroup(); string platformID; string platformFamily; frameworkVersionForVSD = XMakeProjectStrings.vOne; switch ( platformForVSD ) { case VSProjectElements.PocketPC: platformID = "3C41C503-53EF-4c2a-8DD4-A8217CAD115E"; platformFamily = "PocketPC"; break; case VSProjectElements.Smartphone: platformID = "4DE813A2-67E0-4a00-945C-3188240A8243"; platformFamily = "Smartphone"; break; case VSProjectElements.WindowsCE: default: // If we're dealing with a platform other than the three that Everett ships with, we'll assign it as Windows CE platformID = "E2BECB1F-8C8C-41ba-B736-9BE7D946A398"; platformFamily = "WindowsCE"; // We don't ship with a v1.0 WindowsCE platform. Default to v2.0 instead. frameworkVersionForVSD = XMakeProjectStrings.vTwo; break; } // Add the properties for PlatformID and PlatformFamilyName platformPropertyGroup.AddProperty(XMakeProjectStrings.platformID, platformID); platformPropertyGroup.AddProperty(XMakeProjectStrings.platformFamilyName, platformFamily); // Since we're here, we know this is a VSD project. Therefore, let's // add a property for the deployment target path. Note, we only need a suffix. // The prefix will be defaulted to based on the selected device. platformPropertyGroup.AddProperty(XMakeProjectStrings.deployTargetSuffix, "$(AssemblyName)" ); // And, we should also set the Target Framework version. For // VSD projects, we want to stay with v1.0 platformPropertyGroup.AddProperty(XMakeProjectStrings.TargetFrameworkVersion, frameworkVersionForVSD); } } /// <summary> /// Processes the &lt;InteropRegistration&gt; element, and everything within it. /// As it is doing this, it will add extra properties to the configuration's /// property group. /// </summary> /// <owner>RGoel</owner> private void ProcessInteropRegistrationElement ( XmlElementWithLocation interopRegistrationElement, ProjectPropertyGroupElement configPropertyGroup ) { // Make sure this is the <InteropRegistration> element. error.VerifyThrow((interopRegistrationElement != null) && (interopRegistrationElement.Name == VSProjectElements.interopRegistration), "Expected <InteropRegistration> element."); // Make sure we've been given a valid configuration property group. error.VerifyThrow(configPropertyGroup != null, "Expected configuration's property group."); // All of the attributes on the <InteropRegistration> tag get converted to XMake // properties. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Config // ... // ... // ... <all other configuration properties> // ... // ... // > // <InteropRegistration // RegisteredComClassic = "true" // RegisteredOutput = "Project1.dll" // RegisteredTypeLib = "Project1.tlb" // /> // </Config> // ----------------------------------------------------------------------- // XMake format: // ============= // <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> // ... // ... // ... <all other configuration properties> // ... // ... // <RegisteredComClassic>true</RegisteredComClassic> // <RegisteredOutput>Project1.dll</RegisteredOutput> // <RegisteredTypeLib>Project1.tlb</RegisteredTypeLib> // </PropertyGroup> // ----------------------------------------------------------------------- this.AddXMakePropertiesFromXMLAttributes(configPropertyGroup, interopRegistrationElement); // There should be no children of the <InteropRegistration> element. ProjectXmlUtilities.VerifyThrowProjectNoChildElements(interopRegistrationElement); } /// <summary> /// Processes the &lt;References&gt; element, and everything within it. As it is /// doing this, it will add reference items to a new ProjectItemGroupElement. /// </summary> /// <owner>RGoel</owner> private void ProcessReferencesElement ( XmlElementWithLocation referencesElement ) { // Make sure this is the <References> element. error.VerifyThrow((referencesElement != null) && (referencesElement.Name == VSProjectElements.references), "Expected <References> element."); // Make sure the caller has given us a valid xmakeProject object. error.VerifyThrow(xmakeProject != null, "Expected valid XMake project object."); // The <References> tag should have no attributes. ProjectErrorUtilities.VerifyThrowInvalidProject(!referencesElement.HasAttributes, referencesElement.Location, "NoAttributesExpected", VSProjectElements.references); // Before we begin processing the individual references, let's make sure // we have an SLN file, so we can go look up the project-to-project references. // If the caller has not provided us with an SLN file, or if the SLN provided // doesn't actually exist on disk yet (which can happen in VS IDE scenarios because // the SLN is only in-memory and hasn't been saved yet), then we search for the // SLN using a heuristic. if (this.solutionFile == null || !File.Exists(this.solutionFile)) { this.solutionFile = null; this.SearchForSolutionFile(); } else { // We've been given a valid SLN file that exists on disk, so just parse // it. this.solution = new SolutionFile(); this.solution.FullPath = this.solutionFile; this.solution.ParseSolutionFileForConversion(); this.conversionWarnings.AddRange(this.solution.SolutionParserWarnings); } ProjectItemGroupElement referencesItemGroup = null; // Loop through all the direct child elements of the <References> element. foreach(XmlNode referencesChildNode in referencesElement) { // Handle XML comments under the the <References> node (just ignore them). if ((referencesChildNode.NodeType == XmlNodeType.Comment) || (referencesChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (referencesChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation referencesChildElement = (XmlElementWithLocation)referencesChildNode; switch (referencesChildElement.Name) { // The <Reference> element. case VSProjectElements.reference: if (referencesItemGroup == null) { referencesItemGroup = xmakeProject.AddItemGroup(); } this.ProcessReferenceElement(referencesChildElement, referencesItemGroup); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, referencesChildElement.Location, "UnrecognizedChildElement", referencesChildElement.Name, VSProjectElements.references); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(referencesChildNode.Name, referencesElement.Name, referencesElement.Location); } } } /// <summary> /// Processes the &lt;Reference&gt; element, and add an appropriate reference /// items to the referencesItemGroup. /// </summary> /// <owner>RGoel</owner> private void ProcessReferenceElement ( XmlElementWithLocation referenceElement, ProjectItemGroupElement referencesItemGroup ) { // Make sure this is the <Reference> element. error.VerifyThrow((referenceElement != null) && (referenceElement.Name == VSProjectElements.reference), "Expected <Reference> element."); // Make sure the caller has already created an ProjectItemGroupElement for us to // put the new items in. error.VerifyThrow(referencesItemGroup != null, "Received null ProjectItemGroupElement"); // Before we do anything else, look for the "Platform" attribute. // If it's available, we need to remove it, and if it ends in // "-Designer", we need to disregard this reference entirely. string platform = referenceElement.GetAttribute(VSProjectAttributes.platform); if ((platform != null) && (platform.Length > 0)) { if (platform.IndexOf("-Designer", 0, platform.Length, StringComparison.Ordinal) != -1) { return; } referenceElement.RemoveAttribute ( VSProjectAttributes.platform ); } ProjectItemElement newReferenceItem; // Get the "Name" attribute. This is a required attribute in the VS7/ // Everett format. string referenceName = referenceElement.GetAttribute(VSProjectAttributes.name); ProjectErrorUtilities.VerifyThrowInvalidProject((referenceName != null) && (referenceName.Length > 0), referenceElement.Location, "MissingAttribute", VSProjectAttributes.name, VSProjectElements.reference); // Before we go any further, we must special-case some assemblies for VSD projects. if ( ( ( this.language == VSProjectElements.ECSharp ) || ( this.language == VSProjectElements.EVisualBasic ) ) ) { if ( ( this.frameworkVersionForVSD == XMakeProjectStrings.vTwo ) && ( 0 == String.Compare ( referenceName, VSProjectElements.SystemDataCommon, StringComparison.OrdinalIgnoreCase ) ) ) { // We need to remove all references to "System.Data.Common" for VSD projects only. // Note : We only want to do this for projects that will be updated to v2.0 // System.Data.Common is still valid for v1.0 upgraded projects. return; } else if ( 0 == String.Compare ( referenceName, VSProjectElements.SystemSR, StringComparison.OrdinalIgnoreCase ) ) { // We always want to remove all references to "System.SR" return; } } if ( ( this.language == VSProjectElements.EVisualBasic ) && ( 0 == String.Compare ( referenceName, VSProjectElements.MSCorLib, StringComparison.OrdinalIgnoreCase ) ) ) { // We also want to get rid of all 'mscorlib' references for VB projects only. return; } // We need to find out what type of reference this is -- a .NET assembly // reference, a COM reference, or a project reference. In the XMake format, // we use separate item types for each of these. // See if there's a "Guid" attribute on the <Reference> element. If so, // it's a classic COM reference. string comReferenceGuid = referenceElement.GetAttribute(VSProjectAttributes.guid); // See if there's a "Project" guid attribute. If so, it's a project // reference. string referencedProjectGuid = referenceElement.GetAttribute(VSProjectAttributes.project); if ((comReferenceGuid != null) && (comReferenceGuid.Length > 0) && (comReferenceGuid != "{00000000-0000-0000-0000-000000000000}")) { newReferenceItem = ConvertClassicComReference(referenceElement, referencesItemGroup, referenceName); } else if ((referencedProjectGuid != null) && (referencedProjectGuid.Length > 0)) { newReferenceItem = ConvertProjectToProjectReference(referenceElement, referencesItemGroup, referenceName, ref referencedProjectGuid); } else { newReferenceItem = ConvertAssemblyReference(referenceElement, referencesItemGroup, referenceName); } // Add all the rest of the attributes on the <Reference> element to the new // XMake item. foreach (XmlAttribute referenceAttribute in referenceElement.Attributes) { newReferenceItem.AddMetadata(referenceAttribute.Name, ProjectCollection.Escape(referenceAttribute.Value)); } // There should be no children of the <Reference> element. ProjectXmlUtilities.VerifyThrowProjectNoChildElements(referenceElement); } /// <summary> /// Given an element corresponding to a COM reference, create the appropriate element in the new project /// </summary> /// <param name="referenceElement"></param> /// <param name="referencesItemGroup"></param> /// <param name="referenceName"></param> /// <returns></returns> private static ProjectItemElement ConvertClassicComReference(XmlElementWithLocation referenceElement, ProjectItemGroupElement referencesItemGroup, string referenceName) { ProjectItemElement newReferenceItem; // This is a classic COM reference. // This gets added as a new XMake item of type "COMReference". // The "Include" attribute will contain the reference name, // and all the other attributes remain the same. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Reference // Name = "UTILITIESLib" // Guid = "{0EF79DA1-6555-11D2-A889-00AA006C2A9A}" // VersionMajor = "1" // VersionMinor = "0" // Lcid = "0" // WrapperTool = "tlbimp" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <COMReference Include = "UTILITIESLib"> // <Guid>{0EF79DA1-6555-11D2-A889-00AA006C2A9A}</Guid> // <VersionMajor>1</VersionMajor> // <VersionMinor>0</VersionMinor> // <Lcid>0</Lcid> // <WrapperTool>tlbimp</WrapperTool> // </COMReference> // ----------------------------------------------------------------------- // Remove the "Name" attribute so we don't add it again at the end. referenceElement.RemoveAttribute(VSProjectAttributes.name); // Add a new item to XMake of type "COMReference". newReferenceItem = referencesItemGroup.AddItem(XMakeProjectStrings.comReference, ProjectCollection.Escape(referenceName)); return newReferenceItem; } /// <summary> /// Given an element corresponding to a P2P reference, create the appropriate element in the new project /// </summary> /// <param name="referenceElement"></param> /// <param name="referencesItemGroup"></param> /// <param name="referenceName"></param> /// <param name="referencedProjectGuid"></param> /// <returns></returns> private ProjectItemElement ConvertProjectToProjectReference(XmlElementWithLocation referenceElement, ProjectItemGroupElement referencesItemGroup, string referenceName, ref string referencedProjectGuid) { ProjectItemElement newReferenceItem; // This is a project-to-project reference. // This gets added as a new XMake item of type "ProjectReference". // The "Include" attribute should be the relative path from the // current project to the referenced project file. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Reference // Name = "XMakeTasks" // Project = "{44342961-78F4-4F98-AFD6-720DA6E648A2}" // Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <ProjectReference Include = "..\XMakeTasks\XMakeTasks.csproj"> // <Name>XMakeTasks</Name> // <Project>{44342961-78F4-4F98-AFD6-720DA6E648A2}</Project> // <Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package> // </ProjectReference> // ----------------------------------------------------------------------- // Apparently, sometimes project reference guids contain additional goo with relative project path. // Just strip it off. The project system does the same thing, and by doing this early we make // sure that we have the correct guid attribute in the project file and ResolveNonMSBuildReferences // does not complain about invalid characters there which causes all the references to fail to resolve. int barIndex = referencedProjectGuid.IndexOf('|'); if (barIndex != -1) { referencedProjectGuid = referencedProjectGuid.Remove(barIndex); referenceElement.SetAttribute(VSProjectAttributes.project, referencedProjectGuid); } string pathToReferencedProject = this.GetRelativePathToReferencedProject(referencedProjectGuid); if (pathToReferencedProject != null) { // For VSD Projects, we want to transform all Everett ( .csdproj & .vbdproj ) project 2 project references into // Whidbey ( .csproj & .vbproj ) references. if (0 == String.Compare(Path.GetExtension(pathToReferencedProject), XMakeProjectStrings.csdprojFileExtension, StringComparison.OrdinalIgnoreCase)) { pathToReferencedProject = Path.ChangeExtension(pathToReferencedProject, XMakeProjectStrings.csprojFileExtension); } else if (0 == String.Compare(Path.GetExtension(pathToReferencedProject), XMakeProjectStrings.vbdprojFileExtension, StringComparison.OrdinalIgnoreCase)) { pathToReferencedProject = Path.ChangeExtension(pathToReferencedProject, XMakeProjectStrings.vbprojFileExtension); } } // Add a new item to XMake of type "ProjectReference". If we were able to find // the relative path to the project, use it for the "Include", otherwise just use // the project name. string value = (pathToReferencedProject != null) ? pathToReferencedProject : referenceName; newReferenceItem = referencesItemGroup.AddItem(XMakeProjectStrings.projectReference, ProjectCollection.Escape(value)); return newReferenceItem; } /// <summary> /// Given an element corresponding to a .NET Assembly reference, create the appropriate element in the new project /// </summary> /// <param name="referenceElement"></param> /// <param name="referencesItemGroup"></param> /// <param name="referenceName"></param> /// <returns></returns> private ProjectItemElement ConvertAssemblyReference(XmlElementWithLocation referenceElement, ProjectItemGroupElement referencesItemGroup, string referenceName) { ProjectItemElement newReferenceItem; // This is a regular .NET assembly reference. // This gets added as a new XMake item of type "Reference". The "Include" // attribute is the assembly name, and all the other attributes remain // the same. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Reference // Name = "System.Xml" // AssemblyName = "System.Xml" // HintPath = "..\..\binaries\x86chk\bin\i386\System.Xml.dll" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <Reference Include="System.Xml"> // <Name>System.Xml</Name> // <HintPath>..\..\binaries\x86chk\bin\i386\System.Xml.dll</HintPath> // </Reference> // ----------------------------------------------------------------------- // Get the "AssemblyName" attribute. If not found, just use the value from the // "Name" attribute. This is what the project loading code does in VS. string assemblyName = referenceElement.GetAttribute(VSProjectAttributes.assemblyName); if ((assemblyName == null) || (assemblyName.Length == 0)) { assemblyName = referenceName; } else { // Remove the "AssemblyName" attribute so we don't add it again at // the end. referenceElement.RemoveAttribute(VSProjectAttributes.assemblyName); } // MyType should only be added when System.Windows.Forms is present. If this // reference is seen, then set a flag so we can later add MyType. if (0 == String.Compare("System.Windows.Forms", assemblyName, StringComparison.OrdinalIgnoreCase)) { hasWindowsFormsReference = true; } // Remove hint paths that we think are to RTM or Everett framework assemblies string hintPath = referenceElement.GetAttribute(VSProjectAttributes.hintPath); if (hintPath != null) { hintPath = hintPath.ToUpper(CultureInfo.InvariantCulture); if (hintPath.IndexOf(LegacyFrameworkPaths.RTMFrameworkPath, StringComparison.Ordinal) != -1 || hintPath.IndexOf(LegacyFrameworkPaths.EverettFrameworkPath, StringComparison.Ordinal) != -1 || hintPath.IndexOf(LegacyFrameworkPaths.JSharpRTMFrameworkPath, StringComparison.Ordinal) != -1) { referenceElement.RemoveAttribute(VSProjectAttributes.hintPath); } } newReferenceItem = referencesItemGroup.AddItem(XMakeProjectStrings.reference, ProjectCollection.Escape(assemblyName)); return newReferenceItem; } /// <summary> /// To convert project-to-project references correctly, we need some data /// out of the solution file. If we weren't given a solution file, then /// we search the project's directory and every parent directory all the /// way up to the root for the corresponding SLN file. /// </summary> /// <owner>RGoel</owner> private void SearchForSolutionFile ( ) { error.VerifyThrow(this.solutionFile == null, "Solution file already passed in!"); error.VerifyThrow(this.projectGuid != null, "Need project Guid to find solution file."); // Start by looking for a solution file in the directory of the original project file. DirectoryInfo searchDirectory = new DirectoryInfo(Path.GetDirectoryName(Path.GetFullPath(this.oldProjectFile))); while (searchDirectory != null) { // Get a list of all the .SLN files in the current search directory. FileInfo[] slnFiles = searchDirectory.GetFiles("*.sln"); // Open each .SLN file and parse it. We're searching for a .SLN // file that contains the current project that we're converting. foreach (FileInfo slnFile in slnFiles) { // Check that the extension really is ".SLN", because the above call to // GetFiles will also return files such as blah.SLN1 and bloo.SLN2. if (0 == String.Compare(".sln", slnFile.Extension, StringComparison.OrdinalIgnoreCase)) { // Parse the .SLN file. SolutionFile solutionParser = new SolutionFile(); solutionParser.FullPath = slnFile.FullName; try { solutionParser.ParseSolutionFile(); this.conversionWarnings.AddRange(solutionParser.SolutionParserWarnings); // Determine if our current project guid (for the project we're converting) // is listed in the .SLN file. if (solutionParser.GetProjectUniqueNameByGuid(this.projectGuid) != null) { // If we found our project listed, then this is the solution we will // use to help us convert the project-to-project references. this.solutionFile = slnFile.FullName; this.solution = solutionParser; return; } } catch (InvalidProjectFileException) { // If the SLN wasn't valid, that's fine ... just skip it, and // move on to the next one. } } } // Go up one directory, and search there. Stop when we hit the root. searchDirectory = searchDirectory.Parent; } // If we don't find a solution file that contains our project, that's okay... // we can still proceed. It just means that the converted project-to-project // references won't have the relative path to the referenced project. This // may prevent command-line builds from being fully functional, but it's // not the end of the world. } /// <summary> /// Given a 'from' path and a 'to' path, compose a relative path from 'from' /// to 'to'. /// </summary> /// <owner>jomof</owner> internal static string RelativePathTo(string from, string to) { error.VerifyThrow(from.IndexOf("*", StringComparison.Ordinal) == -1, "Bug: RelativePathTo can't handle wild cards."); error.VerifyThrow(to.IndexOf("*", StringComparison.Ordinal) == -1, "Bug: RelativePathTo can't handle wild cards."); from = Path.GetFullPath(from); to = Path.GetFullPath(to); Uri uriFrom = new Uri(from); Uri uriTo = new Uri(to); Uri relative = uriFrom.MakeRelativeUri(uriTo); string result = Uri.UnescapeDataString(relative.ToString()); // The URI class returns forward slashes instead of backslashes. Replace // them now, and return the final path. result = result.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); return result; } /// <summary> /// Given a project guid for a referenced project, this method computes /// the relative path to that referenced project file from the current /// project file that is being converted. In order to do this, we need /// some information out of the SLN file. /// </summary> /// <owner>RGoel</owner> private string GetRelativePathToReferencedProject ( string referencedProjectGuid ) { error.VerifyThrow(referencedProjectGuid != null, "Need valid project guid."); // If we don't have a pointer to the SLN file that contains this project, // then we really have no hope of finding the relative path to the // referenced project. if (this.solution == null) { // Log a warning that indicates that the complete solution file was not used string warning = ResourceUtilities.FormatString( AssemblyResources.GetString("CouldNotFindCompleteSolutionFile"), referencedProjectGuid); conversionWarnings.Add(warning); return null; } // Find the referenced project guid in the SLN file. string relativePathFromSolutionToReferencedProject = this.solution.GetProjectRelativePathByGuid(referencedProjectGuid); if (relativePathFromSolutionToReferencedProject == null) { // If the referenced project does not exist in the solution, we can't // get its relative path. This is not a conversion error; it just means // the converted project file won't have the relative path to the // referenced project. This may prevent some command-line build // scenarios from working completely. string warning = ResourceUtilities.FormatString( AssemblyResources.GetString("ProjectNotListingInSolutionFile"), referencedProjectGuid, this.solution.FullPath); conversionWarnings.Add(warning); return null; } if (relativePathFromSolutionToReferencedProject.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { // We've discovered a P2P reference to a web project. This feature is no // longer supported in Whidbey. We will remove the // P2P reference to the web project and issue a warning into the upgrade log // telling the user he needs to fix this up himself. string warning = ResourceUtilities.FormatString( AssemblyResources.GetString("UnsupportedProjectToProjectWebReference"), relativePathFromSolutionToReferencedProject); conversionWarnings.Add(warning); return null; } // Get the full path to the referenced project. Compute this by combining // the full path to the SLN file with the relative path specified within // the SLN file. string fullPathToReferencedProject = Path.Combine( Path.GetDirectoryName(this.solutionFile), relativePathFromSolutionToReferencedProject); // Now compute the relative path from the current project to the referenced // project. return RelativePathTo(this.oldProjectFile, fullPathToReferencedProject); } /// <summary> /// Processes the &lt;Imports&gt; element, and everything within it. As it is /// doing this, it will add "Import" items to a new ProjectItemGroupElement. /// </summary> /// <owner>RGoel</owner> private void ProcessImportsElement ( XmlElementWithLocation importsElement ) { // Make sure this is the <Imports> element. error.VerifyThrow((importsElement != null) && (importsElement.Name == VSProjectElements.imports), "Expected <Imports> element."); // Make sure the caller gave us a valid xmakeProject to stuff // our new items into. error.VerifyThrow(xmakeProject != null, "Expected valid xmake project object."); // The <Imports> tag should have no attributes. ProjectErrorUtilities.VerifyThrowInvalidProject(!importsElement.HasAttributes, importsElement.Location, "NoAttributesExpected", VSProjectElements.imports); ProjectItemGroupElement importsItemGroup = null; // Loop through all the direct child elements of the <Imports> element. foreach(XmlNode importsChildNode in importsElement) { // Handle XML comments under the the <Imports> node (just ignore them). if ((importsChildNode.NodeType == XmlNodeType.Comment) || (importsChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (importsChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation importsChildElement = (XmlElementWithLocation)importsChildNode; switch (importsChildNode.Name) { // The <Import> element. case VSProjectElements.import: if (importsItemGroup == null) { importsItemGroup = xmakeProject.AddItemGroup(); } this.ProcessImportElement((XmlElementWithLocation)importsChildElement, importsItemGroup); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, importsChildElement.Location, "UnrecognizedChildElement", importsChildElement.Name, VSProjectElements.imports); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(importsChildNode.Name, importsElement.Name, importsElement.Location); } } } /// <summary> /// Processes the &lt;Import&gt; element, and add an appropriate reference /// items to the importsItemGroup. /// </summary> /// <owner>RGoel</owner> private void ProcessImportElement ( XmlElementWithLocation importElement, ProjectItemGroupElement importsItemGroup ) { // Make sure this is the <Import> element. error.VerifyThrow((importElement != null) && (importElement.Name == VSProjectElements.import), "Expected <Import> element."); // Make sure the caller has already created an ProjectItemGroupElement for us to // put the new items in. error.VerifyThrow(importsItemGroup != null, "Received null ProjectItemGroupElement"); // Get the required "Namespace" attribute. string importNamespace = importElement.GetAttribute(VSProjectAttributes.importNamespace); ProjectErrorUtilities.VerifyThrowInvalidProject((importNamespace != null) && (importNamespace.Length > 0), importElement.Location, "MissingAttribute", VSProjectAttributes.importNamespace, VSProjectElements.import); // Remove the "Namespace" attribute, so it doesn't show up in our loop later. importElement.RemoveAttribute(VSProjectAttributes.importNamespace); // The <Import> element gets converted to XMake as an item of type "Import". // The "Namespace" attribute becomes the "Include" for the new item. For // example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Import Namespace = "System.Collections" /> // ----------------------------------------------------------------------- // XMake format: // ============= // <Import Include="System.Collections" /> // ----------------------------------------------------------------------- importsItemGroup.AddItem(XMakeProjectStrings.import, ProjectCollection.Escape(importNamespace)); // There should be no other attributes on the <Import> element (besides // "Namespace" which we already took care of). But loop through them // anyway, so we can emit a useful error message. foreach (XmlAttributeWithLocation importAttribute in importElement.Attributes) { ProjectErrorUtilities.VerifyThrowInvalidProject(false, importAttribute.Location, "UnrecognizedAttribute", importAttribute.Name, VSProjectElements.import); } // There should be no children of the <Import> element. ProjectXmlUtilities.VerifyThrowProjectNoChildElements(importElement); } /// <summary> /// Processes the &lt;Files&gt; element, and everything within it. As it is /// doing this, it will add the appropriate items to a new ProjectItemGroupElement. /// </summary> /// <owner>RGoel</owner> private void ProcessFilesElement ( XmlElementWithLocation filesElement ) { // Make sure this is the <Files> element. error.VerifyThrow((filesElement != null) && (filesElement.Name == VSProjectElements.files), "Expected <Files> element."); // Make sure the caller gave us a valid xmakeProject to stuff // our new items into. error.VerifyThrow(xmakeProject != null, "Expected valid xmake project object."); // The <Files> tag should have no attributes. ProjectErrorUtilities.VerifyThrowInvalidProject(!filesElement.HasAttributes, filesElement.Location, "NoAttributesExpected", VSProjectElements.files); // Loop through all the direct child elements of the <Files> element. foreach(XmlNode filesChildNode in filesElement) { // Handle XML comments under the the <Files> node (just ignore them). if ((filesChildNode.NodeType == XmlNodeType.Comment) || (filesChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (filesChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation filesChildElement = (XmlElementWithLocation)filesChildNode; switch (filesChildNode.Name) { // The <Include> element. case VSProjectElements.include: this.ProcessIncludeElement(filesChildElement); break; // The <Exclude> element. Actually, the <Exclude> element is not supported // by VS. That is, VS completely ignores anything under the <Exclude> // element. Yet, some really old project files have this tag in there, // even though it doesn't do anything. So let's at least not fail if // the project file contains this. case VSProjectElements.exclude: string warning = AssemblyResources.GetString("ExcludeFoundInProject"); conversionWarnings.Add(warning); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, filesChildElement.Location, "UnrecognizedChildElement", filesChildNode.Name, VSProjectElements.files); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(filesChildNode.Name, filesElement.Name, filesElement.Location); } } } /// <summary> /// Processes the &lt;Include&gt; element, and everything within it. As it is /// doing this, it will add the appropriate items to a new ProjectItemGroupElement. /// </summary> /// <owner>RGoel</owner> private void ProcessIncludeElement ( XmlElementWithLocation includeElement ) { // Make sure this is the <Include> element. error.VerifyThrow((includeElement != null) && (includeElement.Name == VSProjectElements.include), "Expected <Include> element."); // Make sure the caller gave us a valid xmakeProject to stuff // our new items into. error.VerifyThrow(xmakeProject != null, "Expected valid xmake project object."); // The <Include> tag should have no attributes. ProjectErrorUtilities.VerifyThrowInvalidProject(!includeElement.HasAttributes, includeElement.Location, "NoAttributesExpected", VSProjectElements.include); ProjectItemGroupElement filesItemGroup = null; // Loop through all the direct child elements of the <Include> element. foreach(XmlNode includeChildNode in includeElement) { // Handle XML comments under the the <Include> node (just ignore them). if ((includeChildNode.NodeType == XmlNodeType.Comment) || (includeChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (includeChildNode.NodeType == XmlNodeType.Element) { if (filesItemGroup == null) { filesItemGroup = xmakeProject.AddItemGroup(); } XmlElementWithLocation includeChildElement = (XmlElementWithLocation)includeChildNode; switch (includeChildElement.Name) { // The <File> element. case VSProjectElements.file: this.ProcessFileElement(includeChildElement, filesItemGroup); break; // The <Folder> element. case VSProjectElements.folder: this.ProcessFolderElement(includeChildElement, filesItemGroup); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, includeChildElement.Location, "UnrecognizedChildElement", includeChildNode.Name, VSProjectElements.include); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(includeChildNode.Name, includeElement.Name, includeElement.Location); } } } /// <summary> /// Processes the &lt;File&gt; element, and adds an appropriate item to the /// filesItemGroup. /// </summary> /// <owner>RGoel</owner> private void ProcessFileElement ( XmlElementWithLocation fileElement, ProjectItemGroupElement filesItemGroup ) { // Make sure this is the <File> element. error.VerifyThrow((fileElement != null) && (fileElement.Name == VSProjectElements.file), "Expected <File> element."); // Make sure the caller has already created an ProjectItemGroupElement for us to // put the new items in. error.VerifyThrow(filesItemGroup != null, "Received null ProjectItemGroupElement"); // Get the required "RelPath" attribute. string relPath = fileElement.GetAttribute(VSProjectAttributes.relPath); ProjectErrorUtilities.VerifyThrowInvalidProject((relPath != null) && (relPath.Length > 0), fileElement.Location, "MissingAttribute", VSProjectAttributes.relPath, VSProjectElements.file); // Remove the "RelPath" attribute, so we don't end up adding it twice. fileElement.RemoveAttribute(VSProjectAttributes.relPath); // Get the "Link" attribute. This is for linked items only. string linkPath = fileElement.GetAttribute(VSProjectAttributes.link); // Remove the "Link" attribute, so we don't end up adding it twice. fileElement.RemoveAttribute(VSProjectAttributes.link); // Get the "BuildAction" attribute. If it doesn't exist, figure out // what the build action is based on the file extension. This is // what the project loading code does in VS. string buildAction = fileElement.GetAttribute(VSProjectAttributes.buildAction); if ((buildAction == null) || (buildAction.Length == 0)) { buildAction = VSProjectAttributes.buildActionNone; } // Remove the "BuildAction" attribute, so we don't end up adding it twice. fileElement.RemoveAttribute(VSProjectAttributes.buildAction); ProjectItemElement newFileItem; // Bug Whidbey #248965. If a .resx file is completely empty, do not include a reference // to it in the upgraded project file. if (! (0 == String.Compare(Path.GetExtension(relPath), ".resx", StringComparison.OrdinalIgnoreCase) && IsFilePresentButEmpty(relPath, linkPath)) ) { // Add the new item to XMake. if ((linkPath == null) || (linkPath.Length == 0)) { // Normal item. // The <File> element gets converted to XMake as a new item, where // the item type is the BuildAction, and the "Include" contains // the relative path to the item. For // example, // ----------------------------------------------------------------------- // Everett format: // =============== // <File // RelPath = "Properties\PropertyGroupCollection.cs" // SubType = "Code" // BuildAction = "Compile" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <Compile Include = "Properties\PropertyGroupCollection.cs"> // <SubType>Code</SubType> // </Compile> // ----------------------------------------------------------------------- newFileItem = filesItemGroup.AddItem(buildAction, ProjectCollection.Escape(relPath)); } else { // Linked item. // The <File> element gets converted to XMake as a new item, where // the item type is the BuildAction, the "Include" contains // the physical relative path to the item, and the non-XMake "Link" // attribute contains the project-relative path for item (for display // purposes in the Solution Explorer). For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <File // RelPath = "Properties\PropertyGroupCollection.cs" // Link = "c:\Rajeev\External\PropertyGroupCollection.cs" // SubType = "Code" // BuildAction = "Compile" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <Compile Include = "c:\Rajeev\External\PropertyGroupCollection.cs"> // <Link>Properties\PropertyGroupCollection.cs</Link> // <SubType>Code</SubType> // </Compile> // ----------------------------------------------------------------------- newFileItem = filesItemGroup.AddItem(buildAction, ProjectCollection.Escape(linkPath)); newFileItem.AddMetadata(XMakeProjectStrings.link, ProjectCollection.Escape(relPath)); } // Add all the rest of the attributes on the <File> element to the new // XMake item. foreach (XmlAttribute fileAttribute in fileElement.Attributes) { newFileItem.AddMetadata(fileAttribute.Name, ProjectCollection.Escape(fileAttribute.Value)); } // If this is a VSD(devices) project and we're dealing with a content file, // mark it to copy if newer. if ( ( ( ( this.language == VSProjectElements.ECSharp ) || ( this.language == VSProjectElements.EVisualBasic ) ) ) && ( 0 == String.Compare ( buildAction, XMakeProjectStrings.content, StringComparison.OrdinalIgnoreCase ) ) ) { newFileItem.AddMetadata ( XMakeProjectStrings.copytooutput, XMakeProjectStrings.preservenewest ); } } else { string warning = ResourceUtilities.FormatString( AssemblyResources.GetString("EmptyResxRemoved"), relPath); conversionWarnings.Add(warning); } // There should be no children of the <File> element. ProjectXmlUtilities.VerifyThrowProjectNoChildElements(fileElement); } /// <summary> /// Checks whether a file has content. If it is empty, returns true. /// If file does not exist we may be waiting for it to download asynchronously /// via source control so return false to leave it in the project /// </summary> /// <owner>danmose</owner> private bool IsFilePresentButEmpty(string relPath, string linkPath) { // relpath is the filename // linkPath, if it exists, is the relative path from the project, or the absolute full path string path; if (linkPath == null || linkPath.Length == 0) { path = Path.Combine(Path.GetDirectoryName(oldProjectFile), relPath); } else { if (Path.IsPathRooted(linkPath)) // absolute { path = linkPath; } else // relative { path = Path.Combine(Path.GetDirectoryName(oldProjectFile), linkPath); } } if (!File.Exists(path)) { // File does not exist - may be waiting to be download asynchronously via source control // so return false to leave it in the project return false; } long length = 0; try { FileInfo fi = new FileInfo(path); length = fi.Length; } catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(e)) throw; // if we can't say for sure it's empty, play safe and return false return false; } return (length == 0); } /// <summary> /// Processes the &lt;Folder&gt; element, and adds an appropriate item to the /// filesItemGroup. /// </summary> /// <owner>RGoel</owner> private void ProcessFolderElement ( XmlElementWithLocation folderElement, ProjectItemGroupElement filesItemGroup ) { // Make sure this is the <Folder> element. error.VerifyThrow((folderElement != null) && (folderElement.Name == VSProjectElements.folder), "Expected <Folder> element."); // Make sure the caller has already created an ProjectItemGroupElement for us to // put the new items in. error.VerifyThrow(filesItemGroup != null, "Received null ProjectItemGroupElement"); // Get the required "RelPath" attribute. string relPath = folderElement.GetAttribute(VSProjectAttributes.relPath); ProjectErrorUtilities.VerifyThrowInvalidProject((relPath != null) && (relPath.Length > 0), folderElement.Location, "MissingAttribute", VSProjectAttributes.relPath, VSProjectElements.folder); // Remove the "RelPath" attribute, so we don't end up adding it twice. folderElement.RemoveAttribute(VSProjectAttributes.relPath); // We need to find out what type of folder this is -- a web references // folder, a web reference URL, or just an empty project folder. // See if there's a "WebReferences" attribute on the <Folder> element. If so, // and the value is set to "True", then it's a web reference folder. string webReferences = folderElement.GetAttribute(VSProjectAttributes.webReferences); // Remove the "WebReferences" attribute, so we don't end up adding it twice. folderElement.RemoveAttribute(VSProjectAttributes.webReferences); // See if there's a "WebReferenceURL" attribute. If so, it's a web reference // URL. string webReferenceUrl = folderElement.GetAttribute(VSProjectAttributes.webReferenceUrl); // Remove the "WebReferenceURL" attribute, so we don't end up adding it twice. folderElement.RemoveAttribute(VSProjectAttributes.webReferenceUrl); ProjectItemElement newFolderItem; if ((webReferences != null) && (0 == String.Compare(webReferences, "true", StringComparison.OrdinalIgnoreCase))) { // This is a web reference folder. // The <Folder> element gets converted to XMake as an item of type // "WebReferences". The "Include" will contain the relative path. // For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Folder // RelPath = "Web References\" // WebReferences = "TRUE" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <WebReferences Include = "Web References\" /> // ----------------------------------------------------------------------- newFolderItem = filesItemGroup.AddItem(XMakeProjectStrings.webReferences, ProjectCollection.Escape(relPath)); } else if ((webReferenceUrl != null) && (webReferenceUrl.Length > 0)) { // This is an actual web reference URL. // The <Folder> element gets converted to XMake as an item of type // "WebReferenceURL". The "Include" will contain the URL. // For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Folder // RelPath = "Web References\mobileakipman\" // WebReferenceUrl = "http://mobileakipman/HelloName/service1.asmx" // UrlBehavior = "Static" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <WebReferenceUrl Include="http://mobileakipman/HelloName/service1.asmx"> // <RelPath>Web References\mobileakipman\</RelPath> // <UrlBehavior>Static</UrlBehavior> // </WebReferenceUrl> // ----------------------------------------------------------------------- newFolderItem = filesItemGroup.AddItem(XMakeProjectStrings.webReferenceUrl, ProjectCollection.Escape(webReferenceUrl)); newFolderItem.AddMetadata(XMakeProjectStrings.relPath, ProjectCollection.Escape(relPath)); // Whidbey projects have some new properties to control the behavior of the // proxy generation. For projects migrated from Everett, we want to force // the proxy generation to mimic the Everett behavior, so that people's projects // still work the same as they did in Everett. (These properties did not // exist in Everett.) See spec at: // http://devdiv/SpecTool/Documents/Whidbey/VSCore/Solution%20Project%20Build/FeatureSpecs/Project-WebReferences.doc if (!this.newWebReferencePropertiesAdded) { this.globalPropertyGroup.AddProperty(XMakeProjectStrings.webRefEnableProperties, (this.language == VSProjectElements.visualJSharp) ? "false" : "true"); this.globalPropertyGroup.AddProperty(XMakeProjectStrings.webRefEnableSqlTypes, "false"); this.globalPropertyGroup.AddProperty(XMakeProjectStrings.webRefEnableLegacyEventing, "true"); this.newWebReferencePropertiesAdded = true; } } else { // This is just a project folder that happens not to have any files in it. // The <Folder> element gets converted to XMake as an item of type "Folder". // However, we do need to remove the trailing backslash, because XMake // interprets that as a recursion (bug # 58591). For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Folder // RelPath = "MyEmptyProjectFolder\" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <Folder Include="MyEmptyProjectFolder" /> // ----------------------------------------------------------------------- // Remove the trailing backslash. XMake interprets trailing backslashes // as a recursive wildcard. This will be fixed in M2 -- bug # 58591 if (relPath.EndsWith("\\", StringComparison.Ordinal)) { relPath = relPath.Remove(relPath.Length - 1, 1); } newFolderItem = filesItemGroup.AddItem(XMakeProjectStrings.folder, ProjectCollection.Escape(relPath)); } // Add all the rest of the attributes on the <Folder> element to the new // XMake item. foreach (XmlAttribute folderAttribute in folderElement.Attributes) { newFolderItem.AddMetadata(folderAttribute.Name, ProjectCollection.Escape(folderAttribute.Value)); } // There should be no children of the <Folder> element. ProjectXmlUtilities.VerifyThrowProjectNoChildElements(folderElement); } /// <summary> /// Processes the &lt;StartupServices&gt; element, and everything within it. As /// it is doing this, it will add new "StartupService" items to a new ProjectItemGroupElement. /// </summary> /// <owner>RGoel</owner> private void ProcessStartupServicesElement ( XmlElementWithLocation startupServicesElement ) { // Make sure this is the <StartupServices> element. error.VerifyThrow((startupServicesElement != null) && (startupServicesElement.Name == VSProjectElements.startupServices), "Expected <StartupServices> element."); // Make sure the caller gave us a valid xmakeProject to stuff // our new items into. error.VerifyThrow(xmakeProject != null, "Expected valid xmake project object."); // The <StartupServices> tag should have no attributes. ProjectErrorUtilities.VerifyThrowInvalidProject(!startupServicesElement.HasAttributes, startupServicesElement.Location, "NoAttributesExpected", VSProjectElements.startupServices); ProjectItemGroupElement startupServicesItemGroup = null; // Loop through all the direct child elements of the <StartupServices> element. foreach(XmlNode startupServicesChildNode in startupServicesElement) { // Handle XML comments under the the <StartupServices> node (just ignore them). if ((startupServicesChildNode.NodeType == XmlNodeType.Comment) || (startupServicesChildNode.NodeType == XmlNodeType.Whitespace)) { continue; } if (startupServicesChildNode.NodeType == XmlNodeType.Element) { XmlElementWithLocation startupServicesChildElement = (XmlElementWithLocation)startupServicesChildNode; switch (startupServicesChildElement.Name) { // The <Service> element. case VSProjectElements.service: if (startupServicesItemGroup == null) { startupServicesItemGroup = xmakeProject.AddItemGroup(); } this.ProcessServiceElement(startupServicesChildElement, startupServicesItemGroup); break; default: ProjectErrorUtilities.VerifyThrowInvalidProject(false, startupServicesChildElement.Location, "UnrecognizedChildElement", startupServicesChildNode.Name, VSProjectElements.startupServices); break; } } else { ProjectXmlUtilities.ThrowProjectInvalidChildElement(startupServicesChildNode.Name, startupServicesElement.Name, startupServicesElement.Location); } } } /// <summary> /// Processes the &lt;Service&gt; element, and add an appropriate reference /// items to the startupServicesItemGroup. /// </summary> /// <owner>RGoel</owner> private void ProcessServiceElement ( XmlElementWithLocation serviceElement, ProjectItemGroupElement startupServicesItemGroup ) { // Make sure this is the <Service> element. error.VerifyThrow((serviceElement != null) && (serviceElement.Name == VSProjectElements.service), "Expected <Service> element."); // Make sure the caller has already created an ProjectItemGroupElement for us to // put the new items in. error.VerifyThrow(startupServicesItemGroup != null, "Received null ProjectItemGroupElement"); // Get the required "ID" attribute. string id = serviceElement.GetAttribute(VSProjectAttributes.id); ProjectErrorUtilities.VerifyThrowInvalidProject((id != null) && (id.Length > 0), serviceElement.Location, "MissingAttribute", VSProjectAttributes.id, VSProjectElements.service); // Remove the "ID" attribute, so it doesn't show up in our loop later. serviceElement.RemoveAttribute(VSProjectAttributes.id); // The <Service> element gets converted to XMake as an item of type "Service". // The "ID" attribute becomes the "Include" for the new item. For // example, // ----------------------------------------------------------------------- // Everett format: // =============== // <Service ID = "ABCD1234-78F4-4F98-AFD6-720DA6E648A2" /> // ----------------------------------------------------------------------- // XMake format: // ============= // <Service Include="ABCD1234-78F4-4F98-AFD6-720DA6E648A2" /> // ----------------------------------------------------------------------- startupServicesItemGroup.AddItem(XMakeProjectStrings.service, ProjectCollection.Escape(id)); // There should be no other attributes on the <Service> element (besides // "ID" which we already took care of). But loop through them // anyway, so we can emit a useful error message. foreach (XmlAttributeWithLocation serviceAttribute in serviceElement.Attributes) { ProjectErrorUtilities.VerifyThrowInvalidProject(false, serviceAttribute.Location, "UnrecognizedAttribute", serviceAttribute.Name, VSProjectElements.service); } // There should be no children of the <Service> element. ProjectXmlUtilities.VerifyThrowProjectNoChildElements(serviceElement); } /// <summary> /// Processes the &lt;OtherProjectSettings&gt; element, and everything within it. /// As it is doing this, it will add stuff to the globalPropertyGroup. /// </summary> /// <owner>RGoel</owner> private void ProcessOtherProjectSettingsElement ( XmlElementWithLocation otherProjectSettingsElement ) { // Make sure this is the <OtherProjectSettings> element. error.VerifyThrow((otherProjectSettingsElement != null) && (otherProjectSettingsElement.Name == VSProjectElements.otherProjectSettings), "Expected <Settings> element."); // Make sure the caller gave us a valid globalPropertyGroup to stuff // our properties into. error.VerifyThrow(globalPropertyGroup != null, "Expected valid global ProjectPropertyElementGroup."); // All of the attributes on the <Settings> tag get converted to XMake // properties. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <OtherProjectSettings // CopyProjectDestinationFolder = "" // CopyProjectUncPath = "" // CopyProjectOption = "0" // ProjectView = "ProjectFiles" // ProjectTrust = "0" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <PropertyGroup> // <CopyProjectDestinationFolder></CopyProjectDestinationFolder> // <CopyProjectUncPath></CopyProjectUncPath> // <CopyProjectOption>0</CopyProjectOption> // <ProjectView>ProjectFiles</ProjectView> // <ProjectTrust>0</ProjectTrust> // </PropertyGroup> // ----------------------------------------------------------------------- this.AddXMakePropertiesFromXMLAttributes(this.globalPropertyGroup, otherProjectSettingsElement); // There should be no children of the <OtherProjectSettings> element. ProjectXmlUtilities.VerifyThrowProjectNoChildElements(otherProjectSettingsElement); } /// <summary> /// Processes the &lt;UserProperties&gt; element, and everything within it. /// Basically, this element and its contents end up going verbatim into /// the &lt;ProjectExtensions&gt; section of the newly converted MSBuild project /// file. /// /// The one slight exception is that we do something special for Trinity /// conversion. Specifically, if we detect that this is a White Rabbit /// project, we add the flavor GUID for Triumph. /// </summary> /// <param name="userPropertiesElement"></param> /// <param name="isTriumphProject"></param> /// <owner>rgoel</owner> private void ProcessUserPropertiesElement ( XmlElementWithLocation userPropertiesElement, out bool isTriumphProject ) { // Make sure this is the <UserProperties> element. error.VerifyThrow((userPropertiesElement != null) && (userPropertiesElement.Name == VSProjectElements.userProperties), "Expected <UserProperties> element."); isTriumphProject = false; // All of the <UserProperties> node goes into the <ProjectExtensions> section // verbatim. The one exception is that if we detect a White Rabbit project, // then we add the flavor GUID for Triumph. For example, // ----------------------------------------------------------------------- // Everett format: // =============== // <UserProperties // OfficeDocumentPath = ".\ExcelProject41.xls" // OfficeDocumentType = "XLS" // OfficeProject = "true" // blun="1" // bloo="2" // blee="3" // /> // ----------------------------------------------------------------------- // XMake format: // ============= // <Project> // // <PropertyGroup> // ... // <ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> // ... // </PropertyGroup> // ... // <ProjectExtensions> // // <VisualStudio> // // <UserProperties // OfficeDocumentPath = ".\ExcelProject41.xls" // OfficeDocumentType = "XLS" // OfficeProject = "true" // blun="1" // bloo="2" // blee="3" // /> // // <CommonProperties> // <FL_B3B1084D_C66C_4F4C_B279_5C1BA6092AFB> // <FL_FAE04EC0_301F_11D3_BF4B_00C04F79EFBC /> // </FL_B3B1084D_C66C_4F4C_B279_5C1BA6092AFB> // </CommonProperties> // // </VisualStudio> // // </ProjectExtensions> // // </Project> // ----------------------------------------------------------------------- string visualStudioProjectExtensions = GetProjectExtensionsString(XMakeProjectStrings.visualStudio); visualStudioProjectExtensions += userPropertiesElement.OuterXml; // If there are any attributes on the <UserProperties> element that indicate that // this was a White Rabbit project, add the Triumph flavor GUID. if ( (userPropertiesElement.Attributes[VSProjectAttributes.officeDocumentPath] != null) || (userPropertiesElement.Attributes[VSProjectAttributes.officeDocumentType] != null) || (userPropertiesElement.Attributes[VSProjectAttributes.officeProject] != null) ) { isTriumphProject = true; // We need the language-specific Guid as well. string languageGuid = String.Empty; if (this.language == VSProjectElements.cSharp) { languageGuid = XMakeProjectStrings.cSharpGuid; } else if (this.language == VSProjectElements.visualBasic) { languageGuid = XMakeProjectStrings.visualBasicGuid; } else if (this.language == VSProjectElements.visualJSharp) { languageGuid = XMakeProjectStrings.visualJSharpGuid; } else { error.VerifyThrow(false, "This project is not recognized as one of the following 3 languages: C#, VB, VJ#"); } // Add a new global property called ProjectTypeGuids. this.globalPropertyGroup.AddProperty(XMakeProjectStrings.projectTypeGuids, "{" + XMakeProjectStrings.triumphProjectTypeGuid + "};{" + languageGuid + "}"); // Add the Office document as a "None" item in the converted project file. XmlAttribute officeDocumentPathAttribute = userPropertiesElement.Attributes[VSProjectAttributes.officeDocumentPath]; if (officeDocumentPathAttribute != null) { string officeDocumentPath = officeDocumentPathAttribute.Value; if ((officeDocumentPath != null) && (officeDocumentPath.Length > 0)) { string projectFileDirectory = Path.GetDirectoryName(Path.GetFullPath(this.oldProjectFile)); string officeDocumentFullPath = Path.GetFullPath(Path.Combine(projectFileDirectory, officeDocumentPath)); // If the office document is in the project directory ... if (0 == String.Compare(projectFileDirectory, Path.GetDirectoryName(officeDocumentFullPath), StringComparison.OrdinalIgnoreCase)) { // If the office document actually exists on disk ... if (File.Exists(officeDocumentFullPath)) { // Add the office document as a "None" item to the converted project. ProjectItemGroupElement officeDocumentItemGroup = this.xmakeProject.AddItemGroup(); officeDocumentItemGroup.AddItem("None", ProjectCollection.Escape(officeDocumentPath)); } } } } } SetProjectExtensionsString(XMakeProjectStrings.visualStudio, visualStudioProjectExtensions); } /// <summary> /// Fix hard-coded fully qualified paths in Code Analysis properties. /// /// Due to a bug in Whidbey configuration cloning, some Code Analysis /// properties in Whidbey project files contain fully qualified paths. /// They need to be detected and removed during project conversion so /// that Code Analysis will work on converted Whidbey projects. /// </summary> /// <owner>duanek</owner> /// <returns>true if changes were required, false otherwise</returns> // ----------------------------------------------------------------------- // XMake format: // ============= // <Project> // ... // <PropertyGroup> // ... // <CodeAnalysisRuleAssemblies>C:\Program Files\Microsoft Visual Studio 8\Team Tools\Static Analysis Tools\FxCop\\rules</CodeAnalysisRuleAssemblies> // ... // </PropertyGroup> // ... // </Project> // ----------------------------------------------------------------------- private bool FixCodeAnalysisPaths() { bool changedProject = false; // Iterate over all <PropertyGroup> nodes // Look for a <CodeAnalysisRuleAssemblies> node foreach (ProjectPropertyElement ProjectPropertyElement in xmakeProject.Properties) { if (ProjectPropertyElement.Name == XMakeProjectStrings.codeAnalysisRuleAssemblies) { // We do not want to blindly remove this property since it // is valid for the user to modify it in the project file. // The default value in Microsoft.CodeAnalysis.Targets // is a rooted path ending in "FxCop\\rules". if (Path.IsPathRooted(ProjectPropertyElement.Value)) { if (ProjectPropertyElement.Value.EndsWith(@"FxCop\\rules", StringComparison.Ordinal)) { ProjectPropertyElement.Parent.RemoveChild(ProjectPropertyElement); changedProject = true; } } break; } } return changedProject; } /// <summary> /// Find the first property with the provided name in the ProjectRootElement. /// If none is found, returns null. /// </summary> private ProjectPropertyElement FindPropertyIfPresent(ProjectRootElement project, string name) { foreach (ProjectPropertyElement property in project.Properties) { if (String.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase)) { return property; } } return null; } /// <summary> /// Get the project extensions string with a particular ID, /// or empty string if it does not exist or there is no project extensions at all /// </summary> private string GetProjectExtensionsString(string id) { ProjectExtensionsElement element = xmakeProject.ProjectExtensions; return (element == null) ? String.Empty : element[id]; } /// <summary> /// Set a project extensions string with the provided Id, /// even if there is no project extensions tag at present /// </summary> private void SetProjectExtensionsString(string id, string content) { ProjectExtensionsElement element = xmakeProject.ProjectExtensions; if (element == null) { element = xmakeProject.CreateProjectExtensionsElement(); xmakeProject.AppendChild(element); } element[id] = content; } } }
49.939256
219
0.553424
[ "MIT" ]
3F/IeXod
src/Deprecated/Conversion/ProjectFileConverter.cs
197,310
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using Azure.Core; using Azure.Identity; using Microsoft.Extensions.Configuration; namespace Microsoft.Extensions.Azure { internal static class ClientFactory { private const string ServiceVersionParameterTypeName = "ServiceVersion"; private const string ConnectionStringParameterName = "connectionString"; public static object CreateClient(Type clientType, Type optionsType, object options, IConfiguration configuration, TokenCredential credential) { List<object> arguments = new List<object>(); // Handle single values as connection strings if (configuration is IConfigurationSection section && section.Value != null) { var connectionString = section.Value; configuration = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair<string, string>(ConnectionStringParameterName, connectionString) }) .Build(); } foreach (var constructor in clientType.GetConstructors().OrderByDescending(c => c.GetParameters().Length)) { if (!IsApplicableConstructor(constructor, optionsType)) { continue; } arguments.Clear(); bool match = true; foreach (var parameter in constructor.GetParameters()) { if (IsCredentialParameter(parameter)) { if (credential == null) { match = false; break; } arguments.Add(credential); continue; } if (IsOptionsParameter(parameter, optionsType)) { break; } if (!TryConvertArgument(configuration, parameter.Name, parameter.ParameterType, out object argument)) { match = false; break; } arguments.Add(argument); } if (!match) { continue; } arguments.Add(options); return constructor.Invoke(arguments.ToArray()); } throw new InvalidOperationException(BuildErrorMessage(configuration, clientType, optionsType)); } internal static TokenCredential CreateCredential(IConfiguration configuration, TokenCredentialOptions identityClientOptions = null) { var credentialType = configuration["credential"]; var clientId = configuration["clientId"]; var tenantId = configuration["tenantId"]; var resourceId = configuration["managedIdentityResourceId"]; var clientSecret = configuration["clientSecret"]; var certificate = configuration["clientCertificate"]; var certificateStoreName = configuration["clientCertificateStoreName"]; var certificateStoreLocation = configuration["clientCertificateStoreLocation"]; if (string.Equals(credentialType, "managedidentity", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(resourceId)) { throw new ArgumentException("Cannot specify both 'clientId' and 'UserAssignedManagedIdentityResourceId'"); } if (!string.IsNullOrWhiteSpace(resourceId)) { return new ManagedIdentityCredential(new ResourceIdentifier(resourceId)); } return new ManagedIdentityCredential(clientId); } if (!string.IsNullOrWhiteSpace(tenantId) && !string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(clientSecret)) { return new ClientSecretCredential(tenantId, clientId, clientSecret, identityClientOptions); } if (!string.IsNullOrWhiteSpace(tenantId) && !string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(certificate)) { StoreLocation storeLocation = StoreLocation.CurrentUser; if (!string.IsNullOrWhiteSpace(certificateStoreLocation)) { storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), certificateStoreLocation, true); } if (string.IsNullOrWhiteSpace(certificateStoreName)) { certificateStoreName = "MY"; // MY is the default used in X509Store } using var store = new X509Store(certificateStoreName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificate, false); if (certs.Count == 0) { throw new InvalidOperationException($"Unable to find a certificate with thumbprint '{certificate}'"); } var credential = new ClientCertificateCredential(tenantId, clientId, certs[0], identityClientOptions); store.Close(); return credential; } // TODO: More logging return null; } internal static object CreateClientOptions(object version, Type optionsType) { ConstructorInfo parameterlessConstructor = null; int versionParameterIndex = 0; object[] constructorArguments = null; foreach (var constructor in optionsType.GetConstructors()) { var parameters = constructor.GetParameters(); if (parameters.Length == 0) { parameterlessConstructor = constructor; continue; } bool allParametersHaveDefaultValue = true; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameter = parameters[i]; if (parameter.HasDefaultValue) { if (IsServiceVersionParameter(parameter)) { versionParameterIndex = i; } } else { allParametersHaveDefaultValue = false; break; } } if (allParametersHaveDefaultValue) { constructorArguments = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { constructorArguments[i] = parameters[i].DefaultValue; } } } if (version != null) { if (constructorArguments != null) { constructorArguments[versionParameterIndex] = version; return Activator.CreateInstance(optionsType, constructorArguments); } throw new InvalidOperationException("Unable to find constructor that takes service version"); } if (parameterlessConstructor != null) { return Activator.CreateInstance(optionsType); } return Activator.CreateInstance(optionsType, constructorArguments); } private static bool IsServiceVersionParameter(ParameterInfo parameter) => parameter.ParameterType.Name == ServiceVersionParameterTypeName; private static bool IsCredentialParameter(ParameterInfo parameter) { return parameter.ParameterType == typeof(TokenCredential); } private static bool IsOptionsParameter(ParameterInfo parameter, Type optionsType) { return parameter.ParameterType.IsAssignableFrom(optionsType) && parameter.Position == ((ConstructorInfo)parameter.Member).GetParameters().Length - 1; } private static string BuildErrorMessage(IConfiguration configuration, Type clientType, Type optionsType) { var builder = new StringBuilder(); void TrimTrailingDelimiter() { while (builder[builder.Length - 1] is '/' or ',' or ' ') { builder.Length--; } } builder.Append("Unable to find matching constructor while trying to create an instance of ").Append(clientType.Name).AppendLine("."); builder.AppendLine("Expected one of the follow sets of configuration parameters:"); int counter = 1; foreach (var constructor in clientType.GetConstructors()) { if (!IsApplicableConstructor(constructor, optionsType)) { continue; } builder.Append(counter).Append(". "); foreach (var parameter in constructor.GetParameters()) { if (IsOptionsParameter(parameter, optionsType)) { break; } if (parameter.ParameterType is { IsClass: true } parameterType && parameterType != typeof(string) && parameterType != typeof(Uri)) { foreach (var parameterConstructor in GetApplicableParameterConstructors(parameterType)) { foreach (var parameterConstructorParameter in parameterConstructor.GetParameters()) { builder .Append(parameter.Name) .Append(':') .Append(parameterConstructorParameter.Name) .Append(", "); } TrimTrailingDelimiter(); builder.Append('/'); } TrimTrailingDelimiter(); } else { builder.Append(parameter.Name); } builder.Append(", "); } TrimTrailingDelimiter(); builder.AppendLine(); counter++; } builder.AppendLine(); builder.Append("Found the following configuration keys: "); foreach (var child in configuration.AsEnumerable(true)) { builder.Append(child.Key).Append(", "); } TrimTrailingDelimiter(); return builder.ToString(); } private static bool IsApplicableConstructor(ConstructorInfo constructorInfo, Type optionsType) { var parameters = constructorInfo.GetParameters(); return constructorInfo.IsPublic && parameters.Length > 0 && IsOptionsParameter(parameters[parameters.Length - 1], optionsType); } private static bool TryConvertArgument(IConfiguration configuration, string parameterName, Type parameterType, out object value) { if (parameterType == typeof(string)) { return TryConvertFromString(configuration, parameterName, s => s, out value); } if (parameterType == typeof(Uri)) { return TryConvertFromString(configuration, parameterName, s => new Uri(s), out value); } if (parameterType == typeof(Guid)) { return TryConvertFromString(configuration, parameterName, s => Guid.Parse(s), out value); } return TryCreateObject(parameterType, configuration.GetSection(parameterName), out value); } private static bool TryConvertFromString(IConfiguration configuration, string parameterName, Func<string, object> func, out object value) { string stringValue = configuration[parameterName]; if (stringValue == null) { value = null; return false; } value = func(stringValue); return true; } internal static bool TryCreateObject(Type type, IConfigurationSection configuration, out object value) { if (!configuration.GetChildren().Any()) { value = null; return false; } List<object> arguments = new List<object>(); foreach (var constructor in GetApplicableParameterConstructors(type)) { arguments.Clear(); bool match = true; foreach (var parameter in constructor.GetParameters()) { if (!TryConvertArgument(configuration, parameter.Name, parameter.ParameterType, out object argument)) { match = false; break; } arguments.Add(argument); } if (!match) { continue; } value = constructor.Invoke(arguments.ToArray()); return true; } value = null; return false; } private static IOrderedEnumerable<ConstructorInfo> GetApplicableParameterConstructors(Type type) { return type.GetConstructors(BindingFlags.Public | BindingFlags.Instance).OrderByDescending(c => c.GetParameters().Length); } } }
36.90932
150
0.524193
[ "MIT" ]
v-kaifazhang/azure-sdk-for-net
sdk/extensions/Microsoft.Extensions.Azure/src/Internal/ClientFactory.cs
14,655
C#
using Xunit; namespace Algorithm.BasicDataStructure { public class PriorityQueueTest { [Fact] void PriorityQueue() { var pq = new PriorityQueue<int>(); pq.Enqueue(5); pq.Enqueue(1); pq.Enqueue(7); pq.Enqueue(3); Assert.Equal(4, pq.Count); Assert.Equal(1, pq.Peek()); Assert.Equal(1, pq.Dequeue()); Assert.Equal(3, pq.Dequeue()); Assert.Equal(5, pq.Dequeue()); Assert.Equal(7, pq.Dequeue()); } } }
23.04
46
0.486111
[ "MIT" ]
AreTrash/CompetitiveProgrammingSnippets
CompetitiveProgrammingSnippets.Test/Algorithm/BasicDataStructure/PriorityQueueTest.cs
578
C#
using System; using System.Collections.Generic; using System.ComponentModel; using Mirror.RemoteCalls; using UnityEngine; namespace Mirror { public enum SyncMode { Observers, Owner } /// <summary>Base class for networked components.</summary> [AddComponentMenu("")] [RequireComponent(typeof(NetworkIdentity))] [HelpURL("https://mirror-networking.gitbook.io/docs/guides/networkbehaviour")] public abstract class NetworkBehaviour : MonoBehaviour { /// <summary>sync mode for OnSerialize</summary> // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. [Tooltip("By default synced data is sent from the server to all Observers of the object.\nChange this to Owner to only have the server update the client that has ownership authority for this object")] [HideInInspector] public SyncMode syncMode = SyncMode.Observers; /// <summary>sync interval for OnSerialize (in seconds)</summary> // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. // [0,2] should be enough. anything >2s is too laggy anyway. [Tooltip("Time in seconds until next change is synchronized to the client. '0' means send immediately if changed. '0.5' means only send changes every 500ms.\n(This is for state synchronization like SyncVars, SyncLists, OnSerialize. Not for Cmds, Rpcs, etc.)")] [Range(0, 2)] [HideInInspector] public float syncInterval = 0.1f; internal double lastSyncTime; /// <summary>True if this object is on the server and has been spawned.</summary> // This is different from NetworkServer.active, which is true if the // server itself is active rather than this object being active. public bool isServer => netIdentity.isServer; /// <summary>True if this object is on the client and has been spawned by the server.</summary> public bool isClient => netIdentity.isClient; /// <summary>True if this object is the the client's own local player.</summary> public bool isLocalPlayer => netIdentity.isLocalPlayer; /// <summary>True if this object is on the server-only, not host.</summary> public bool isServerOnly => netIdentity.isServerOnly; /// <summary>True if this object is on the client-only, not host.</summary> public bool isClientOnly => netIdentity.isClientOnly; /// <summary>This returns true if this object is the authoritative version of the object in the distributed network application.</summary> // keeping this ridiculous summary as a reminder of a time long gone... public bool hasAuthority => netIdentity.hasAuthority; /// <summary>The unique network Id of this object (unique at runtime).</summary> public uint netId => netIdentity.netId; /// <summary>Client's network connection to the server. This is only valid for player objects on the client.</summary> public NetworkConnection connectionToServer => netIdentity.connectionToServer; /// <summary>Server's network connection to the client. This is only valid for player objects on the server.</summary> public NetworkConnection connectionToClient => netIdentity.connectionToClient; // SyncLists, SyncSets, etc. protected readonly List<SyncObject> syncObjects = new List<SyncObject>(); // NetworkBehaviourInspector needs to know if we have SyncObjects internal bool HasSyncObjects() => syncObjects.Count > 0; // NetworkIdentity based values set from NetworkIdentity.Awake(), // which is way more simple and way faster than trying to figure out // component index from in here by searching all NetworkComponents. /// <summary>Returns the NetworkIdentity of this object</summary> public NetworkIdentity netIdentity { get; internal set; } /// <summary>Returns the index of the component on this object</summary> public int ComponentIndex { get; internal set; } // to avoid fully serializing entities every time, we have two options: // * run a delta compression algorithm // -> for fixed size types this is as easy as varint(b-a) for all // -> for dynamically sized types like strings this is not easy. // algorithms need to detect inserts/deletions, i.e. Myers Diff. // those are very cpu intensive and barely fast enough for large // scale multiplayer games (in Unity) // * or we use dirty bits as meta data about which fields have changed // -> spares us from running delta algorithms // -> still supports dynamically sized types // // 64 bit mask, tracking up to 64 SyncVars. protected ulong syncVarDirtyBits { get; private set; } // 64 bit mask, tracking up to 64 sync collections (internal for tests). // internal for tests, field for faster access (instead of property) // TODO 64 SyncLists are too much. consider smaller mask later. internal ulong syncObjectDirtyBits; // Weaver replaces '[SyncVar] int health' with 'Networkhealth' property. // setter calls the hook if value changed. // if we then modify the [SyncVar] from inside the setter, // the setter would call the hook and we deadlock. // hook guard prevents that. ulong syncVarHookGuard; // USED BY WEAVER to set syncvars in host mode without deadlocking protected bool GetSyncVarHookGuard(ulong dirtyBit) => (syncVarHookGuard & dirtyBit) != 0UL; // Deprecated 2021-09-16 (old weavers used it) [Obsolete("Renamed to GetSyncVarHookGuard (uppercase)")] protected bool getSyncVarHookGuard(ulong dirtyBit) => GetSyncVarHookGuard(dirtyBit); // USED BY WEAVER to set syncvars in host mode without deadlocking protected void SetSyncVarHookGuard(ulong dirtyBit, bool value) { // set the bit if (value) syncVarHookGuard |= dirtyBit; // clear the bit else syncVarHookGuard &= ~dirtyBit; } // Deprecated 2021-09-16 (old weavers used it) [Obsolete("Renamed to SetSyncVarHookGuard (uppercase)")] protected void setSyncVarHookGuard(ulong dirtyBit, bool value) => SetSyncVarHookGuard(dirtyBit, value); /// <summary>Set as dirty so that it's synced to clients again.</summary> // these are masks, not bit numbers, ie. 110011b not '2' for 2nd bit. public void SetSyncVarDirtyBit(ulong dirtyBit) { syncVarDirtyBits |= dirtyBit; } // Deprecated 2021-09-19 [Obsolete("SetDirtyBit was renamed to SetSyncVarDirtyBit because that's what it does")] public void SetDirtyBit(ulong dirtyBit) => SetSyncVarDirtyBit(dirtyBit); // true if syncInterval elapsed and any SyncVar or SyncObject is dirty public bool IsDirty() { if (NetworkTime.localTime - lastSyncTime >= syncInterval) { // OR both bitmasks. != 0 if either was dirty. return (syncVarDirtyBits | syncObjectDirtyBits) != 0UL; } return false; } /// <summary>Clears all the dirty bits that were set by SetDirtyBits()</summary> // automatically invoked when an update is sent for this object, but can // be called manually as well. public void ClearAllDirtyBits() { lastSyncTime = NetworkTime.localTime; syncVarDirtyBits = 0L; syncObjectDirtyBits = 0L; // clear all unsynchronized changes in syncobjects // (Linq allocates, use for instead) for (int i = 0; i < syncObjects.Count; ++i) { syncObjects[i].ClearChanges(); } } // this gets called in the constructor by the weaver // for every SyncObject in the component (e.g. SyncLists). // We collect all of them and we synchronize them with OnSerialize/OnDeserialize protected void InitSyncObject(SyncObject syncObject) { if (syncObject == null) { Debug.LogError("Uninitialized SyncObject. Manually call the constructor on your SyncList, SyncSet, SyncDictionary or SyncField<T>"); return; } // add it, remember the index in list (if Count=0, index=0 etc.) int index = syncObjects.Count; syncObjects.Add(syncObject); // OnDirty needs to set nth bit in our dirty mask ulong nthBit = 1UL << index; syncObject.OnDirty = () => syncObjectDirtyBits |= nthBit; // only record changes while we have observers. // prevents ever growing .changes lists: // if a monster has no observers but we keep modifing a SyncObject, // then the changes would never be flushed and keep growing, // because OnSerialize isn't called without observers. syncObject.IsRecording = () => netIdentity.observers?.Count > 0; } protected void SendCommandInternal(Type invokeClass, string cmdName, NetworkWriter writer, int channelId, bool requiresAuthority = true) { // this was in Weaver before // NOTE: we could remove this later to allow calling Cmds on Server // to avoid Wrapper functions. a lot of people requested this. if (!NetworkClient.active) { Debug.LogError($"Command Function {cmdName} called without an active client."); return; } // previously we used NetworkClient.readyConnection. // now we check .ready separately. if (!NetworkClient.ready) { // Unreliable Cmds from NetworkTransform may be generated, // or client may have been set NotReady intentionally, so // only warn if on the reliable channel. if (channelId == Channels.Reliable) Debug.LogWarning("Send command attempted while NetworkClient is not ready.\nThis may be ignored if client intentionally set NotReady."); return; } // local players can always send commands, regardless of authority, other objects must have authority. if (!(!requiresAuthority || isLocalPlayer || hasAuthority)) { Debug.LogWarning($"Trying to send command for object without authority. {invokeClass}.{cmdName}"); return; } // IMPORTANT: can't use .connectionToServer here because calling // a command on other objects is allowed if requireAuthority is // false. other objects don't have a .connectionToServer. // => so we always need to use NetworkClient.connection instead. // => see also: https://github.com/vis2k/Mirror/issues/2629 if (NetworkClient.connection == null) { Debug.LogError("Send command attempted with no client running."); return; } // construct the message CommandMessage message = new CommandMessage { netId = netId, componentIndex = (byte)ComponentIndex, // type+func so Inventory.RpcUse != Equipment.RpcUse functionHash = RemoteCallHelper.GetMethodHash(invokeClass, cmdName), // segment to avoid reader allocations payload = writer.ToArraySegment() }; // IMPORTANT: can't use .connectionToServer here because calling // a command on other objects is allowed if requireAuthority is // false. other objects don't have a .connectionToServer. // => so we always need to use NetworkClient.connection instead. // => see also: https://github.com/vis2k/Mirror/issues/2629 NetworkClient.connection.Send(message, channelId); } protected void SendRPCInternal(Type invokeClass, string rpcName, NetworkWriter writer, int channelId, bool includeOwner) { // this was in Weaver before if (!NetworkServer.active) { Debug.LogError($"RPC Function {rpcName} called on Client."); return; } // This cannot use NetworkServer.active, as that is not specific to this object. if (!isServer) { Debug.LogWarning($"ClientRpc {rpcName} called on un-spawned object: {name}"); return; } // construct the message RpcMessage message = new RpcMessage { netId = netId, componentIndex = (byte)ComponentIndex, // type+func so Inventory.RpcUse != Equipment.RpcUse functionHash = RemoteCallHelper.GetMethodHash(invokeClass, rpcName), // segment to avoid reader allocations payload = writer.ToArraySegment() }; NetworkServer.SendToReadyObservers(netIdentity, message, includeOwner, channelId); } protected void SendTargetRPCInternal(NetworkConnection conn, Type invokeClass, string rpcName, NetworkWriter writer, int channelId) { if (!NetworkServer.active) { Debug.LogError($"TargetRPC {rpcName} called when server not active"); return; } if (!isServer) { Debug.LogWarning($"TargetRpc {rpcName} called on {name} but that object has not been spawned or has been unspawned"); return; } // connection parameter is optional. assign if null. if (conn is null) { conn = connectionToClient; } // if still null if (conn is null) { Debug.LogError($"TargetRPC {rpcName} was given a null connection, make sure the object has an owner or you pass in the target connection"); return; } if (!(conn is NetworkConnectionToClient)) { Debug.LogError($"TargetRPC {rpcName} requires a NetworkConnectionToClient but was given {conn.GetType().Name}"); return; } // construct the message RpcMessage message = new RpcMessage { netId = netId, componentIndex = (byte)ComponentIndex, // type+func so Inventory.RpcUse != Equipment.RpcUse functionHash = RemoteCallHelper.GetMethodHash(invokeClass, rpcName), // segment to avoid reader allocations payload = writer.ToArraySegment() }; conn.Send(message, channelId); } // helper function for [SyncVar] GameObjects. // needs to be public so that tests & NetworkBehaviours from other // assemblies both find it [EditorBrowsable(EditorBrowsableState.Never)] public static bool SyncVarGameObjectEqual(GameObject newGameObject, uint netIdField) { uint newNetId = 0; if (newGameObject != null) { NetworkIdentity identity = newGameObject.GetComponent<NetworkIdentity>(); if (identity != null) { newNetId = identity.netId; if (newNetId == 0) { Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?"); } } } return newNetId == netIdField; } // helper function for [SyncVar] GameObjects. // dirtyBit is a mask like 00010 protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, ulong dirtyBit, ref uint netIdField) { if (GetSyncVarHookGuard(dirtyBit)) return; uint newNetId = 0; if (newGameObject != null) { NetworkIdentity identity = newGameObject.GetComponent<NetworkIdentity>(); if (identity != null) { newNetId = identity.netId; if (newNetId == 0) { Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?"); } } } //Debug.Log($"SetSyncVar GameObject {GetType().Name} bit:{dirtyBit} netfieldId:{netIdField} -> {newNetId}"); SetSyncVarDirtyBit(dirtyBit); // assign new one on the server, and in case we ever need it on client too gameObjectField = newGameObject; netIdField = newNetId; } // helper function for [SyncVar] GameObjects. // -> ref GameObject as second argument makes OnDeserialize processing easier protected GameObject GetSyncVarGameObject(uint netId, ref GameObject gameObjectField) { // server always uses the field if (isServer) { return gameObjectField; } // client always looks up based on netId because objects might get in and out of range // over and over again, which shouldn't null them forever if (NetworkClient.spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null) return gameObjectField = identity.gameObject; return null; } // helper function for [SyncVar] NetworkIdentities. // needs to be public so that tests & NetworkBehaviours from other // assemblies both find it [EditorBrowsable(EditorBrowsableState.Never)] public static bool SyncVarNetworkIdentityEqual(NetworkIdentity newIdentity, uint netIdField) { uint newNetId = 0; if (newIdentity != null) { newNetId = newIdentity.netId; if (newNetId == 0) { Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?"); } } // netId changed? return newNetId == netIdField; } // helper function for [SyncVar] NetworkIdentities. // dirtyBit is a mask like 00010 protected void SetSyncVarNetworkIdentity(NetworkIdentity newIdentity, ref NetworkIdentity identityField, ulong dirtyBit, ref uint netIdField) { if (GetSyncVarHookGuard(dirtyBit)) return; uint newNetId = 0; if (newIdentity != null) { newNetId = newIdentity.netId; if (newNetId == 0) { Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?"); } } //Debug.Log($"SetSyncVarNetworkIdentity NetworkIdentity {GetType().Name} bit:{dirtyBit} netIdField:{netIdField} -> {newNetId}"); SetSyncVarDirtyBit(dirtyBit); netIdField = newNetId; // assign new one on the server, and in case we ever need it on client too identityField = newIdentity; } // helper function for [SyncVar] NetworkIdentities. // -> ref GameObject as second argument makes OnDeserialize processing easier protected NetworkIdentity GetSyncVarNetworkIdentity(uint netId, ref NetworkIdentity identityField) { // server always uses the field if (isServer) { return identityField; } // client always looks up based on netId because objects might get in and out of range // over and over again, which shouldn't null them forever NetworkClient.spawned.TryGetValue(netId, out identityField); return identityField; } protected static bool SyncVarNetworkBehaviourEqual<T>(T newBehaviour, NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour { uint newNetId = 0; int newComponentIndex = 0; if (newBehaviour != null) { newNetId = newBehaviour.netId; newComponentIndex = newBehaviour.ComponentIndex; if (newNetId == 0) { Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?"); } } // netId changed? return syncField.Equals(newNetId, newComponentIndex); } // helper function for [SyncVar] NetworkIdentities. // dirtyBit is a mask like 00010 protected void SetSyncVarNetworkBehaviour<T>(T newBehaviour, ref T behaviourField, ulong dirtyBit, ref NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour { if (GetSyncVarHookGuard(dirtyBit)) return; uint newNetId = 0; int componentIndex = 0; if (newBehaviour != null) { newNetId = newBehaviour.netId; componentIndex = newBehaviour.ComponentIndex; if (newNetId == 0) { Debug.LogWarning($"{nameof(SetSyncVarNetworkBehaviour)} NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?"); } } syncField = new NetworkBehaviourSyncVar(newNetId, componentIndex); SetSyncVarDirtyBit(dirtyBit); // assign new one on the server, and in case we ever need it on client too behaviourField = newBehaviour; // Debug.Log($"SetSyncVarNetworkBehaviour NetworkIdentity {GetType().Name} bit [{dirtyBit}] netIdField:{oldField}->{syncField}"); } // helper function for [SyncVar] NetworkIdentities. // -> ref GameObject as second argument makes OnDeserialize processing easier protected T GetSyncVarNetworkBehaviour<T>(NetworkBehaviourSyncVar syncNetBehaviour, ref T behaviourField) where T : NetworkBehaviour { // server always uses the field if (isServer) { return behaviourField; } // client always looks up based on netId because objects might get in and out of range // over and over again, which shouldn't null them forever if (!NetworkClient.spawned.TryGetValue(syncNetBehaviour.netId, out NetworkIdentity identity)) { return null; } behaviourField = identity.NetworkBehaviours[syncNetBehaviour.componentIndex] as T; return behaviourField; } // backing field for sync NetworkBehaviour public struct NetworkBehaviourSyncVar : IEquatable<NetworkBehaviourSyncVar> { public uint netId; // limited to 255 behaviours per identity public byte componentIndex; public NetworkBehaviourSyncVar(uint netId, int componentIndex) : this() { this.netId = netId; this.componentIndex = (byte)componentIndex; } public bool Equals(NetworkBehaviourSyncVar other) { return other.netId == netId && other.componentIndex == componentIndex; } public bool Equals(uint netId, int componentIndex) { return this.netId == netId && this.componentIndex == componentIndex; } public override string ToString() { return $"[netId:{netId} compIndex:{componentIndex}]"; } } protected static bool SyncVarEqual<T>(T value, ref T fieldValue) { // newly initialized or changed value? // value.Equals(fieldValue) allocates without 'where T : IEquatable' // seems like we use EqualityComparer to avoid allocations, // because not all SyncVars<T> are IEquatable return EqualityComparer<T>.Default.Equals(value, fieldValue); } // dirtyBit is a mask like 00010 protected void SetSyncVar<T>(T value, ref T fieldValue, ulong dirtyBit) { //Debug.Log($"SetSyncVar {GetType().Name} bit:{dirtyBit} fieldValue:{value}"); SetSyncVarDirtyBit(dirtyBit); fieldValue = value; } /// <summary>Override to do custom serialization (instead of SyncVars/SyncLists). Use OnDeserialize too.</summary> // if a class has syncvars, then OnSerialize/OnDeserialize are added // automatically. // // initialState is true for full spawns, false for delta syncs. // note: SyncVar hooks are only called when inital=false public virtual bool OnSerialize(NetworkWriter writer, bool initialState) { // if initialState: write all SyncVars. // otherwise write dirtyBits+dirty SyncVars bool objectWritten = initialState ? SerializeObjectsAll(writer) : SerializeObjectsDelta(writer); bool syncVarWritten = SerializeSyncVars(writer, initialState); return objectWritten || syncVarWritten; } /// <summary>Override to do custom deserialization (instead of SyncVars/SyncLists). Use OnSerialize too.</summary> public virtual void OnDeserialize(NetworkReader reader, bool initialState) { if (initialState) { DeSerializeObjectsAll(reader); } else { DeSerializeObjectsDelta(reader); } DeserializeSyncVars(reader, initialState); } // USED BY WEAVER protected virtual bool SerializeSyncVars(NetworkWriter writer, bool initialState) { return false; // SyncVar are written here in subclass // if initialState // write all SyncVars // else // write syncVarDirtyBits // write dirty SyncVars } // USED BY WEAVER protected virtual void DeserializeSyncVars(NetworkReader reader, bool initialState) { // SyncVars are read here in subclass // if initialState // read all SyncVars // else // read syncVarDirtyBits // read dirty SyncVars } public bool SerializeObjectsAll(NetworkWriter writer) { bool dirty = false; for (int i = 0; i < syncObjects.Count; i++) { SyncObject syncObject = syncObjects[i]; syncObject.OnSerializeAll(writer); dirty = true; } return dirty; } public bool SerializeObjectsDelta(NetworkWriter writer) { bool dirty = false; // write the mask writer.WriteULong(syncObjectDirtyBits); // serializable objects, such as synclists for (int i = 0; i < syncObjects.Count; i++) { // check dirty mask at nth bit SyncObject syncObject = syncObjects[i]; if ((syncObjectDirtyBits & (1UL << i)) != 0) { syncObject.OnSerializeDelta(writer); dirty = true; } } return dirty; } internal void DeSerializeObjectsAll(NetworkReader reader) { for (int i = 0; i < syncObjects.Count; i++) { SyncObject syncObject = syncObjects[i]; syncObject.OnDeserializeAll(reader); } } internal void DeSerializeObjectsDelta(NetworkReader reader) { ulong dirty = reader.ReadULong(); for (int i = 0; i < syncObjects.Count; i++) { // check dirty mask at nth bit SyncObject syncObject = syncObjects[i]; if ((dirty & (1UL << i)) != 0) { syncObject.OnDeserializeDelta(reader); } } } internal void ResetSyncObjects() { foreach (SyncObject syncObject in syncObjects) { syncObject.Reset(); } } /// <summary>Like Start(), but only called on server and host.</summary> public virtual void OnStartServer() {} /// <summary>Stop event, only called on server and host.</summary> public virtual void OnStopServer() {} /// <summary>Like Start(), but only called on client and host.</summary> public virtual void OnStartClient() {} /// <summary>Stop event, only called on client and host.</summary> public virtual void OnStopClient() {} /// <summary>Like Start(), but only called on client and host for the local player object.</summary> public virtual void OnStartLocalPlayer() {} /// <summary>Like Start(), but only called for objects the client has authority over.</summary> public virtual void OnStartAuthority() {} /// <summary>Stop event, only called for objects the client has authority over.</summary> public virtual void OnStopAuthority() {} } }
42.410437
268
0.5943
[ "MIT" ]
Crotshot/FYP
Assets/Mirror/Runtime/NetworkBehaviour.cs
30,069
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Newtonsoft.Json; namespace Frogvall.AspNetCore.ApiUtilities.ExceptionHandling { public sealed class ApiError { public const string ModelBindingErrorMessage = "Invalid parameters."; [JsonConstructor] public ApiError(string serviceName) { Service = serviceName; } public ApiError(int errorCode, object developerContext, string message, string serviceName) { ErrorCode = errorCode; Service = serviceName; Message = message; DeveloperContext = developerContext; } /// <summary> /// Creates a new <see cref="ApiError"/> from the result of a model binding attempt. /// The model binding errors (if any) are placed in the <see cref="DeveloperContext"/> property. /// </summary> /// <param name="errorCode"></param> /// <param name="modelState"></param> /// <param name="correlationId"></param> /// <param name="serviceName"></param> public ApiError(int errorCode, ModelStateDictionary modelState, string correlationId, string serviceName) { Service = serviceName; Message = ModelBindingErrorMessage; ErrorCode = errorCode; DeveloperContext = new SerializableError(modelState); CorrelationId = correlationId; } public string Service { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string CorrelationId { get; set; } public string Message { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string DetailedMessage { get; set; } public int ErrorCode { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public object DeveloperContext { get; set; } } }
34.684211
113
0.633283
[ "MIT" ]
Frogvall/AspNetCoreApiUtilities
src/AspNetCoreApiUtilities/ExceptionHandling/ApiError.cs
1,979
C#
using Microsoft.Extensions.Configuration; using Castle.MicroKernel.Registration; using Abp.Events.Bus; using Abp.Modules; using Abp.Reflection.Extensions; using InventoryManagementSystem.Configuration; using InventoryManagementSystem.EntityFrameworkCore; using InventoryManagementSystem.Migrator.DependencyInjection; namespace InventoryManagementSystem.Migrator { [DependsOn(typeof(InventoryManagementSystemEntityFrameworkModule))] public class InventoryManagementSystemMigratorModule : AbpModule { private readonly IConfigurationRoot _appConfiguration; public InventoryManagementSystemMigratorModule(InventoryManagementSystemEntityFrameworkModule abpProjectNameEntityFrameworkModule) { abpProjectNameEntityFrameworkModule.SkipDbSeed = true; _appConfiguration = AppConfigurations.Get( typeof(InventoryManagementSystemMigratorModule).GetAssembly().GetDirectoryPathOrNull() ); } public override void PreInitialize() { Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString( InventoryManagementSystemConsts.ConnectionStringName ); Configuration.BackgroundJobs.IsJobExecutionEnabled = false; Configuration.ReplaceService( typeof(IEventBus), () => IocManager.IocContainer.Register( Component.For<IEventBus>().Instance(NullEventBus.Instance) ) ); } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(InventoryManagementSystemMigratorModule).GetAssembly()); ServiceCollectionRegistrar.Register(IocManager); } } }
37.291667
138
0.716201
[ "MIT" ]
farazahmed879/Inventory-Management-System
aspnet-core/src/InventoryManagementSystem.Migrator/InventoryManagementSystemMigratorModule.cs
1,790
C#
using System; using System.Collections.Generic; namespace ReCache { public class TupleComparer<TItem1, TItem2> : IEqualityComparer<Tuple<TItem1, TItem2>> { private IEqualityComparer<TItem1> _item1Comparer; private IEqualityComparer<TItem2> _item2Comparer; public TupleComparer() { } public TupleComparer( IEqualityComparer<TItem1> item1Comparer, IEqualityComparer<TItem2> item2Comparer) { _item1Comparer = item1Comparer; _item2Comparer = item2Comparer; } public bool DefaultCompareEquals<T>(T first, T second) { return EqualityComparer<T>.Default.Equals(first, second); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1")] public bool Equals(Tuple<TItem1, TItem2> x, Tuple<TItem1, TItem2> y) { if (ReferenceEquals(null, x) ^ ReferenceEquals(null, y)) return false; if (ReferenceEquals(null, x) && ReferenceEquals(null, y)) return true; Func<TItem1, TItem1, bool> item1sAreEqual = DefaultCompareEquals; if (_item1Comparer != null) item1sAreEqual = _item1Comparer.Equals; Func<TItem2, TItem2, bool> item2sAreEqual = DefaultCompareEquals; if (_item2Comparer != null) item2sAreEqual = _item2Comparer.Equals; return item1sAreEqual(x.Item1, y.Item1) && item2sAreEqual(x.Item2, y.Item2); } public int GetHashCode(Tuple<TItem1, TItem2> obj) { if (obj == null) return -1; int hash = 0; if (_item1Comparer != null) hash += _item1Comparer.GetHashCode(obj.Item1); else hash += obj.Item1.GetHashCode(); if (_item2Comparer != null) hash += _item2Comparer.GetHashCode(obj.Item2); else hash += obj.Item2.GetHashCode(); return hash; } } }
27.75
135
0.718601
[ "MIT" ]
jfbosch/recache
ReCache/TupleComparer.cs
1,889
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("NetworkingUtilities")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("NetworkingUtilities")] [assembly: System.Reflection.AssemblyTitleAttribute("NetworkingUtilities")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.958333
80
0.656405
[ "MIT" ]
zihasz/NetworkingUtilities
NetworkingUtilities/obj/Debug/netstandard2.0/NetworkingUtilities.AssemblyInfo.cs
1,007
C#
using System; using System.Text; using System.Net; using Newtonsoft.Json; using System.Threading.Tasks; using System.IO; namespace KODIRemoteController.Model { class JsonRpcClient { private JsonrpcDefaultOption _option; public JsonRpcClient(string host) { _option = new JsonrpcDefaultOption(); _option.RpcServer = host; } public async Task<bool> SendRequstAsync(RPCRequestModel reqData) { var req = HttpWebRequest.Create(GetJsonRpcUrl(reqData.Method)) as HttpWebRequest; req.Method = _option.Type; req.ContentType = _option.ContentType; var byteData = GetRequstByteData(reqData); req.ContentLength = byteData.Length; req.GetRequestStream().Write(byteData, 0, byteData.Length); var response = await req.GetResponseAsync() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) { var reader = new StreamReader(response.GetResponseStream()); var r = reader.ReadToEnd(); return true; } return false; } private byte[] GetRequstByteData(RPCRequestModel reqData) { var jsonStr = JsonConvert.SerializeObject(reqData , Formatting.Indented , new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); return Encoding.UTF8.GetBytes(jsonStr); } private string GetJsonRpcUrl(string method) { return $"{_option.RpcServer}/jsonrpc?{method}"; } } }
33.759259
113
0.599561
[ "Apache-2.0" ]
shellywu/KODIController
KODIRemoteController/Model/JsonRpcClient.cs
1,823
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Xml.Linq; using NuGet.Configuration; using NuGet.Test.Utility; using Xunit; namespace Dotnet.Integration.Test { [Collection("Dotnet Integration Tests")] public class DotnetSourcesTests { private readonly MsbuildIntegrationTestFixture _fixture; public DotnetSourcesTests(MsbuildIntegrationTestFixture fixture) { _fixture = fixture; } [PlatformFact(Platform.Windows)] public void Sources_WhenAddingSource_GotAdded() { using (var pathContext = new SimpleTestPathContext()) { var workingPath = pathContext.WorkingDirectory; var settings = pathContext.Settings; // Arrange var args = new string[] { "nuget", "add", "source", "https://source.test", "--name", "test_source", "--configfile", settings.ConfigPath }; // Act var result = _fixture.RunDotnet(workingPath, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.ExitCode == 0); var loadedSettings = Settings.LoadDefaultSettings(root: workingPath, configFileName: null, machineWideSettings: null); var packageSourcesSection = loadedSettings.GetSection("packageSources"); var sourceItem = packageSourcesSection?.GetFirstItemWithAttribute<SourceItem>("key", "test_source"); Assert.Equal("https://source.test", sourceItem.GetValueAsPath()); } } [PlatformFact(Platform.Windows)] public void Sources_WhenAddingSourceWithCredentials_CredentialsWereAddedAndEncrypted() { using (var pathContext = new SimpleTestPathContext()) { var workingPath = pathContext.WorkingDirectory; var settings = pathContext.Settings; // Arrange var args = new string[] { "nuget", "add", "source", "https://source.test", "--name", "test_source", "--username", "test_user_name", "--password", "test_password", "--configfile", settings.ConfigPath }; // Act var result = _fixture.RunDotnet(workingPath, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.Success, result.Output + " " + result.Errors); var loadedSettings = Settings.LoadDefaultSettings(root: workingPath, configFileName: null, machineWideSettings: null); var packageSourcesSection = loadedSettings.GetSection("packageSources"); var sourceItem = packageSourcesSection?.GetFirstItemWithAttribute<SourceItem>("key", "test_source"); Assert.Equal("https://source.test", sourceItem.GetValueAsPath()); var sourceCredentialsSection = loadedSettings.GetSection("packageSourceCredentials"); var credentialItem = sourceCredentialsSection?.Items.First(c => string.Equals(c.ElementName, "test_source", StringComparison.OrdinalIgnoreCase)) as CredentialsItem; Assert.NotNull(credentialItem); Assert.Equal("test_user_name", credentialItem.Username); var password = EncryptionUtility.DecryptString(credentialItem.Password); Assert.Equal("test_password", password); } } [PlatformFact(Platform.Windows)] public void Sources_WhenAddingSourceWithCredentialsInClearText_CredentialsWereAddedAndNotEncrypted() { using (var pathContext = new SimpleTestPathContext()) { var workingPath = pathContext.WorkingDirectory; var settings = pathContext.Settings; // Arrange var args = new string[] { "nuget", "add", "source", "https://source.test", "--name", "test_source", "--username", "test_user_name", "--password", "test_password", "--store-password-in-clear-text", "--configfile", settings.ConfigPath }; // Act var result = _fixture.RunDotnet(workingPath, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.Success, result.Output + " " + result.Errors); var loadedSettings = Settings.LoadDefaultSettings(root: workingPath, configFileName: null, machineWideSettings: null); var packageSourcesSection = loadedSettings.GetSection("packageSources"); var sourceItem = packageSourcesSection?.GetFirstItemWithAttribute<SourceItem>("key", "test_source"); Assert.Equal("https://source.test", sourceItem.GetValueAsPath()); var sourceCredentialsSection = loadedSettings.GetSection("packageSourceCredentials"); var credentialItem = sourceCredentialsSection?.Items.First(c => string.Equals(c.ElementName, "test_source", StringComparison.OrdinalIgnoreCase)) as CredentialsItem; Assert.NotNull(credentialItem); Assert.Equal("test_user_name", credentialItem.Username); Assert.Equal("test_password", credentialItem.Password); } } [PlatformFact(Platform.Windows)] public void Sources_WhenAddingSourceWithCredentialsToUserConfigFile_CredentialsWereAddedAndEncryptedInUserConfigFile() { // Arrange using (var configFileDirectory = _fixture.CreateTestDirectory()) { var configFileName = "nuget.config"; var configFilePath = Path.Combine(configFileDirectory, configFileName); string nugetConfig = @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> </configuration>"; CreateXmlFile(configFilePath, nugetConfig); var args = new string[] { "nuget", "add", "source", "https://source.test", "--name", "test_source", "--username", "test_user_name", "--password", "test_password", "--configfile", configFilePath }; // Act var result = _fixture.RunDotnet(configFileDirectory, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.Success, result.AllOutput); var settings = Settings.LoadDefaultSettings( configFileDirectory, configFileName, null); var packageSourcesSection = settings.GetSection("packageSources"); var sourceItem = packageSourcesSection?.GetFirstItemWithAttribute<SourceItem>("key", "test_source"); Assert.Equal("https://source.test", sourceItem.GetValueAsPath()); var sourceCredentialsSection = settings.GetSection("packageSourceCredentials"); var credentialItem = sourceCredentialsSection?.Items.First(c => string.Equals(c.ElementName, "test_source", StringComparison.OrdinalIgnoreCase)) as CredentialsItem; Assert.NotNull(credentialItem); Assert.Equal("test_user_name", credentialItem.Username); var password = EncryptionUtility.DecryptString(credentialItem.Password); Assert.Equal("test_password", password); } } private static void CreateXmlFile(string configFilePath, string nugetConfigString) { using (var stream = File.OpenWrite(configFilePath)) { var nugetConfigXDoc = XDocument.Parse(nugetConfigString); ProjectFileUtils.WriteXmlToFile(nugetConfigXDoc, stream); } } [PlatformFact(Platform.Windows)] public void Sources_WhenEnablingADisabledSource_SourceBecameEnabled() { // Arrange using (var configFileDirectory = _fixture.CreateTestDirectory()) { var configFileName = "nuget.config"; var configFilePath = Path.Combine(configFileDirectory, configFileName); var nugetConfig = @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> <add key=""test_source"" value=""https://source.test"" /> </packageSources> <disabledPackageSources> <add key=""test_source"" value=""true"" /> <add key=""Microsoft and .NET"" value=""true"" /> </disabledPackageSources> </configuration>"; CreateXmlFile(configFilePath, nugetConfig); var args = new string[] { "nuget", "enable", "source", "TEST_source", // this should work in a case sensitive manner "--configfile", configFilePath }; // Act var settings = Settings.LoadDefaultSettings( configFileDirectory, configFileName, machineWideSettings: null); var packageSourceProvider = new PackageSourceProvider(settings); var sources = packageSourceProvider.LoadPackageSources().ToList(); Assert.Single(sources); var source = sources.Single(); Assert.Equal("test_source", source.Name); Assert.Equal("https://source.test", source.Source); Assert.False(source.IsEnabled); // Main Act var result = _fixture.RunDotnet(configFileDirectory, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.ExitCode == 0); settings = Settings.LoadDefaultSettings( configFileDirectory, configFileName, null); var disabledSourcesSection = settings.GetSection("disabledPackageSources"); var disabledSources = disabledSourcesSection?.Items.Select(c => c as AddItem).Where(c => c != null).ToList(); Assert.Single(disabledSources); var disabledSource = disabledSources.Single(); Assert.Equal("Microsoft and .NET", disabledSource.Key); packageSourceProvider = new PackageSourceProvider(settings); sources = packageSourceProvider.LoadPackageSources().ToList(); var testSources = sources.Where(s => s.Name == "test_source"); Assert.Single(testSources); source = testSources.Single(); Assert.Equal("test_source", source.Name); Assert.Equal("https://source.test", source.Source); Assert.True(source.IsEnabled, "Source is not enabled"); } } [PlatformFact(Platform.Windows)] public void Sources_WhenDisablingAnEnabledSource_SourceBecameDisabled() { // Arrange using (var configFileDirectory = _fixture.CreateTestDirectory()) { var configFileName = "nuget.config"; var configFilePath = Path.Combine(configFileDirectory, configFileName); var nugetConfig = @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> <add key=""test_source"" value=""https://source.test"" /> </packageSources> </configuration>"; CreateXmlFile(configFilePath, nugetConfig); var args = new string[] { "nuget", "disable", "source", "TEST_source", "--configfile", configFilePath }; // Act var settings = Settings.LoadDefaultSettings( configFileDirectory, configFileName, null); var packageSourceProvider = new PackageSourceProvider(settings); var sources = packageSourceProvider.LoadPackageSources().ToList(); Assert.Single(sources); var source = sources.Single(); Assert.Equal("test_source", source.Name); Assert.Equal("https://source.test", source.Source); Assert.True(source.IsEnabled); // Main Act var result = _fixture.RunDotnet(configFileDirectory, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.ExitCode == 0); settings = Settings.LoadDefaultSettings( configFileDirectory, configFileName, null); packageSourceProvider = new PackageSourceProvider(settings); sources = packageSourceProvider.LoadPackageSources().ToList(); var testSources = sources.Where(s => s.Name == "test_source"); Assert.Single(testSources); source = testSources.Single(); Assert.Equal("test_source", source.Name); Assert.Equal("https://source.test", source.Source); Assert.False(source.IsEnabled, "Source is not disabled"); } } [PlatformTheory(Platform.Windows)] [InlineData("list source --foo", 2)] [InlineData("add source foo bar", 3)] [InlineData("remove source a b", 3)] [InlineData("remove a b c", 1)] [InlineData("add source B a --configfile file.txt --name x --source y", 3)] [InlineData("list source --configfile file.txt B a", 4)] public void Sources_WhenPassingInvalidArguments_ProperErrorsAreRaised(string cmd, int badParam) { // all of these commands need to start with "nuget ", and need to adjust bad param to account for those 2 new params TestCommandInvalidArguments("nuget " + cmd, badParam + 1); } [Fact(Skip = "cutting verbosity Quiet for now. #6374 covers fixing it for `dotnet add package` too.")] public void TestVerbosityQuiet_DoesNotShowInfoMessages() { using (var pathContext = new SimpleTestPathContext()) { var workingPath = pathContext.WorkingDirectory; var settings = pathContext.Settings; // Arrange var args = new string[] { "nuget", "add", "source", "https://source.test", "--name", "test_source", "--verbosity", "Quiet", "--configfile", settings.ConfigPath }; // Act var result = _fixture.RunDotnet(workingPath, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.ExitCode == 0); // Ensure that no messages are shown with Verbosity as Quiet Assert.Equal(string.Empty, result.Output); var loadedSettings = Settings.LoadDefaultSettings(root: workingPath, configFileName: null, machineWideSettings: null); var packageSourcesSection = loadedSettings.GetSection("packageSources"); var sourceItem = packageSourcesSection?.GetFirstItemWithAttribute<SourceItem>("key", "test_source"); Assert.Equal("https://source.test", sourceItem.GetValueAsPath()); } } /// <summary> /// Verify non-zero status code and proper messages /// </summary> /// <remarks>Checks invalid arguments message in stderr, check help message in stdout</remarks> /// <param name="commandName">The nuget.exe command name to verify, without "nuget.exe" at the beginning</param> public void TestCommandInvalidArguments(string command, int badCommandIndex) { using (var testDirectory = _fixture.CreateTestDirectory()) { // Act var result = _fixture.RunDotnet(testDirectory, command, ignoreExitCode: true); var commandSplit = command.Split(' '); // Break the test if no proper command is found if (commandSplit.Length < 1 || string.IsNullOrEmpty(commandSplit[0])) Assert.True(false, "command not found"); // 0th - "nuget" // 1st - "source" // 2nd - action // 3rd - nextParam string badCommand = commandSplit[badCommandIndex]; // Assert command Assert.Contains("'" + badCommand + "'", result.Output, StringComparison.InvariantCultureIgnoreCase); // Assert invalid argument message string invalidMessage; if (badCommand.StartsWith("-")) { invalidMessage = "error: Unrecognized option"; } else { invalidMessage = "error: Unrecognized command"; } // Verify Exit code VerifyResultFailure(result, invalidMessage); // Verify traits of help message in stdout Assert.Contains("Specify --help for a list of available options and commands.", result.Output); } } /// <summary> /// Utility for asserting faulty executions of dotnet.exe /// /// Asserts a non-zero status code and a message on stderr. /// </summary> /// <param name="result">An instance of <see cref="CommandRunnerResult"/> with command execution results</param> /// <param name="expectedErrorMessage">A portion of the error message to be sent</param> public static void VerifyResultFailure(CommandRunnerResult result, string expectedErrorMessage) { Assert.False( result.Success, "dotnet.exe nuget DID NOT FAIL: Output is " + result.Output + ". Error is " + result.Errors); Assert.True( result.Output.Contains(expectedErrorMessage), "Expected error is " + expectedErrorMessage + ". Actual error is " + result.Output); } } }
41.029167
180
0.547273
[ "Apache-2.0" ]
BlackGad/NuGet.Client
test/NuGet.Core.FuncTests/Dotnet.Integration.Test/DotnetSourcesTests.cs
19,694
C#
using System; using System.Threading.Tasks; using Blockcore.Builder; using Blockcore.Builder.Feature; using Xunit; namespace Blockcore.Tests.Builder.Feature { public class FeatureCollectionTest { [Fact] public void AddToCollectionReturnsOfGivenType() { var collection = new FeatureCollection(); collection.AddFeature<FeatureCollectionFullNodeFeature>(); Assert.Single(collection.FeatureRegistrations); Assert.Equal(typeof(FeatureCollectionFullNodeFeature), collection.FeatureRegistrations[0].FeatureType); } [Fact] public void AddFeatureAlreadyInCollectionThrowsException() { Assert.Throws<ArgumentException>(() => { var collection = new FeatureCollection(); collection.AddFeature<FeatureCollectionFullNodeFeature>(); collection.AddFeature<FeatureCollectionFullNodeFeature>(); }); } private class FeatureCollectionFullNodeFeature : IFullNodeFeature { /// <inheritdoc /> public bool InitializeBeforeBase { get; set; } public string State { get; set; } public void LoadConfiguration() { throw new NotImplementedException(); } public Task InitializeAsync() { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } public void ValidateDependencies(IFullNodeServiceProvider services) { throw new NotImplementedException(); } } } }
27.952381
115
0.58887
[ "MIT" ]
Botcoin-Abacus/blockcore
src/Tests/Blockcore.Tests/Builder/Feature/FeatureCollectionTest.cs
1,763
C#
/* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr4.StringTemplate.Misc { using Antlr4.StringTemplate.Compiler; ////** <name> where name is not found up the dynamic scoping chain. */ public class AttributeNotFoundException : TemplateException { private readonly TemplateFrame _frame; private readonly string _attributeName; public AttributeNotFoundException(TemplateFrame frame, string attributeName) { _frame = frame; _attributeName = attributeName; } public override string Message { get { return "from template " + _frame.Template.Name + " no attribute " + _attributeName + " is visible"; } } } }
41.537037
115
0.703968
[ "BSD-3-Clause" ]
antlr/antlrcs
Antlr4.StringTemplate/Misc/AttributeNotFoundException.cs
2,245
C#
using System; class PrimeCheck { static void Main() { int N = int.Parse(Console.ReadLine()); var isPrime = "true"; if (1 < N && N <= 100) { for (int i = 2; i < N; i++) { if (N % i == 0) { isPrime = "false"; } } Console.WriteLine(isPrime); } else { Console.WriteLine("false"); } } }
18.807692
46
0.337423
[ "MIT" ]
DobrinStefkin/HomeworkThirdLecture
PrimeCheck/PrimeCheck.cs
491
C#
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace SecurityAdminSuite { /// <summary> /// Interaction logic for EditStringWindow.xaml /// </summary> public partial class EditStringWindow : Window { #region Constructors (1) public EditStringWindow() { InitializeComponent(); DataContext = this; tbString.Focus(); } #endregion Constructors #region Properties (2) public string Header { get { return tbHeader.Text; } set { tbHeader.Text = value; } } public string TextItem { get { return tbString.Text; } set { tbString.Text = value; tbString.SelectAll(); } } #endregion Properties #region Event Handlers (1) void OK_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(TextItem)) { MessageBox.Show("Text must not be empty!"); return; } DialogResult = true; } #endregion Event Handlers } }
31.225806
137
0.527548
[ "MIT" ]
hmehr/OSS
MemoryLifter/Development/Current/SecurityAdminSuite/StringEditor.xaml.cs
2,915
C#
// *********************************************************************** // Assembly : MPT.CSI.OOAPI // Author : Mark Thomas // Created : 11-18-2018 // // Last Modified By : Mark Thomas // Last Modified On : 11-21-2018 // *********************************************************************** // <copyright file="FrameLoadsDistributed.cs" company=""> // Copyright © 2018 // </copyright> // <summary></summary> // *********************************************************************** using MPT.CSI.API.Core.Program.ModelBehavior; namespace MPT.CSI.OOAPI.Core.Program.Model.Assignments.AppliedLoads { /// <summary> /// Struct FrameLoadsDistributed /// </summary> public class FrameLoadDistributed : Load { /// <summary> /// Force type for the distributed load for the load pattern. /// </summary> /// <value>The type of the force.</value> public eLoadForceType ForceType { get; set; } /// <summary> /// Direction that the load is applied in for the load pattern. /// </summary> /// <value>The load direction.</value> public eLoadDirection LoadDirection { get; set; } /// <summary> /// The load value at the start of the distributed load. /// [F/L] when <see cref="ForceType" /> is <see cref="eLoadForceType.Force" /> and [F*L/L] when <see cref="ForceType" /> is <see cref="eLoadForceType.Moment" />. /// </summary> /// <value>The start load value.</value> public double StartLoadValue { get; set; } /// <summary> /// The load value at the end of the distributed load. /// [F/L] when <see cref="ForceType" /> is <see cref="eLoadForceType.Force" /> and [F*L/L] when <see cref="ForceType" /> is <see cref="eLoadForceType.Moment" />. /// </summary> /// <value>The end load value.</value> public double EndLoadValue { get; set; } /// <summary> /// The actual distance from the I-End of the element to the start of the distributed load. [L] /// </summary> /// <value>The absolute distance start from i.</value> public double AbsoluteDistanceStartFromI { get; set; } /// <summary> /// The actual distance from the I-End of the element to the end of the distributed load. [L] /// </summary> /// <value>The absolute distance end from i.</value> public double AbsoluteDistanceEndFromI { get; set; } /// <summary> /// The relative distance from the I-End of the element to the start of the distributed load. /// </summary> /// <value>The relative distance start from i.</value> public double RelativeDistanceStartFromI { get; set; } /// <summary> /// The relative distance from the I-End of the element to the end of the distributed load. /// </summary> /// <value>The relative distance end from i.</value> public double RelativeDistanceEndFromI { get; set; } /// <summary> /// Coordinated system used for the distributed load. /// It may be Local or the name of a defined coordinate system. /// </summary> /// <value>The coordinate system.</value> public string CoordinateSystem { get; set; } } }
40.385542
170
0.554893
[ "MIT" ]
MarkPThomas/MPT.Net
MPT/CSI/API/MPT.CSI.OOAPI.EndToEndTests/Core/Program/Model/Assignments/AppliedLoads/FrameLoadDistributed.cs
3,355
C#
using System.Threading; using System.Threading.Tasks; #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously namespace AutoSaliens.Console.Commands { [CommandVerb("checkupdate")] internal class CheckUpdateCommand : CommandBase { public override async Task RunAsync(string parameters, CancellationToken cancellationToken) { if (!UpdateChecker.HasUpdate && !UpdateChecker.HasUpdateBranch) { this.Logger?.LogCommandOutput($"No update was available during the last check."); return; } if (UpdateChecker.AppBranch == "stable") { #pragma warning disable CS0162 // Unreachable code detected: This code will run on AppVeyor builds if (UpdateChecker.HasUpdate && UpdateChecker.AppBranch == "stable") this.Logger?.LogCommandOutput($"An update is available: {{value}}{UpdateChecker.UpdateVersion}."); #pragma warning restore CS0162 // Unreachable code detected } else { if (UpdateChecker.HasUpdateBranch) this.Logger?.LogCommandOutput($"An update is available for your branch {{value}}{UpdateChecker.AppBranch}{{reset}}: {{value}}{UpdateChecker.UpdateVersionBranch}{{reset}}."); if (UpdateChecker.HasUpdate) this.Logger?.LogCommandOutput($"An update is available for the {{value}}stable{{reset}} branch: {{value}}{UpdateChecker.UpdateVersion}{{reset}}. Check if it's worth going back from the {{value}}{UpdateChecker.AppBranch}{{reset}} branch."); } this.Logger?.LogCommandOutput($"Visit the homepage at {{url}}{Program.HomepageUrl}"); } } }
48.027027
259
0.644907
[ "MIT" ]
Archomeda/AutoSaliens
AutoSaliens/Console/Commands/CheckUpdateCommand.cs
1,777
C#
using Warframe_WebLog.Classes.Twitter; namespace Warframe_WebLog.Classes { public class Config { public string DbAddress; public string DbPassword; public string DbTable; public string DbUsername; public string GcmKey; public string GcmPackage; public string GcmSenderId; public TwitterInfo TwitterInfo; public int WorldVersion; } }
24.588235
39
0.665072
[ "MIT" ]
Deathmax/wf-weblog-deathsnacks
Classes/Config.cs
420
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Ocelot.DependencyInjection; using Ocelot.Middleware; using Ocelot.Cache.CacheManager; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OcelotApiGw { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddOcelot() .AddCacheManager(settings => settings.WithDictionaryHandle()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public async void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); await app.UseOcelot(); } } }
31.270833
122
0.638241
[ "MIT" ]
bgani/dotnet-microservices
src/ApiGateways/OcelotApiGw/Startup.cs
1,501
C#
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Threading.Tasks; using MassTransit; using MassTransit.Util; namespace Publisher { public class SqlLoggingPublicationObserver : IPublishObserver { public Task PrePublish<T>(PublishContext<T> context) where T : class { InsertMessageInfo(context.MessageId); return TaskUtil.Completed; } public Task PostPublish<T>(PublishContext<T> context) where T : class { PublicationQueueManager.DecrementQueueDepth(); return TaskUtil.Completed; } public Task PublishFault<T>(PublishContext<T> context, Exception exception) where T : class { PublicationQueueManager.DecrementQueueDepth(); DeleteMessageInfo(context.MessageId); Console.Out.WriteLineAsync(exception.Message); return TaskUtil.Completed; } private static void DeleteMessageInfo(Guid? messageId) { using (var connection = GetConnection()) { connection.Open(); var command = connection.CreateCommand(); command.CommandType = CommandType.StoredProcedure; command.CommandText = "dbo.spUnconsumedMessageDelete"; var clientNameParameter = new SqlParameter("clientName", SqlDbType.VarChar, 100) { Value = Configuration .ClientName }; var messageIdParameter = new SqlParameter("messageId", SqlDbType.UniqueIdentifier) { Value = messageId }; command.Parameters.Add(clientNameParameter); command.Parameters.Add(messageIdParameter); command.ExecuteNonQuery(); connection.Close(); } } private static SqlConnection GetConnection() { return new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString); } private static void InsertMessageInfo(Guid? messageId) { using (var connection = GetConnection()) { connection.Open(); var command = connection.CreateCommand(); command.CommandType = CommandType.StoredProcedure; command.CommandText = "dbo.spUnconsumedMessageInsert"; var clientNameParameter = new SqlParameter("clientName", SqlDbType.VarChar, 100) { Value = Configuration .ClientName }; var messageIdParameter = new SqlParameter("messageId", SqlDbType.UniqueIdentifier) { Value = messageId }; command.Parameters.Add(clientNameParameter); command.Parameters.Add(messageIdParameter); command.ExecuteNonQuery(); connection.Close(); } } } }
38.363636
121
0.530509
[ "MIT" ]
EnterpriseProductsLP/RabbitStressTest
src/Publisher/SqlLoggingPublicationObserver.cs
3,378
C#
#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator using System; using System.Reflection; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Detrack.ElasticRoute { /// <summary> /// Represents a single stop in a <see cref="Plan"/> you need to route <see cref="Vehicle"/>s to. /// </summary> [JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy), ItemNullValueHandling = NullValueHandling.Ignore)] //[JsonConverter(typeof(Detrack.ElasticRoute.Tools.StopConverter))] public class Stop : Detrack.ElasticRoute.Tools.BaseModel { private string _vehicle_type; private string _depot; private string _name; private float? _weight_load; private float? _volume_load; private float? _seating_load; private string _address; private string _postal_code; private int? _service_time; private float? _lat; private float? _lng; private int? _from; private int? _till; /// <summary> /// Gets or sets the vehicle type of the stop, used to add a constraint where this stop can only be served by vehicles with a corresponding type. /// </summary> /// <value>The type of the vehicle.</value> public string VehicleType { get => _vehicle_type; set { if (_vehicle_type != value) { NotifyPropertyChanged(); _vehicle_type = value; } } } /// <summary> /// Gets or sets the depot of the stop, used to specify the starting location where the driver would pickup the goods/products to be delivered to the stop. If you leave this empty, it will match the first instance in the list of depots in the plan. /// </summary> /// <value>The depot.</value> public string Depot { get => _depot; set { if (_depot != value) { NotifyPropertyChanged(); _depot = value; } } } /// <summary> /// Gets or sets the name of the stop. Names MUST be distinct within a plan. Required field. /// </summary> /// <value>Name of the stop. The name must be unique and the value will automatically be trimmed of whitespace.</value> public string Name { get { return _name; } set { if (string.IsNullOrWhiteSpace(value)) { throw new BadFieldException("Stop name cannot be null"); } else if (value.Length > 255) { throw new BadFieldException("Stop name cannot be more than 255 chars"); } else { if (_name != value.Trim()) { NotifyPropertyChanged(); _name = value.Trim(); } } } } /// <summary> /// Gets or sets the address of the stop. Required field. /// </summary> /// <value>The address.</value> public string Address { get => _address; set { if (_address != value) { NotifyPropertyChanged(); _address = value; } } } /// <summary> /// Gets or sets the postal code of the stop. This can be used as an alternative form of geocoding (opposed to address/lat+lng) only if your country defined in your plan's GeneralSettings supports postal code geocoding. /// </summary> /// <value>The postal code.</value> public string PostalCode { get => _postal_code; set { if (_postal_code != value) { NotifyPropertyChanged(); _postal_code = value; } } } /// <summary> /// Gets or sets the weight load of the stop, used to add weight contraints to the routing algorithm. /// </summary> /// <value>The weight load.</value> public float? WeightLoad { get { return _weight_load; } set { if (value < 0) { throw new BadFieldException("Stop WeightLoad cannot be negative"); } else { if (_weight_load != value) { NotifyPropertyChanged(); _weight_load = value; } } } } /// <summary> /// Gets or sets the volume load of the stop, used to add volume constraints to the routing algorithm. /// </summary> /// <value>The volume load.</value> public float? VolumeLoad { get { return _volume_load; } set { if (value < 0) { throw new BadFieldException("Stop VolumeLoad cannot be negative"); } else { if (_volume_load != value) { NotifyPropertyChanged(); _volume_load = value; } } } } /// <summary> /// Gets or sets the seating load of the stop, used to add seating constraints to the routing algorithm. /// </summary> /// <value>The seating load.</value> public float? SeatingLoad { get { return _seating_load; } set { if (value < 0) { throw new BadFieldException("Stop SeatingLoad cannot be negative"); } else { if (_seating_load != value) { NotifyPropertyChanged(); _seating_load = value; } } } } /// <summary> /// Gets or sets the service time of the stop, additional time in minutes to be spent at this stop. /// </summary> /// <value>The service time.</value> public int? ServiceTime { get => _service_time; set { if (_service_time != value) { NotifyPropertyChanged(); _service_time = value; } } } /// <summary> /// Gets or sets the latitude of the stop. Can be used in place of address. /// </summary> /// <value>The lat.</value> public float? Lat { get => _lat; set { if (_lat != value) { NotifyPropertyChanged(); _lat = value; } } } /// <summary> /// Gets or sets the longtitude of the stop. Can be used in place of address. /// </summary> /// <value>The lng.</value> public float? Lng { get => _lng; set { if (_lng != value) { NotifyPropertyChanged(); _lng = value; } } } /// <summary> /// Gets or sets the start of the time window this stop must be served within. Accepts a value of 0 to 2359. /// </summary> /// <value>From.</value> public int? From { get => _from; set { if (_from != value) { NotifyPropertyChanged(); _from = value; } } } /// <summary> /// Gets or sets the end of the time window this stop must be served within. Accepts a value of 0 to 2359. /// </summary> /// <value>The till.</value> public int? Till { get => _till; set { if (_till != value) { NotifyPropertyChanged(); _till = value; } } } /// <summary> /// After solving the plan, gets the name of the vehicle this stop has been assigned to. /// </summary> /// <value>The assign to.</value> [JsonProperty] public string AssignTo { get; internal set; } /// <summary> /// After solving the plan, gets the run number this stop belongs to. A run number is used to identify a sequence of stops served by the same vehicle before returning to the depot. /// </summary> /// <value>The run.</value> [JsonProperty] public int Run { get; internal set; } /// <summary> /// After solving the plan, gets the sequence number of this stop. Denotes the position of this stop in its run. (i.e. the nth stop in the run) /// </summary> /// <value>The sequence.</value> [JsonProperty] public int Sequence { get; internal set; } /// <summary> /// After solving the plan, gets the estimated time of arrival of the serving vehicle. /// </summary> /// <value>The eta.</value> [JsonProperty] public DateTime Eta { get; internal set; } /// <summary> /// After solving the plan, gets the reason why this stop cannot be served. /// </summary> /// <value>The exception.</value> [JsonProperty] public string Exception { get; internal set; } /// <summary> /// Initializes a new Stop instance with no forms of address. Use the other constructors to pass addresses. You MUST pass a form of address before solving the plan. /// </summary> /// <param name="name">Name of the stop. The name must be unique and the value will automatically be trimmed of whitespace.</param> [JsonConstructor] public Stop(string name) { this.Name = name; } /// <summary> /// Initializes a new Stop instance, using a full address to geocode the location. /// </summary> /// <param name="name">Name of the stop. The name must be unique and the value will automatically be trimmed of whitespace.</param> /// <param name="address">Address of the stop. Include the full address with country for the most accurate results.</param> public Stop(string name, string address) { this.Name = name; this.Address = address; } /// <summary> /// Initializes a new Stop instance, using a set of coordinates to exactly pinpoint the location. /// </summary> /// <param name="name">Name of the stop. The name must be unique and the value will automatically be trimmed of whitespace.</param> /// <param name="lat">Latitude of the stop</param> /// <param name="lng">Longitude of the stop</param> public Stop(String name, float lat, float lng) { this.Name = name; this.Lat = lat; this.Lng = lng; } /// <summary> /// Given a list of stops, checks whether all these stops have valid data. /// </summary> /// <returns><c>true</c>, if all stops validated, <c>false</c> otherwise.</returns> /// <param name="stops">The list of <see cref="Stop"/>s to validate</param> public static bool ValidateStops(List<Stop> stops) { if (stops.Count < 2) { throw new BadFieldException("You must have at least two stops"); } foreach (Stop stop in stops) { bool sameNameStop(Stop v) => v.Name == stop.Name; if (stops.FindAll((Predicate<Stop>)sameNameStop).Count > 1) { throw new BadFieldException("Stop name must be distinct"); } if (stop.Lat == null || stop.Lng == null) { if (stop.Address == null) { throw new BadFieldException("Stop address and coordinates are not given"); } } } return true; } /// <summary> /// Returns a new copy of this instance. /// </summary> /// <returns>The clone.</returns> public Stop Clone() { string json = JsonConvert.SerializeObject(this); return JsonConvert.DeserializeObject<Stop>(json); } /// <summary> /// Copies the attributes of another Stop <paramref name="other"/> such that their public attributes match. /// </summary> /// <param name="other">The other stop to copy from</param> public void Absorb(Stop other) { PropertyInfo[] properties = other.GetType().GetProperties(); foreach (PropertyInfo property in properties) { PropertyInfo internalProperty = this.GetType().GetProperty(property.Name); object value = property.GetValue(other); if (value != null) { Type internalType = internalProperty.PropertyType; Type internalUnderlyingType = Nullable.GetUnderlyingType(internalType); internalProperty.SetValue(this, Convert.ChangeType(value, internalUnderlyingType ?? internalType), null); } else if (value == null) { internalProperty.SetValue(this, null, null); } } } } }
35.8775
256
0.488677
[ "MIT" ]
detrack/elasticroute-dotnet
ElasticRoute/Stop.cs
14,353
C#
using System; namespace Revisao { class Program { static void Main(string[] args) { Aluno [] alunos = new Aluno[5]; var indiceAluno = 0; string opcaoUsuario = ObterOpcaoUsuario(); while (opcaoUsuario.ToUpper() != "X") { switch (opcaoUsuario) { case "1": Console.WriteLine("Informe o nome do aluno"); var aluno = new Aluno(); aluno.Nome = Console.ReadLine(); Console.WriteLine("informe a nota do aluno:"); if (decimal.TryParse(Console.ReadLine(), out decimal nota)){ aluno.Nota = nota; } else{ throw new ArgumentException("Valor da nota deve ser decimal"); } alunos[indiceAluno] = aluno; indiceAluno++; break; case "2": foreach(var a in alunos){ if (!string.IsNullOrEmpty(a.Nome)){ Console.WriteLine($"Aluno: {a.Nome} - Nota: {a.Nota}"); } } break; case "3": var notaTotal = 0; var nrAlunos = 0; for(int i = 0; i< alunos.Length; i++) { if (!string.IsNullOrEmpty(alunos[i].Nome)){ notaTotal = notaTotal + alunos[i].Nota; nrAlunos++; } } var mediaGeral = notaTotal / nrAlunos; Conceito conceitoGeral; if(mediaGeral < 2) { conceitoGeral = Conceito.E; } else if (mediaGeral < 4) { conceitoGeral = Conceito.D; } else if (mediaGeral < 6) { conceitoGeral = Conceito.C; } else if (mediaGeral < 8) { conceitoGeral = Conceito.B; } else { conceitoGeral = Conceito.A; } Console.WriteLine($"Média Geral: {mediaGeral}"); break; default: throw new ArgumentOutOfRangeException(); } opcaoUsuario = ObterOpcaoUsuario(); } } private static string ObterOpcaoUsuario() { Console.WriteLine(); Console.WriteLine("Informe a opção desejada:"); Console.WriteLine("1- Inserer novo aluno"); Console.WriteLine("2- Lista alunos"); Console.WriteLine("-3 Calcular média geral"); Console.WriteLine("X- Sarir"); Console.WriteLine(); string opcaoUsuario = Console.ReadLine(); Console.WriteLine(); return opcaoUsuario; } } }
34.714286
90
0.352263
[ "MIT" ]
JefAlmeida1/DigitalInnovationOne
NET C Sharp/Revisao/Program.cs
3,651
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. public class Test {}
51.5
184
0.76699
[ "Apache-2.0" ]
codemonkey85/roslyn
Src/Compilers/Test/Resources/Core/SymbolsTests/netModule/hash_module.cs
208
C#
using System; using System.Collections.Generic; using System.Text; using SmartSql.Test.Entities; using Xunit; namespace SmartSql.Test.Unit.FlexibleConvert { [Collection("GlobalSmartSql")] public class FlexibleSingleTest : FlexibleTest { protected ISqlMapper SqlMapper { get; } public FlexibleSingleTest(SmartSqlFixture smartSqlFixture) { SqlMapper = smartSqlFixture.SqlMapper; } // TODO [Fact(Skip = "TODO")] public void Test() { var entity = SqlMapper.QuerySingle<FlexibleSingle>(new RequestContext { RealSql = SQL }); Assert.Equal(1, entity.Single); } } }
24.166667
81
0.602759
[ "Apache-2.0" ]
Ahoo-Wang/SmartSql
src/SmartSql.Test.Unit/FlexibleConvert/FlexibleSingleTest.cs
727
C#
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Net; using Microsoft.Azure.Search.Models; using Microsoft.Azure.Test; using Xunit; namespace Microsoft.Azure.Search.Tests.Utilities { public class IndexerFixture : SearchServiceFixture { // The connection string we use here, as well as table name and target index schema, use the usgs database that we set up // to support our code samples. private const string AzureSqlReadOnlyConnectionString = "Server=tcp:azs-playground.database.windows.net,1433;Database=usgs;User ID=reader;Password=EdrERBt3j6mZDP;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"; public IndexerFixture() { SearchServiceClient searchClient = this.GetSearchServiceClient(); TargetIndexName = TestUtilities.GenerateName(); DataSourceName = TestUtilities.GenerateName(); var index = new Index( TargetIndexName, new[] { new Field("feature_id", DataType.String) { IsKey = true }, }); AzureOperationResponse createResponse = searchClient.Indexes.Create(index); Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode); var dataSource = new DataSource( DataSourceName, DataSourceType.AzureSql, new DataSourceCredentials(AzureSqlReadOnlyConnectionString), new DataContainer("GeoNamesRI")); createResponse = searchClient.DataSources.Create(dataSource); Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode); } public string TargetIndexName { get; private set; } public string DataSourceName { get; private set; } public Indexer CreateTestIndexer() { return new Indexer(TestUtilities.GenerateName(), DataSourceName, TargetIndexName) { // We can't test startTime because it's an absolute time that must be within 24 hours of the current // time. That doesn't play well with recorded mock payloads. Schedule = new IndexingSchedule() { Interval = TimeSpan.FromDays(1) } }; } } }
39.356164
232
0.66133
[ "Apache-2.0" ]
CerebralMischief/azure-sdk-for-net
src/Search/Search.Tests/Utilities/IndexerFixture.cs
2,875
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class GeneratedMetadataNames { // This method is intended to match all the generated member names that // the EE (Result Provider) needs to know about (for both VB and C#). // The checks here much more encompassing than the actual set of generated // names that the compilers produce, but that is acceptable (considering // the fact that none of these will be valid language identifiers, and also // the fact that a broad check helps "future proof" this implementation). internal static bool IsCompilerGenerated(this string name) { return name.StartsWith("<", StringComparison.Ordinal) || (name.IndexOf('$') >= 0); } } }
45.952381
160
0.693264
[ "Apache-2.0" ]
0x53A/roslyn
src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/GeneratedMetadataNames.cs
965
C#
using Its.Jenuiue.Core.Actions; using Its.Jenuiue.Core.Database; using Its.Jenuiue.Core.Models.Organization; using MongoDB.Driver; namespace Its.Jenuiue.Core.Actions.Registration { public class AddRegistrationAction : BaseActionAdd { private readonly string collName = "registrations"; public AddRegistrationAction(IDatabase conn, string orgId) { Init(conn, orgId); IMongoCollection<MRegistration> coll = GetCollection<MRegistration>(); var option = new CreateIndexOptions() { Unique = true }; var pdIdField = new StringFieldDefinition<MRegistration>("RegistrationId"); var indexDefinition = new IndexKeysDefinitionBuilder<MRegistration>().Ascending(pdIdField); var idxModel = new CreateIndexModel<MRegistration>(indexDefinition, option); coll.Indexes.CreateOne(idxModel); } protected override string GetCollectionName() { return collName; } } }
30.228571
103
0.649338
[ "Apache-2.0" ]
its-software-services-jenuine/jenuine-core
jenuine-core/Actions/Registration/AddRegistrationAction.cs
1,058
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Reinforced.Typings; using Reinforced.Typings.Ast; using Reinforced.Typings.Ast.TypeNames; using Reinforced.Typings.Fluent; using Reinforced.Typings.Generators; namespace SignalRTypeScriptHubGenerator { public static class SignalRTypeScriptHubGeneratorExtensions { public static void GenerateSignalRTypeScriptHub(this ConfigurationBuilder builder, HubConnectionProviderReference hubConnectionProviderReference, Type hub, string hubPattern, string namespaceFilter) { var serverType = hub; var frontendType = hub.BaseType.GetGenericArguments()[0]; builder.Global(c => c.UseModules()); builder.AddImport("{ Injectable }", "@angular/core"); builder.AddImport("{ HubConnection }", "@microsoft/signalr"); builder.AddImport("{ SignalDispatcher, SimpleEventDispatcher }", "strongly-typed-events"); builder.AddImport(hubConnectionProviderReference.Target, hubConnectionProviderReference.From); builder.Substitute(typeof(Task), new RtSimpleTypeName("Promise<void>")); builder.Substitute(typeof(Task<>), new RtSimpleTypeName("Promise")); builder.Substitute(typeof(DateTime), new RtSimpleTypeName("Date")); builder.Substitute(typeof(Uri), new RtSimpleTypeName("string")); var relatedTypes = new HashSet<Type>(); relatedTypes.UnionWith(TraverseTypes(serverType, namespaceFilter)); relatedTypes.UnionWith(TraverseTypes(frontendType, namespaceFilter)); relatedTypes.Remove(serverType); relatedTypes.Remove(frontendType); var relatedClassTypes = relatedTypes.Where(t => t.IsClass); var relatedEnumTypes = relatedTypes.Where(t => t.IsEnum); var otherTypes = relatedTypes.Where(t => !(t.IsClass || t.IsEnum)); Func<Type, int> orderFunc = relatedTypes.SelectMany(t => EnumerateHierarchy(t, e => e.BaseType).Reverse()).ToList().IndexOf; builder.ExportAsEnums(relatedEnumTypes, c => c.Order(orderFunc(c.Type))); builder.ExportAsClasses(relatedClassTypes, c => c.WithPublicProperties().WithPublicFields().WithPublicMethods().Order(orderFunc(c.Type))); builder.ExportAsInterfaces(otherTypes, c => c.WithPublicProperties().WithPublicFields().WithPublicMethods().Order(orderFunc(c.Type))); builder.ExportAsInterfaces(new[] {serverType}, c => c.WithPublicProperties().WithPublicFields().WithPublicMethods().WithCodeGenerator<ServerClientAppender>()); builder.ExportAsInterfaces(new[] {frontendType}, c => c.WithPublicProperties().WithPublicFields().WithPublicMethods().WithCodeGenerator<FrontEndClientAppender>()); } private static IEnumerable<T> EnumerateHierarchy<T>(T item, Func<T, T> selector) where T : class { do { yield return item; item = selector(item); } while (item != default(T)); } public static IEnumerable<Type> TraverseTypes(Type type, string namespaceFilter) { return TraverseTypes(type, namespaceFilter, new List<Type>()); } public static IEnumerable<Type> TraverseTypes(Type type, string namespaceFilter, List<Type> visited) { visited.Add(type); var types = new HashSet<Type>(); types.UnionWith(type.GetInterfaces()); types.UnionWith(GetBaseClassIfAny(type)); types.UnionWith(TraverseMethods(type)); types.UnionWith(TraverseProperties(type)); types.UnionWith(types.ToList().SelectMany(t => visited.Contains(t) ? new List<Type>() : TraverseTypes(t, namespaceFilter, visited))); types.IntersectWith(types.Where(t => t.Namespace != null && t.Namespace.StartsWith(namespaceFilter))); types.ExceptWith(types.ToList().Where(t => t.IsByRef || t.IsArray)); types.Add(type); return types; } private static IEnumerable<Type> GetBaseClassIfAny(Type type) { return type.BaseType == null ? new Type[0] : new[] { type.BaseType }; } private static IEnumerable<Type> TraverseProperties(Type type) { return type.GetProperties().SelectMany(HandleProperty); } private static IEnumerable<Type> TraverseMethods(Type type) { var types = new HashSet<Type>(); types.UnionWith(type.GetMethods().SelectMany(HandleReturnType)); types.UnionWith(type.GetMethods().SelectMany(m => m.GetParameters().SelectMany(HandleParameters))); return types; } private static IEnumerable<Type> HandleParameters(ParameterInfo p) { var types = new HashSet<Type> { p.ParameterType }; if (p.ParameterType.IsGenericType) { types.UnionWith(p.ParameterType.GetGenericArguments()); } return types; } private static IEnumerable<Type> HandleReturnType(MethodInfo m) { var types = new HashSet<Type> { m.ReturnType }; if (m.ReturnType.IsGenericType) { types.UnionWith(m.ReturnType.GetGenericArguments()); } return types; } private static IEnumerable<Type> HandleProperty(PropertyInfo p) { var types = new HashSet<Type> { p.PropertyType }; if (p.PropertyType.IsGenericType) { types.UnionWith(p.PropertyType.GetGenericArguments()); } return types; } } internal abstract class ClientAppenderBase : InterfaceCodeGenerator { public override RtInterface GenerateNode(Type element, RtInterface result, TypeResolver resolver) { var existing = base.GenerateNode(element, result, resolver); if (existing == null) return null; if (Context.Location.CurrentNamespace == null) return existing; ClientAppenderImpl(element, result, resolver); return ReturnExisting() ? existing : null; } protected virtual bool ReturnExisting() { return true; } protected abstract void ClientAppenderImpl(Type element, RtInterface result, TypeResolver resolver); } internal class ServerClientAppender : ClientAppenderBase { protected override void ClientAppenderImpl(Type element, RtInterface result, TypeResolver resolver) { var clientImpl = new RtClass() { Name = new RtSimpleTypeName($"{element.Name}Client"), Export = true, Decorators = { new RtDecorator("Injectable()\r\n") }, Implementees = { result.Name }, Members = { new RtField { AccessModifier = AccessModifier.Private, Identifier = new RtIdentifier("hubConnection"), Type = new RtSimpleTypeName("Promise<HubConnection>") }, new RtConstructor { Arguments = { new RtArgument { Type = new RtSimpleTypeName("HubConnectionProvider"), Identifier = new RtIdentifier("hubConnectionProvider") }}, Body = new RtRaw("this.hubConnection = hubConnectionProvider.getHubConnection(\"/hub\");"), } }, }; clientImpl.Members.AddRange(GetImplementationMembers(result)); Context.Location.CurrentNamespace.CompilationUnits.Add(clientImpl); } private IEnumerable<RtNode> GetImplementationMembers(RtInterface result) { var functions = result.Members.OfType<RtFuncion>(); foreach (var function in functions) { var arguments = function.Arguments.Select(a => a.Identifier.ToString()); function.Body = new RtRaw($"return this.hubConnection.then(hub => hub.invoke(\"{function.Identifier.IdentifierName}\",{string.Join(",", arguments)}));"); } return functions; } } internal class FrontEndClientAppender : ClientAppenderBase { protected override bool ReturnExisting() { return false; } protected override void ClientAppenderImpl(Type element, RtInterface result, TypeResolver resolver) { var typeName = element.IsInterface && element.Name.StartsWith('I') ? element.Name.Substring(1) : element.Name; var clientImpl = new RtClass { Name = new RtSimpleTypeName(typeName), Export = true, Decorators = { new RtDecorator("Injectable()\r\n") }, }; clientImpl.Members.AddRange(GetImplementationMembers(result)); Context.Location.CurrentNamespace.CompilationUnits.Add(clientImpl); } private IEnumerable<RtNode> GetImplementationMembers(RtInterface result) { var members = new List<RtNode>(); var functions = result.Members.OfType<RtFuncion>(); foreach (var function in functions) { var rtTypeNames = function.Arguments.Select(a => a.Type.ToString()).ToList(); var generics = string.Join(",", rtTypeNames); if (rtTypeNames.Count > 1) { generics = $"[{generics}]"; } var stringType = rtTypeNames.Count == 0 ? "SignalDispatcher" : $"SimpleEventDispatcher<{generics}>"; var eventDispatcher = new RtField { AccessModifier = AccessModifier.Public, Identifier = new RtIdentifier($"on{function.Identifier.ToString().FirstCharToUpper()}"), Type = new RtSimpleTypeName(stringType), InitializationExpression = $"new {stringType}()" }; members.Add(eventDispatcher); } members.Add(new RtConstructor { Arguments = { new RtArgument { Type = new RtSimpleTypeName("HubConnectionProvider"), Identifier = new RtIdentifier("hubConnectionProvider") }}, Body = GetEventRegistrationBody(functions) }); return members; } private RtRaw GetEventRegistrationBody(IEnumerable<RtFuncion> functions) { var pre = "hubConnectionProvider.getHubConnection(\"/hub\").then(hubConnection => {\r\n"; var e = functions.Select(f => { var args = f.Arguments.Select(a => $"{a.Identifier} : {a.Type}").ToList(); var response = $"({string.Join(",", args)})"; var commaArgs = string.Join(",", f.Arguments.Select(a => a.Identifier)); if (args.Count > 1) { commaArgs = $"[{commaArgs}]"; } return $" hubConnection.on(\"{f.Identifier}\", {response} => {{\r\n console.log(\"{f.Identifier} received from server\", {commaArgs});\r\n this.on{f.Identifier.ToString().FirstCharToUpper()}.dispatch({commaArgs});\r\n }});"; }); var post = "\r\n});"; return new RtRaw(pre + string.Join("\r\n", e) + post); } } }
43.360714
255
0.574088
[ "MIT" ]
mathiasi/SignalRTypeScriptHubGenerator
SignalRTypeScriptHubGenerator/SignalRTypeScriptHubGeneratorExtensions.cs
12,143
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.CodeAnalysis.Elfie.Model.Strings; using XForm.Data; using XForm.Query; namespace XForm.Columns { /// <summary> /// SingleValueColumn implements IXColumn for a single value that is not known before Next() /// </summary> public class SingleValueColumn : IXColumn { public ColumnDetails ColumnDetails { get; private set; } private bool _isNull; private Array _array; private IXTable _source; public SingleValueColumn(IXTable source, string columnName, Type type) { _source = source; Allocator.AllocateToSize(ref _array, 1, type); ColumnDetails = new ColumnDetails(columnName, type); } public void Set(object value) { _array.SetValue(value, 0); _isNull = (value == null || value.Equals("null")); } private XArray Get() { return (_isNull ? XArray.Null(_array, _source.CurrentRowCount) : XArray.Single(_array, _source.CurrentRowCount)); } public Func<XArray> CurrentGetter() { return () => Get(); } public Func<ArraySelector, XArray> SeekGetter() { return null; } public Func<XArray> ValuesGetter() { return null; } public Type IndicesType => null; public Func<XArray> IndicesCurrentGetter() { return null; } public Func<ArraySelector, XArray> IndicesSeekGetter() { return null; } public Func<object> ComponentGetter(string componentName) { return null; } public override string ToString() { return XqlScanner.Escape((_array.GetValue(0) ?? "null").ToString(), TokenType.Value, (_isNull || ColumnDetails.Type != typeof(String8))); } } }
25.802469
149
0.584689
[ "MIT" ]
Bhaskers-Blu-Org2/elfie-arriba
XForm/XForm/Columns/SingleValueColumn.cs
2,092
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using MultiagentEngine.Pulse.Map; using Pulse.Common; using Pulse.Common.ConfigSystem; using Pulse.Common.Model.Agent; using Pulse.Common.Model.Environment; using Pulse.Common.Model.Environment.Poi; using Pulse.Common.Model.Legend; using Pulse.Common.PluginSystem.Spawn; using Pulse.Common.PluginSystem.Util; using Pulse.Common.Pseudo3D; using Pulse.Common.Scenery.Loaders; using Pulse.Common.Utils; using Pulse.GraphUtil; namespace $pulsepre$$safeprojectname$ { public class $safeprojectname$SceneryFactory : ISceneryFactory { public ILegendable GetRoleManager(string name, IPopulationManager pm) { return null; // new SocioRoleLegend(pm.SocioClasses); } public void BuildScenery(PulseScenarioConfig config, GeoCartesUtil gcu, AbstractPulsePluginFactory plgnf, ref AbstractExternalPortalBuilder prtlm, ref PulseScenery sb) { #region config var inFileRel = @"scenery\map.json"; var outFileRel = @"scenery\map_qtg.json"; var offset = new Coords(0, 0); var qtConfig = new QuadTreeConfig { BottomLeftCorner = new Coords(-20, -20), Size = 160, MinSize = 0.5, MaxSize = 4 }; var pjrCfg = new PulseJsonReaderConfig { Levels = true, Way = true, Obstacle = true, Poi = true, Portal = true, Zone = false, Offset = offset }; #endregion AutoGraphCheck(config, offset, qtConfig, inFileRel, outFileRel); var pjr = new PulseJsonReader("Pulse json reader", pjrCfg, config.DataDir.Value, outFileRel); pjr.Initialize(); prtlm = new SimplePortalBuilder(pjr.PulseObject, GetSimplePortalLoaders()); prtlm.Initialize(); var slm = new SimpleLevelsBuilder(pjr.PulseObject, prtlm.Portals, null); slm.Initialize(); var ssgp = new SimpleGraphBuilder(slm.Levels, pjr.PulseObject); ssgp.Initialize(); sb = new PulseScenery { Levels = slm.Levels, Graph = ssgp.Graph }; RegisterPlugins(sb, plgnf); } private void AutoGraphCheck(PulseScenarioConfig config, Coords offset, QuadTreeConfig qtConfig, string inFileRel, string outFileRel) { var inFileAbs = Path.Combine(config.DataDir.Value, inFileRel); var outFileAbs = Path.Combine(config.DataDir.Value, outFileRel); if (File.Exists(inFileAbs)) { var pjrCfgMap = new PulseJsonReaderConfig { Levels = true, Obstacle = true, Poi = true, Portal = true, Offset = offset }; var pjrMap = new PulseJsonReader("Pulse json reader", pjrCfgMap, config.DataDir.Value, inFileRel); pjrMap.Initialize(); if (File.Exists(outFileAbs)) { var pjrQtgHyp = new PulseJsonReader("Pulse json reader", pjrCfgMap, config.DataDir.Value, outFileRel); pjrQtgHyp.Initialize(); if (pjrMap.PulseObject.Version == pjrQtgHyp.PulseObject.Version) { return; } } var prtlmMap = new SimplePortalBuilder(pjrMap.PulseObject, GetSimplePortalLoaders()); prtlmMap.Initialize(); var slmMap = new SimpleLevelsBuilder(pjrMap.PulseObject, prtlmMap.Portals, null); slmMap.Initialize(); var maxx = slmMap.Levels.First().Value.Obstacles.Max(o => o.Max(p => p.X)) + 1; var maxy = slmMap.Levels.First().Value.Obstacles.Max(o => o.Max(p => p.Y)) + 1; var minx = slmMap.Levels.First().Value.Obstacles.Min(o => o.Min(p => p.X)) + 1; var miny = slmMap.Levels.First().Value.Obstacles.Min(o => o.Min(p => p.Y)) + 1; var qtgl = new MultilevelQuadTreeGraphLoader(slmMap.Levels, qtConfig); qtgl.Initialize(); qtgl.AddOrUpdateGraph(inFileAbs, outFileAbs, qtgl.LeveledSubGraphs); } } private IDictionary<string, Func<ILevelPortal, IExternalPortal>> GetSimplePortalLoaders() { return new Dictionary<string, Func<ILevelPortal, IExternalPortal>> { {"example_killer", portal => new ExternalPortal(portal)}, {"example_generator", portal => { var ep = new ExternalPortal(portal); ep.AgentGenerator = new $safeprojectname$SimpleAgentsGenerator(ep); return ep; } } }; } private void RegisterPlugins(PulseScenery building, AbstractPulsePluginFactory plgnf) { building.Levels.Values.ToList().ForEach(l => l.PointsOfInterest.ToList().ForEach(poi => poi.RegisterPugins(plgnf.GetPluginsForBuilding()))); building.Levels.Values.ToList().ForEach(l => l.ExternalPortals.ToList().ForEach(p => p.RegisterPugins(plgnf.GetPluginsForBuilding()))); building.Levels.Values.ToList().ForEach(l => l.LevelPortals.ToList().ForEach(p => p.RegisterPugins(plgnf.GetPluginsForBuilding()))); } } }
36.120253
152
0.569476
[ "MIT" ]
vladkar/pulse-project-open
Pulse.Template.Scenery/TemplateSceneryFactory.cs
5,709
C#
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Testing.VoidReturn.Snippets { // [START unknown_generated_VoidReturn_VoidMethod_sync] using Testing.VoidReturn; public sealed partial class GeneratedVoidReturnClientSnippets { /// <summary>Snippet for VoidMethod</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void VoidMethodRequestObject() { // Create client VoidReturnClient voidReturnClient = VoidReturnClient.Create(); // Initialize request argument(s) Request request = new Request { ResourceName = ResourceName.FromItem("[ITEM_ID]"), }; // Make the request voidReturnClient.VoidMethod(request); } } // [END unknown_generated_VoidReturn_VoidMethod_sync] }
36.068182
89
0.672968
[ "Apache-2.0" ]
LaudateCorpus1/gapic-generator-csharp
Google.Api.Generator.Tests/ProtoTests/VoidReturn/Testing.VoidReturn.GeneratedSnippets/VoidReturnClient.VoidMethodRequestObjectSnippet.g.cs
1,589
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace NMaier.GetOptNet { internal sealed class EnumArgumentHandler : ArgumentHandler { private readonly ArgumentCollision collision; private readonly Dictionary<string, string> names; public EnumArgumentHandler(object handledObject, MemberInfo memberInfo, Type elementType, ArgumentCollision collision, bool required) : base(handledObject, memberInfo, elementType, false, required) { this.collision = collision; names = (from e in Enum.GetNames(elementType) select new {Key = e.ToLowerInvariant(), Value = e}).ToDictionary(v => v.Key, v => v.Value); } internal override void Assign(string toAssign) { try { if (!ShouldAssign(collision)) { return; } toAssign = names[toAssign.ToLowerInvariant()]; InternalAssign(Enum.Parse(ElementType, toAssign)); } catch (Exception) { var allowed = GetOpt.FormatEnum(ElementType); throw new NotSupportedException($"Invalid value {toAssign}, must be one of {allowed}"); } } } }
30
106
0.674359
[ "MIT" ]
lilggamegenius/getoptnet
Handlers/EnumArgumentHandler.cs
1,170
C#
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2015/03/29 22:56 using System; using DG.Tweening.Core; using DG.Tweening.Core.Easing; using DG.Tweening.Core.Enums; using DG.Tweening.Plugins.Core; using DG.Tweening.Plugins.Options; #pragma warning disable 1591 namespace DG.Tweening.Plugins { public class LongPlugin : ABSTweenPlugin<long, long, NoOptions> { public override void Reset(TweenerCore<long, long, NoOptions> t) { } public override void SetFrom(TweenerCore<long, long, NoOptions> t, bool isRelative) { long prevEndVal = t.endValue; t.endValue = t.getter(); t.startValue = isRelative ? t.endValue + prevEndVal : prevEndVal; t.setter(t.startValue); } public override long ConvertToStartValue(TweenerCore<long, long, NoOptions> t, long value) { return value; } public override void SetRelativeEndValue(TweenerCore<long, long, NoOptions> t) { t.endValue += t.startValue; } public override void SetChangeValue(TweenerCore<long, long, NoOptions> t) { t.changeValue = t.endValue - t.startValue; } public override float GetSpeedBasedDuration(NoOptions options, float unitsXSecond, long changeValue) { float res = changeValue / unitsXSecond; if (res < 0) res = -res; return res; } public override void EvaluateAndApply(NoOptions options, Tween t, bool isRelative, DOGetter<long> getter, DOSetter<long> setter, float elapsed, long startValue, long changeValue, float duration, bool usingInversePosition, UpdateNotice updateNotice) { if (t.loopType == LoopType.Incremental) startValue += changeValue * (t.isComplete ? t.completedLoops - 1 : t.completedLoops); if (t.isSequenced && t.sequenceParent.loopType == LoopType.Incremental) { startValue += changeValue * (t.loopType == LoopType.Incremental ? t.loops : 1) * (t.sequenceParent.isComplete ? t.sequenceParent.completedLoops - 1 : t.sequenceParent.completedLoops); } setter((long)Math.Round(startValue + changeValue * EaseManager.Evaluate(t.easeType, t.customEase, elapsed, duration, t.easeOvershootOrAmplitude, t.easePeriod))); } } }
40.40678
256
0.651846
[ "MIT" ]
JansonC/knight
knight-client/Packages/Knight-Lib/Knight.Framework.Tweening/Runtime/DOTween/Plugins/LongPlugin.cs
2,386
C#
namespace SampleEndpointApp.DomainModel; public class Author : BaseEntity { public string Name { get; set; } = null!; public string PluralsightUrl { get; set; } = null!; public string? TwitterAlias { get; set; } }
24.666667
53
0.702703
[ "MIT" ]
ScriptBox99/ApiEndpoints
sample/SampleEndpointApp/DomainModel/Author.cs
224
C#
using Sharpen; namespace android.view { /// <summary>Interface for managing the items in a menu.</summary> /// <remarks> /// Interface for managing the items in a menu. /// <p> /// By default, every Activity supports an options menu of actions or options. /// You can add items to this menu and handle clicks on your additions. The /// easiest way of adding menu items is inflating an XML file into the /// <see cref="Menu">Menu</see> /// via /// <see cref="MenuInflater">MenuInflater</see> /// . The easiest way of attaching code to /// clicks is via /// <see cref="android.app.Activity.onOptionsItemSelected(MenuItem)">android.app.Activity.onOptionsItemSelected(MenuItem) /// </see> /// and /// <see cref="android.app.Activity.onContextItemSelected(MenuItem)">android.app.Activity.onContextItemSelected(MenuItem) /// </see> /// . /// <p> /// Different menu types support different features: /// <ol> /// <li><b>Context menus</b>: Do not support item shortcuts and item icons. /// <li><b>Options menus</b>: The <b>icon menus</b> do not support item check /// marks and only show the item's /// <see cref="MenuItem.setTitleCondensed(java.lang.CharSequence)">condensed title</see> /// . The /// <b>expanded menus</b> (only available if six or more menu items are visible, /// reached via the 'More' item in the icon menu) do not show item icons, and /// item check marks are discouraged. /// <li><b>Sub menus</b>: Do not support item icons, or nested sub menus. /// </ol> /// <div class="special reference"> /// <h3>Developer Guides</h3> /// <p>For more information about creating menus, read the /// &lt;a href=" /// <docRoot></docRoot> /// guide/topics/ui/menus.html"&gt;Menus</a> developer guide.</p> /// </div> /// </remarks> [Sharpen.Sharpened] public interface Menu { // Implementation note: Keep these CATEGORY_* in sync with the category enum // in attrs.xml /// <summary>Add a new item to the menu.</summary> /// <remarks> /// Add a new item to the menu. This item displays the given title for its /// label. /// </remarks> /// <param name="title">The text to display for the item.</param> /// <returns>The newly added menu item.</returns> android.view.MenuItem add(java.lang.CharSequence title); /// <summary>Add a new item to the menu.</summary> /// <remarks> /// Add a new item to the menu. This item displays the given title for its /// label. /// </remarks> /// <param name="titleRes">Resource identifier of title string.</param> /// <returns>The newly added menu item.</returns> android.view.MenuItem add(int titleRes); /// <summary>Add a new item to the menu.</summary> /// <remarks> /// Add a new item to the menu. This item displays the given title for its /// label. /// </remarks> /// <param name="groupId"> /// The group identifier that this item should be part of. /// This can be used to define groups of items for batch state /// changes. Normally use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if an item should not be in a /// group. /// </param> /// <param name="itemId"> /// Unique item ID. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not need a /// unique ID. /// </param> /// <param name="order"> /// The order for the item. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not care /// about the order. See /// <see cref="MenuItem.getOrder()">MenuItem.getOrder()</see> /// . /// </param> /// <param name="title">The text to display for the item.</param> /// <returns>The newly added menu item.</returns> android.view.MenuItem add(int groupId, int itemId, int order, java.lang.CharSequence title); /// <summary> /// Variation on /// <see cref="add(int, int, int, java.lang.CharSequence)">add(int, int, int, java.lang.CharSequence) /// </see> /// that takes a /// string resource identifier instead of the string itself. /// </summary> /// <param name="groupId"> /// The group identifier that this item should be part of. /// This can also be used to define groups of items for batch state /// changes. Normally use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if an item should not be in a /// group. /// </param> /// <param name="itemId"> /// Unique item ID. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not need a /// unique ID. /// </param> /// <param name="order"> /// The order for the item. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not care /// about the order. See /// <see cref="MenuItem.getOrder()">MenuItem.getOrder()</see> /// . /// </param> /// <param name="titleRes">Resource identifier of title string.</param> /// <returns>The newly added menu item.</returns> android.view.MenuItem add(int groupId, int itemId, int order, int titleRes); /// <summary>Add a new sub-menu to the menu.</summary> /// <remarks> /// Add a new sub-menu to the menu. This item displays the given title for /// its label. To modify other attributes on the submenu's menu item, use /// <see cref="SubMenu.getItem()">SubMenu.getItem()</see> /// . /// </remarks> /// <param name="title">The text to display for the item.</param> /// <returns>The newly added sub-menu</returns> android.view.SubMenu addSubMenu(java.lang.CharSequence title); /// <summary>Add a new sub-menu to the menu.</summary> /// <remarks> /// Add a new sub-menu to the menu. This item displays the given title for /// its label. To modify other attributes on the submenu's menu item, use /// <see cref="SubMenu.getItem()">SubMenu.getItem()</see> /// . /// </remarks> /// <param name="titleRes">Resource identifier of title string.</param> /// <returns>The newly added sub-menu</returns> android.view.SubMenu addSubMenu(int titleRes); /// <summary>Add a new sub-menu to the menu.</summary> /// <remarks> /// Add a new sub-menu to the menu. This item displays the given /// <var>title</var> for its label. To modify other attributes on the /// submenu's menu item, use /// <see cref="SubMenu.getItem()">SubMenu.getItem()</see> /// . /// <p> /// Note that you can only have one level of sub-menus, i.e. you cannnot add /// a subMenu to a subMenu: An /// <see cref="System.NotSupportedException">System.NotSupportedException</see> /// will be /// thrown if you try. /// </remarks> /// <param name="groupId"> /// The group identifier that this item should be part of. /// This can also be used to define groups of items for batch state /// changes. Normally use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if an item should not be in a /// group. /// </param> /// <param name="itemId"> /// Unique item ID. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not need a /// unique ID. /// </param> /// <param name="order"> /// The order for the item. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not care /// about the order. See /// <see cref="MenuItem.getOrder()">MenuItem.getOrder()</see> /// . /// </param> /// <param name="title">The text to display for the item.</param> /// <returns>The newly added sub-menu</returns> android.view.SubMenu addSubMenu(int groupId, int itemId, int order, java.lang.CharSequence title); /// <summary> /// Variation on /// <see cref="addSubMenu(int, int, int, java.lang.CharSequence)">addSubMenu(int, int, int, java.lang.CharSequence) /// </see> /// that takes /// a string resource identifier for the title instead of the string itself. /// </summary> /// <param name="groupId"> /// The group identifier that this item should be part of. /// This can also be used to define groups of items for batch state /// changes. Normally use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if an item should not be in a group. /// </param> /// <param name="itemId"> /// Unique item ID. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not need a unique ID. /// </param> /// <param name="order"> /// The order for the item. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not care about the /// order. See /// <see cref="MenuItem.getOrder()">MenuItem.getOrder()</see> /// . /// </param> /// <param name="titleRes">Resource identifier of title string.</param> /// <returns>The newly added sub-menu</returns> android.view.SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes); /// <summary> /// Add a group of menu items corresponding to actions that can be performed /// for a particular Intent. /// </summary> /// <remarks> /// Add a group of menu items corresponding to actions that can be performed /// for a particular Intent. The Intent is most often configured with a null /// action, the data that the current activity is working with, and includes /// either the /// <see cref="android.content.Intent.CATEGORY_ALTERNATIVE">android.content.Intent.CATEGORY_ALTERNATIVE /// </see> /// or /// <see cref="android.content.Intent.CATEGORY_SELECTED_ALTERNATIVE">android.content.Intent.CATEGORY_SELECTED_ALTERNATIVE /// </see> /// to find activities that have /// said they would like to be included as optional action. You can, however, /// use any Intent you want. /// <p> /// See /// <see cref="android.content.pm.PackageManager.queryIntentActivityOptions(android.content.ComponentName, android.content.Intent[], android.content.Intent, int) /// ">android.content.pm.PackageManager.queryIntentActivityOptions(android.content.ComponentName, android.content.Intent[], android.content.Intent, int) /// </see> /// for more * details on the <var>caller</var>, <var>specifics</var>, and /// <var>intent</var> arguments. The list returned by that function is used /// to populate the resulting menu items. /// <p> /// All of the menu items of possible options for the intent will be added /// with the given group and id. You can use the group to control ordering of /// the items in relation to other items in the menu. Normally this function /// will automatically remove any existing items in the menu in the same /// group and place a divider above and below the added items; this behavior /// can be modified with the <var>flags</var> parameter. For each of the /// generated items /// <see cref="MenuItem.setIntent(android.content.Intent)">MenuItem.setIntent(android.content.Intent) /// </see> /// is called to associate the /// appropriate Intent with the item; this means the activity will /// automatically be started for you without having to do anything else. /// </remarks> /// <param name="groupId"> /// The group identifier that the items should be part of. /// This can also be used to define groups of items for batch state /// changes. Normally use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if the items should not be in /// a group. /// </param> /// <param name="itemId"> /// Unique item ID. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not need a /// unique ID. /// </param> /// <param name="order"> /// The order for the items. Use /// <see cref="android.view.MenuClass.NONE">android.view.MenuClass.NONE</see> /// if you do not /// care about the order. See /// <see cref="MenuItem.getOrder()">MenuItem.getOrder()</see> /// . /// </param> /// <param name="caller"> /// The current activity component name as defined by /// queryIntentActivityOptions(). /// </param> /// <param name="specifics"> /// Specific items to place first as defined by /// queryIntentActivityOptions(). /// </param> /// <param name="intent"> /// Intent describing the kinds of items to populate in the /// list as defined by queryIntentActivityOptions(). /// </param> /// <param name="flags">Additional options controlling how the items are added.</param> /// <param name="outSpecificItems"> /// Optional array in which to place the menu items /// that were generated for each of the <var>specifics</var> that were /// requested. Entries may be null if no activity was found for that /// specific action. /// </param> /// <returns>The number of menu items that were added.</returns> /// <seealso cref="android.view.MenuClass.FLAG_APPEND_TO_GROUP">android.view.MenuClass.FLAG_APPEND_TO_GROUP /// </seealso> /// <seealso cref="MenuItem.setIntent(android.content.Intent)">MenuItem.setIntent(android.content.Intent) /// </seealso> /// <seealso cref="android.content.pm.PackageManager.queryIntentActivityOptions(android.content.ComponentName, android.content.Intent[], android.content.Intent, int) /// ">android.content.pm.PackageManager.queryIntentActivityOptions(android.content.ComponentName, android.content.Intent[], android.content.Intent, int) /// </seealso> int addIntentOptions(int groupId, int itemId, int order, android.content.ComponentName caller, android.content.Intent[] specifics, android.content.Intent intent, int flags, android.view.MenuItem[] outSpecificItems); /// <summary>Remove the item with the given identifier.</summary> /// <remarks>Remove the item with the given identifier.</remarks> /// <param name="id"> /// The item to be removed. If there is no item with this /// identifier, nothing happens. /// </param> void removeItem(int id); /// <summary>Remove all items in the given group.</summary> /// <remarks>Remove all items in the given group.</remarks> /// <param name="groupId"> /// The group to be removed. If there are no items in this /// group, nothing happens. /// </param> void removeGroup(int groupId); /// <summary> /// Remove all existing items from the menu, leaving it empty as if it had /// just been created. /// </summary> /// <remarks> /// Remove all existing items from the menu, leaving it empty as if it had /// just been created. /// </remarks> void clear(); /// <summary>Control whether a particular group of items can show a check mark.</summary> /// <remarks> /// Control whether a particular group of items can show a check mark. This /// is similar to calling /// <see cref="MenuItem.setCheckable(bool)">MenuItem.setCheckable(bool)</see> /// on all of the menu items /// with the given group identifier, but in addition you can control whether /// this group contains a mutually-exclusive set items. This should be called /// after the items of the group have been added to the menu. /// </remarks> /// <param name="group">The group of items to operate on.</param> /// <param name="checkable"> /// Set to true to allow a check mark, false to /// disallow. The default is false. /// </param> /// <param name="exclusive"> /// If set to true, only one item in this group can be /// checked at a time; checking an item will automatically /// uncheck all others in the group. If set to false, each /// item can be checked independently of the others. /// </param> /// <seealso cref="MenuItem.setCheckable(bool)">MenuItem.setCheckable(bool)</seealso> /// <seealso cref="MenuItem.setChecked(bool)">MenuItem.setChecked(bool)</seealso> void setGroupCheckable(int group, bool checkable, bool exclusive); /// <summary>Show or hide all menu items that are in the given group.</summary> /// <remarks>Show or hide all menu items that are in the given group.</remarks> /// <param name="group">The group of items to operate on.</param> /// <param name="visible">If true the items are visible, else they are hidden.</param> /// <seealso cref="MenuItem.setVisible(bool)">MenuItem.setVisible(bool)</seealso> void setGroupVisible(int group, bool visible); /// <summary>Enable or disable all menu items that are in the given group.</summary> /// <remarks>Enable or disable all menu items that are in the given group.</remarks> /// <param name="group">The group of items to operate on.</param> /// <param name="enabled">If true the items will be enabled, else they will be disabled. /// </param> /// <seealso cref="MenuItem.setEnabled(bool)">MenuItem.setEnabled(bool)</seealso> void setGroupEnabled(int group, bool enabled); /// <summary>Return whether the menu currently has item items that are visible.</summary> /// <remarks>Return whether the menu currently has item items that are visible.</remarks> /// <returns> /// True if there is one or more item visible, /// else false. /// </returns> bool hasVisibleItems(); /// <summary>Return the menu item with a particular identifier.</summary> /// <remarks>Return the menu item with a particular identifier.</remarks> /// <param name="id">The identifier to find.</param> /// <returns> /// The menu item object, or null if there is no item with /// this identifier. /// </returns> android.view.MenuItem findItem(int id); /// <summary>Get the number of items in the menu.</summary> /// <remarks> /// Get the number of items in the menu. Note that this will change any /// times items are added or removed from the menu. /// </remarks> /// <returns>The item count.</returns> int size(); /// <summary>Gets the menu item at the given index.</summary> /// <remarks>Gets the menu item at the given index.</remarks> /// <param name="index">The index of the menu item to return.</param> /// <returns>The menu item.</returns> /// <exception> /// IndexOutOfBoundsException /// when /// <code>index &lt; 0 || &gt;= size()</code> /// </exception> android.view.MenuItem getItem(int index); /// <summary>Closes the menu, if open.</summary> /// <remarks>Closes the menu, if open.</remarks> void close(); /// <summary> /// Execute the menu item action associated with the given shortcut /// character. /// </summary> /// <remarks> /// Execute the menu item action associated with the given shortcut /// character. /// </remarks> /// <param name="keyCode">The keycode of the shortcut key.</param> /// <param name="event">Key event message.</param> /// <param name="flags">Additional option flags or 0.</param> /// <returns> /// If the given shortcut exists and is shown, returns /// true; else returns false. /// </returns> /// <seealso cref="android.view.MenuClass.FLAG_PERFORM_NO_CLOSE">android.view.MenuClass.FLAG_PERFORM_NO_CLOSE /// </seealso> bool performShortcut(int keyCode, android.view.KeyEvent @event, int flags); /// <summary>Is a keypress one of the defined shortcut keys for this window.</summary> /// <remarks>Is a keypress one of the defined shortcut keys for this window.</remarks> /// <param name="keyCode"> /// the key code from /// <see cref="KeyEvent">KeyEvent</see> /// to check. /// </param> /// <param name="event"> /// the /// <see cref="KeyEvent">KeyEvent</see> /// to use to help check. /// </param> bool isShortcutKey(int keyCode, android.view.KeyEvent @event); /// <summary>Execute the menu item action associated with the given menu identifier.</summary> /// <remarks>Execute the menu item action associated with the given menu identifier.</remarks> /// <param name="id">Identifier associated with the menu item.</param> /// <param name="flags">Additional option flags or 0.</param> /// <returns> /// If the given identifier exists and is shown, returns /// true; else returns false. /// </returns> /// <seealso cref="android.view.MenuClass.FLAG_PERFORM_NO_CLOSE">android.view.MenuClass.FLAG_PERFORM_NO_CLOSE /// </seealso> bool performIdentifierAction(int id, int flags); /// <summary> /// Control whether the menu should be running in qwerty mode (alphabetic /// shortcuts) or 12-key mode (numeric shortcuts). /// </summary> /// <remarks> /// Control whether the menu should be running in qwerty mode (alphabetic /// shortcuts) or 12-key mode (numeric shortcuts). /// </remarks> /// <param name="isQwerty"> /// If true the menu will use alphabetic shortcuts; else it /// will use numeric shortcuts. /// </param> void setQwertyMode(bool isQwerty); } /// <summary>Interface for managing the items in a menu.</summary> /// <remarks> /// Interface for managing the items in a menu. /// <p> /// By default, every Activity supports an options menu of actions or options. /// You can add items to this menu and handle clicks on your additions. The /// easiest way of adding menu items is inflating an XML file into the /// <see cref="Menu">Menu</see> /// via /// <see cref="MenuInflater">MenuInflater</see> /// . The easiest way of attaching code to /// clicks is via /// <see cref="android.app.Activity.onOptionsItemSelected(MenuItem)">android.app.Activity.onOptionsItemSelected(MenuItem) /// </see> /// and /// <see cref="android.app.Activity.onContextItemSelected(MenuItem)">android.app.Activity.onContextItemSelected(MenuItem) /// </see> /// . /// <p> /// Different menu types support different features: /// <ol> /// <li><b>Context menus</b>: Do not support item shortcuts and item icons. /// <li><b>Options menus</b>: The <b>icon menus</b> do not support item check /// marks and only show the item's /// <see cref="MenuItem.setTitleCondensed(java.lang.CharSequence)">condensed title</see> /// . The /// <b>expanded menus</b> (only available if six or more menu items are visible, /// reached via the 'More' item in the icon menu) do not show item icons, and /// item check marks are discouraged. /// <li><b>Sub menus</b>: Do not support item icons, or nested sub menus. /// </ol> /// <div class="special reference"> /// <h3>Developer Guides</h3> /// <p>For more information about creating menus, read the /// &lt;a href=" /// <docRoot></docRoot> /// guide/topics/ui/menus.html"&gt;Menus</a> developer guide.</p> /// </div> /// </remarks> [Sharpen.Sharpened] public static class MenuClass { /// <summary>This is the part of an order integer that the user can provide.</summary> /// <remarks>This is the part of an order integer that the user can provide.</remarks> /// <hide></hide> public const int USER_MASK = unchecked((int)(0x0000ffff)); /// <summary>Bit shift of the user portion of the order integer.</summary> /// <remarks>Bit shift of the user portion of the order integer.</remarks> /// <hide></hide> public const int USER_SHIFT = 0; /// <summary> /// This is the part of an order integer that supplies the category of the /// item. /// </summary> /// <remarks> /// This is the part of an order integer that supplies the category of the /// item. /// </remarks> /// <hide></hide> public const int CATEGORY_MASK = unchecked((int)(0xffff0000)); /// <summary>Bit shift of the category portion of the order integer.</summary> /// <remarks>Bit shift of the category portion of the order integer.</remarks> /// <hide></hide> public const int CATEGORY_SHIFT = 16; /// <summary> /// Value to use for group and item identifier integers when you don't care /// about them. /// </summary> /// <remarks> /// Value to use for group and item identifier integers when you don't care /// about them. /// </remarks> public const int NONE = 0; /// <summary>First value for group and item identifier integers.</summary> /// <remarks>First value for group and item identifier integers.</remarks> public const int FIRST = 1; /// <summary> /// Category code for the order integer for items/groups that are part of a /// container -- or/add this with your base value. /// </summary> /// <remarks> /// Category code for the order integer for items/groups that are part of a /// container -- or/add this with your base value. /// </remarks> public const int CATEGORY_CONTAINER = unchecked((int)(0x00010000)); /// <summary> /// Category code for the order integer for items/groups that are provided by /// the system -- or/add this with your base value. /// </summary> /// <remarks> /// Category code for the order integer for items/groups that are provided by /// the system -- or/add this with your base value. /// </remarks> public const int CATEGORY_SYSTEM = unchecked((int)(0x00020000)); /// <summary> /// Category code for the order integer for items/groups that are /// user-supplied secondary (infrequently used) options -- or/add this with /// your base value. /// </summary> /// <remarks> /// Category code for the order integer for items/groups that are /// user-supplied secondary (infrequently used) options -- or/add this with /// your base value. /// </remarks> public const int CATEGORY_SECONDARY = unchecked((int)(0x00030000)); /// <summary> /// Category code for the order integer for items/groups that are /// alternative actions on the data that is currently displayed -- or/add /// this with your base value. /// </summary> /// <remarks> /// Category code for the order integer for items/groups that are /// alternative actions on the data that is currently displayed -- or/add /// this with your base value. /// </remarks> public const int CATEGORY_ALTERNATIVE = unchecked((int)(0x00040000)); /// <summary> /// Flag for /// <see cref="addIntentOptions(int, int, int, android.content.ComponentName, android.content.Intent[], android.content.Intent, int, MenuItem[]) /// ">addIntentOptions(int, int, int, android.content.ComponentName, android.content.Intent[], android.content.Intent, int, MenuItem[]) /// </see> /// : if set, do not automatically remove /// any existing menu items in the same group. /// </summary> public const int FLAG_APPEND_TO_GROUP = unchecked((int)(0x0001)); /// <summary> /// Flag for /// <see cref="performShortcut(int, KeyEvent, int)">performShortcut(int, KeyEvent, int) /// </see> /// : if set, do not close the menu after /// executing the shortcut. /// </summary> public const int FLAG_PERFORM_NO_CLOSE = unchecked((int)(0x0001)); /// <summary> /// Flag for /// <see cref="performShortcut(int, KeyEvent, int)">performShortcut(int, KeyEvent, int) /// </see> /// : if set, always /// close the menu after executing the shortcut. Closing the menu also resets /// the prepared state. /// </summary> public const int FLAG_ALWAYS_PERFORM_CLOSE = unchecked((int)(0x0002)); } }
41.9125
167
0.674508
[ "Apache-2.0" ]
Conceptengineai/XobotOS
android/generated/android/view/Menu.cs
26,824
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("Logger")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("apexys")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
42.695652
82
0.739308
[ "BSD-2-Clause" ]
apexys/RadioController
Logger/Properties/AssemblyInfo.cs
982
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mediapackage-vod-2018-11-07.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.MediaPackageVod { /// <summary> /// Configuration for accessing Amazon MediaPackageVod service /// </summary> public partial class AmazonMediaPackageVodConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.103.25"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonMediaPackageVodConfig() { this.AuthenticationServiceName = "mediapackage-vod"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "mediapackage-vod"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2018-11-07"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.775
114
0.595705
[ "Apache-2.0" ]
UpendoVentures/aws-sdk-net
sdk/src/Services/MediaPackageVod/Generated/AmazonMediaPackageVodConfig.cs
2,142
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; using TownPatroller.SocketServer; using TPPacket.Packet; using TPPacket.Class; namespace TownPatroller.Client { class ConsoleClient : BaseClient { public ConsoleMode consoleMode { get; private set; } public ulong TargetBot { get; private set; } private Dictionary<ulong, BaseClient> Clients; public bool ReceivedCamFrame; public bool ReceivedCarStatus; public ConsoleClient(ulong _Id, SocketClient socketClient, Dictionary<ulong, BaseClient> clients) : base(_Id, socketClient, false) { Clients = clients; TargetBot = 0; } public override void Dispose() { if (Clients.ContainsKey(TargetBot)) ((HardwareClient)Clients[TargetBot]).RemoveViwer(this); TargetBot = 0; } public override void ManualReceiveData(BasePacket basePacket) { switch (basePacket.packetType) { case PacketType.CamConfig: CamConfigPacket ccp = (CamConfigPacket)basePacket; switch (ccp.camaraConfigType) { case CamaraConfigType.ChangeCamara: if (Clients.ContainsKey(TargetBot)) Clients[TargetBot].SendPacket(basePacket); break; case CamaraConfigType.SendFrame: break; default: break; } break; case PacketType.CamReceived: ReceivedCamFrame = true; break; case PacketType.CamResolutionReq: if (Clients.ContainsKey(TargetBot) == true) { Clients[TargetBot].SendPacket(basePacket); } break; case PacketType.CarStatusReceived: ReceivedCarStatus = true; break; case PacketType.CarStatusChangeReq: CarStatusChangeReqPacket cscr = (CarStatusChangeReqPacket)basePacket; if (Clients.ContainsKey(TargetBot) == true) { ((HardwareClient)Clients[TargetBot]).SetCardevice(cscr.ReqCarDevice); } break; case PacketType.CarGPSSpotStatusChangeReq: if (Clients.ContainsKey(TargetBot) == true) { Clients[TargetBot].SendPacket(basePacket); } break; case PacketType.UpdateDataReq: if (Clients.ContainsKey(TargetBot) == true) { Clients[TargetBot].SendPacket(basePacket); } break; case PacketType.UpdateConsoleModeReq: ConsoleUpdatePacket cup = (ConsoleUpdatePacket)basePacket; switch (cup.consoleMode) { case ConsoleMode.ViewBotList: if (Clients.ContainsKey(TargetBot) == true) { ((HardwareClient)Clients[TargetBot]).RemoveViwer(this); SendPacket(new ConsoleUpdatedPacket(ConsoleMode.ViewBotList)); TargetBot = 0; } break; case ConsoleMode.ViewSingleBot: if (Clients.ContainsKey(cup.TargetBot)) { ReceivedCamFrame = true; ReceivedCarStatus = true; ((HardwareClient)Clients[cup.TargetBot]).AddViwer(this); TargetBot = cup.TargetBot; SendPacket(new ConsoleUpdatedPacket(ConsoleMode.ViewSingleBot)); SendPacket(new DataUpdatedPacket(((HardwareClient)Clients[cup.TargetBot]).modeType)); SendPacket(new CarGPSSpotStatusPacket(GPSSpotManagerChangeType.OverWrite, ((HardwareClient)Clients[cup.TargetBot]).spotManager)); SendPacket(new CamResolutionPacket(((HardwareClient)Clients[cup.TargetBot]).CamQuality)); } else { SendPacket(new ConsoleUpdatedPacket(ConsoleMode.ViewBotList)); } break; default: break; } break; case PacketType.UniversalCommand: break; case PacketType.ClientsInfoReq: List<ClientInfo> clientInfos = new List<ClientInfo>(); foreach (var item in Clients) { if(item.Value.IsBot == true) { clientInfos.Add(new ClientInfo(item.Value.Id, ((HardwareClient)(item.Value)).gPSPosition)); } } SendPacket(new ClientinfoPacket(clientInfos.ToArray())); break; default: break; } } } }
39.190476
161
0.46971
[ "MIT" ]
noname0310/TownPatroller-Server
TownPatroller/Assets/Scripts/Client/ConsoleClient.cs
5,763
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.APIGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.APIGateway.Model.Internal.MarshallTransformations { /// <summary> /// CreateStage Request Marshaller /// </summary> public class CreateStageRequestMarshaller : IMarshaller<IRequest, CreateStageRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateStageRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateStageRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.APIGateway"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-07-09"; request.HttpMethod = "POST"; string uriResourcePath = "/restapis/{restapi_id}/stages"; if (!publicRequest.IsSetRestApiId()) throw new AmazonAPIGatewayException("Request object does not have required field RestApiId set"); uriResourcePath = uriResourcePath.Replace("{restapi_id}", StringUtils.FromStringWithSlashEncoding(publicRequest.RestApiId)); request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetCacheClusterEnabled()) { context.Writer.WritePropertyName("cacheClusterEnabled"); context.Writer.Write(publicRequest.CacheClusterEnabled); } if(publicRequest.IsSetCacheClusterSize()) { context.Writer.WritePropertyName("cacheClusterSize"); context.Writer.Write(publicRequest.CacheClusterSize); } if(publicRequest.IsSetCanarySettings()) { context.Writer.WritePropertyName("canarySettings"); context.Writer.WriteObjectStart(); var marshaller = CanarySettingsMarshaller.Instance; marshaller.Marshall(publicRequest.CanarySettings, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetDeploymentId()) { context.Writer.WritePropertyName("deploymentId"); context.Writer.Write(publicRequest.DeploymentId); } if(publicRequest.IsSetDescription()) { context.Writer.WritePropertyName("description"); context.Writer.Write(publicRequest.Description); } if(publicRequest.IsSetDocumentationVersion()) { context.Writer.WritePropertyName("documentationVersion"); context.Writer.Write(publicRequest.DocumentationVersion); } if(publicRequest.IsSetStageName()) { context.Writer.WritePropertyName("stageName"); context.Writer.Write(publicRequest.StageName); } if(publicRequest.IsSetTags()) { context.Writer.WritePropertyName("tags"); context.Writer.WriteObjectStart(); foreach (var publicRequestTagsKvp in publicRequest.Tags) { context.Writer.WritePropertyName(publicRequestTagsKvp.Key); var publicRequestTagsValue = publicRequestTagsKvp.Value; context.Writer.Write(publicRequestTagsValue); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetTracingEnabled()) { context.Writer.WritePropertyName("tracingEnabled"); context.Writer.Write(publicRequest.TracingEnabled); } if(publicRequest.IsSetVariables()) { context.Writer.WritePropertyName("variables"); context.Writer.WriteObjectStart(); foreach (var publicRequestVariablesKvp in publicRequest.Variables) { context.Writer.WritePropertyName(publicRequestVariablesKvp.Key); var publicRequestVariablesValue = publicRequestVariablesKvp.Value; context.Writer.Write(publicRequestVariablesValue); } context.Writer.WriteObjectEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateStageRequestMarshaller _instance = new CreateStageRequestMarshaller(); internal static CreateStageRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateStageRequestMarshaller Instance { get { return _instance; } } } }
38.762431
137
0.586659
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/CreateStageRequestMarshaller.cs
7,016
C#
using System; using Microsoft.ML; using Microsoft.ML.Data; using Microsoft.ML.Transforms; namespace Samples.Dynamic.Transforms.Categorical { public static class OneHotHashEncoding { public static void Example() { // Create a new ML context for ML.NET operations. It can be used for // exception tracking and logging as well as the source of randomness. var mlContext = new MLContext(); // Create a small dataset as an IEnumerable. var samples = new[] { new DataPoint {Education = "0-5yrs"}, new DataPoint {Education = "0-5yrs"}, new DataPoint {Education = "6-11yrs"}, new DataPoint {Education = "6-11yrs"}, new DataPoint {Education = "11-15yrs"} }; // Convert training data to an IDataView. IDataView data = mlContext.Data.LoadFromEnumerable(samples); // A pipeline for one hot hash encoding the 'Education' column. var pipeline = mlContext.Transforms.Categorical.OneHotHashEncoding( "EducationOneHotHashEncoded", "Education", numberOfBits: 3); // Fit and transform the data. IDataView hashEncodedData = pipeline.Fit(data).Transform(data); PrintDataColumn(hashEncodedData, "EducationOneHotHashEncoded"); // We have 8 slots, because we used numberOfBits = 3. // 0 0 0 1 0 0 0 0 // 0 0 0 1 0 0 0 0 // 0 0 0 0 1 0 0 0 // 0 0 0 0 1 0 0 0 // 0 0 0 0 0 0 0 1 // A pipeline for one hot hash encoding the 'Education' column // (using keying strategy). var keyPipeline = mlContext.Transforms.Categorical.OneHotHashEncoding( "EducationOneHotHashEncoded", "Education", OneHotEncodingEstimator.OutputKind.Key, 3); // Fit and transform the data. IDataView hashKeyEncodedData = keyPipeline.Fit(data).Transform(data); // Get the data of the newly created column for inspecting. var keyEncodedColumn = hashKeyEncodedData.GetColumn<uint>("EducationOneHotHashEncoded"); Console.WriteLine( "One Hot Hash Encoding of single column 'Education', with key " + "type output."); // One Hot Hash Encoding of single column 'Education', with key type output. foreach (uint element in keyEncodedColumn) Console.WriteLine(element); // 4 // 4 // 5 // 5 // 8 } private static void PrintDataColumn(IDataView transformedData, string columnName) { var countSelectColumn = transformedData.GetColumn<float[]>( transformedData.Schema[columnName]); foreach (var row in countSelectColumn) { for (var i = 0; i < row.Length; i++) Console.Write($"{row[i]}\t"); Console.WriteLine(); } } private class DataPoint { public string Education { get; set; } } } }
34.755319
88
0.555862
[ "MIT" ]
GitHubPang/machinelearning
docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/Categorical/OneHotHashEncoding.cs
3,269
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; using Twitter.Models; namespace Twitter.App.Models.ViewModels { public class UserViewModel { [JsonProperty("user_id")] public string UserId { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("class")] public string Class { get; set; } [JsonProperty("real_name")] public string RealName { get; set; } [JsonProperty("phone_number")] public string PhoneNumber { get; set; } [JsonProperty("has_avatar_image")] public bool HasAvatarImage { get; set; } [JsonProperty("avatar_image_name")] public string AvatarImageName { get; set; } [JsonProperty("registered_time")] public DateTime RegisteredTime { get; set; } [JsonProperty("joined_groups")] public IEnumerable<GroupVieModels> JoinedGroups { get; set; } [JsonProperty("created_groups")] public IEnumerable<GroupVieModels> CreatedGroups { get; set; } [JsonProperty("posted_tweets")] public IEnumerable<TweetViewModel> PostedTweets { get; set; } [JsonProperty("joined_activities")] public IEnumerable<ActivityViewModel> JoinedActivities { get; set; } [JsonProperty("created_activities")] public IEnumerable<ActivityViewModel> CreatedActivities { get; set; } [JsonProperty("posted_photos")] public IEnumerable<PhotoViewModel> PostedPhotos { get; set; } } }
29.961538
77
0.649551
[ "Apache-2.0" ]
ZJGSU-Open-Source/QQmgs
QQmgs.App/Models/ViewModels/UserViewModel.cs
1,560
C#
// ----------------------------------------------------------------------- // <copyright file="DocumentTask.cs" company="Nodine Legal, LLC"> // Licensed to Nodine Legal, LLC under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Nodine Legal, LLC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // </copyright> // ----------------------------------------------------------------------- namespace OpenLawOffice.Data.DBOs.Documents { using System; using AutoMapper; /// <summary> /// TODO: Update summary. /// </summary> [Common.Models.MapMe] public class DocumentTask : Core { [ColumnMapping(Name = "id")] public Guid Id { get; set; } [ColumnMapping(Name = "document_id")] public Guid DocumentId { get; set; } [ColumnMapping(Name = "task_id")] public long TaskId { get; set; } public void BuildMappings() { Dapper.SqlMapper.SetTypeMap(typeof(DocumentTask), new ColumnAttributeTypeMapper<DocumentTask>()); Mapper.CreateMap<DBOs.Documents.DocumentTask, Common.Models.Documents.DocumentTask>() .ForMember(dst => dst.IsStub, opt => opt.UseValue(false)) .ForMember(dst => dst.Created, opt => opt.ResolveUsing(db => { return db.UtcCreated.ToSystemTime(); })) .ForMember(dst => dst.Modified, opt => opt.ResolveUsing(db => { return db.UtcModified.ToSystemTime(); })) .ForMember(dst => dst.Disabled, opt => opt.ResolveUsing(db => { return db.UtcDisabled.ToSystemTime(); })) .ForMember(dst => dst.CreatedBy, opt => opt.ResolveUsing(db => { return new Common.Models.Account.Users() { PId = db.CreatedByUserPId, IsStub = true }; })) .ForMember(dst => dst.ModifiedBy, opt => opt.ResolveUsing(db => { return new Common.Models.Account.Users() { PId = db.ModifiedByUserPId, IsStub = true }; })) .ForMember(dst => dst.DisabledBy, opt => opt.ResolveUsing(db => { if (!db.DisabledByUserPId.HasValue) return null; return new Common.Models.Account.Users() { PId = db.DisabledByUserPId.Value, IsStub = true }; })) .ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(dst => dst.Document, opt => opt.ResolveUsing(db => { return new Common.Models.Documents.Document() { Id = db.DocumentId, IsStub = true }; })) .ForMember(dst => dst.Task, opt => opt.ResolveUsing(db => { return new Common.Models.Tasks.Task() { Id = db.TaskId, IsStub = true }; })); Mapper.CreateMap<Common.Models.Documents.DocumentTask, DBOs.Documents.DocumentTask>() .ForMember(dst => dst.UtcCreated, opt => opt.ResolveUsing(db => { return db.Created.ToDbTime(); })) .ForMember(dst => dst.UtcModified, opt => opt.ResolveUsing(db => { return db.Modified.ToDbTime(); })) .ForMember(dst => dst.UtcDisabled, opt => opt.ResolveUsing(db => { return db.Disabled.ToDbTime(); })) .ForMember(dst => dst.CreatedByUserPId, opt => opt.ResolveUsing(model => { if (model.CreatedBy == null || !model.CreatedBy.PId.HasValue) return Guid.Empty; return model.CreatedBy.PId.Value; })) .ForMember(dst => dst.ModifiedByUserPId, opt => opt.ResolveUsing(model => { if (model.ModifiedBy == null || !model.ModifiedBy.PId.HasValue) return Guid.Empty; return model.ModifiedBy.PId.Value; })) .ForMember(dst => dst.DisabledByUserPId, opt => opt.ResolveUsing(model => { if (model.DisabledBy == null) return null; return model.DisabledBy.PId; })) .ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Id)) .ForMember(dst => dst.DocumentId, opt => opt.ResolveUsing(db => { return db.Document.Id.Value; })) .ForMember(dst => dst.TaskId, opt => opt.ResolveUsing(db => { return db.Task.Id.Value; })); } } }
41.440559
109
0.476038
[ "Apache-2.0" ]
NodineLegal/OpenLawOffice
OpenLawOffice.Data/DBOs/Documents/DocumentTask.cs
5,928
C#
// (c) www.click2wait.net using System; using System.Text; using System.Collections.Generic; using System.Linq; using UnityEngine; using click2wait; namespace click2wait { [CreateAssetMenu(fileName = "New Buff", menuName = "Templates/New Buff", order = 999)] public partial class BuffTemplate : BaseTemplate { [Header("Costs")] public LevelCurrencyCost[] buyCost; public LevelCurrencyCost[] sellCost; [Header("Folder Name")] public string _folderName; public static string folderName = ""; private static Dictionary<int, BuffTemplate> _cache; public static Dictionary<int, BuffTemplate> dict { get { if (_cache == null) { BuffTemplate[] templates = Resources.LoadAll<BuffTemplate>(BuffTemplate.folderName); List<string> duplicates = templates.ToList().FindDuplicates(t => t.name); if (duplicates.Count == 0) { _cache = templates.ToDictionary(t => t.name.GetDeterministicHashCode(), t => t); } else { foreach (string duplicate in duplicates) Debug.LogError("[Warning] Resources folder contains multiple templates with the name " + duplicate); } } return _cache; } } public override void OnValidate() { base.OnValidate(); folderName = _folderName; } } }
22.04918
107
0.651301
[ "MIT" ]
Ghetaldus/click2wait-browser-game-style-engine
Scripts/Templates/BuffTemplate.cs
1,347
C#
 namespace System { partial class managemarks { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.id}); this.dataGridView1.Location = new System.Drawing.Point(-1, 96); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowHeadersWidth = 51; this.dataGridView1.RowTemplate.Height = 24; this.dataGridView1.Size = new System.Drawing.Size(992, 464); this.dataGridView1.TabIndex = 6; this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick); // // id // this.id.DataPropertyName = "id"; this.id.HeaderText = "id"; this.id.MinimumWidth = 6; this.id.Name = "id"; this.id.Width = 125; // // textBox1 // this.textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox1.Location = new System.Drawing.Point(136, 48); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(623, 30); this.textBox1.TabIndex = 5; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(150, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(255, 25); this.label1.TabIndex = 4; this.label1.Text = "Enter Name Of The student"; // // managemarks // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = global::System.Properties.Resources.wp2581371_plain_background; this.ClientSize = new System.Drawing.Size(991, 560); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.Name = "managemarks"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "managemarks"; this.Load += new System.EventHandler(this.managemarks_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Windows.Forms.DataGridView dataGridView1; private Windows.Forms.DataGridViewTextBoxColumn id; private Windows.Forms.TextBox textBox1; private Windows.Forms.Label label1; } }
45.299065
169
0.587993
[ "MIT" ]
Rohan12e/student-mgmt-system
System/managemarks.Designer.cs
4,849
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System.Collections.Generic; using Hyak.Common; namespace Microsoft.Azure.Internal.Subscriptions.Models { /// <summary> /// Location list operation response. /// </summary> public partial class LocationListResult : AzureOperationResponse { private IList<Location> _locations; /// <summary> /// Optional. Gets the locations. /// </summary> public IList<Location> Locations { get { return this._locations; } set { this._locations = value; } } /// <summary> /// Initializes a new instance of the LocationListResult class. /// </summary> public LocationListResult() { this.Locations = new LazyList<Location>(); } } }
31.538462
77
0.631098
[ "MIT" ]
DalavanCloud/azure-powershell
src/ResourceManager/Common/Commands.ResourceManager.Common/Generated/Models/LocationListResult.cs
1,589
C#
using System; using System.IO; using System.Windows.Forms; using System.Xml.Serialization; namespace DesctopMemo { /// <summary> /// 設定値 /// </summary> public struct MySetting { /// <summary> /// アプリケーションのコンフィグ /// </summary> public MyCONFIG CONFIG; /// <summary> /// 注意書きの文字列 /// </summary> public string NOTE; /// <summary> /// <see cref="MySetting"/>の初期化処理 /// </summary> public void Init() { CONFIG.Init(); NOTE = ""; } /// <summary> /// アプリケーションのコンフィグ /// </summary> public struct MyCONFIG { /// <summary> /// 表示用のフォントを指定するための情報 /// </summary> public MyFONT FONT; /// <summary> /// <see cref="MyFONT"/>の初期化処理 /// </summary> public void Init() { FONT.Init(); } } /// <summary> /// フォントを指定するための情報 /// </summary> public struct MyFONT { /// <summary> /// 名前 /// </summary> public string name; /// <summary> /// サイズ /// </summary> public int size; /// <summary> /// <see cref="MyFONT"/>の初期化処理 /// </summary> public void Init() { name = "MS ゴシック"; size = 9; } } } /// <summary> /// 設定値管理機能 /// 設定値はxmlファイルの形式で扱う /// </summary> public static partial class CAppSetting { /// <summary> /// 設定値のファイルパス(デフォルトは実行ファイルのあるフォルダ内のAppSetting.xml) /// </summary> private static readonly string FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DesctopMemo.xml"); /// <summary> /// アクセスを排他するためのロックオブジェクト /// </summary> private static readonly object SettingLock = new object(); /// <summary> /// 設定値 /// </summary> public static MySetting Setting; /// <summary> /// <see cref="FilePath"/>で指定されたファイルから設定値をロードする処理 /// </summary> /// <returns>処理の実行結果</returns> public static bool Load() { bool result = false; lock (SettingLock) { if (File.Exists(FilePath)) { try { XmlSerializer se = new XmlSerializer(typeof(MySetting)); using (StreamReader sr = new StreamReader(FilePath, new System.Text.UTF8Encoding(false))) { Setting = (MySetting)se.Deserialize(sr); sr.Close(); result = true; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } if (!result) { Setting.Init(); } } return result; } /// <summary> /// <see cref="FilePath"/>で指定されたファイルへ設定値をセーブする処理 /// </summary> /// <returns>処理の実行結果</returns> public static bool Save() { lock (SettingLock) { try { XmlSerializer se = new XmlSerializer(typeof(MySetting)); using (StreamWriter sw = new StreamWriter(FilePath, false, new System.Text.UTF8Encoding(false))) { //名前空間のプレフィックスを出力しなようにする XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add(String.Empty, String.Empty); se.Serialize(sw, Setting, ns); sw.Close(); return true; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } return false; } /// <summary> /// XMLファイルから読み取った文字列をテキスト表示できる文字列に変換する処理 /// </summary> /// <param name="buf">XMLで読み取った文字列</param> /// <returns>表示用の文字列</returns> public static string XmlStringToViewString(string buf) { //\rがないと改行表示されないことがあるため\n→\rn変換する //(XMLのシリアライズ化する際に\rが消えたりするので・・・) string tmp_buf = buf.Replace("\r\n", "\n"); return tmp_buf.Replace("\n", "\r\n"); } /// <summary> /// 垂直スクロールバーの幅を取得 /// </summary> /// <returns></returns> public static int GetVScrollBarWidth() { VScrollBar vscroll = new System.Windows.Forms.VScrollBar(); return vscroll.Width; } /// <summary> /// 水平スクロールバーのサイズ高さを取得 /// </summary> /// <returns></returns> public static int GetHScrollBarHight() { HScrollBar hscroll = new System.Windows.Forms.HScrollBar(); return hscroll.Height; } } }
28.365079
131
0.431076
[ "MIT" ]
k-110/DesctopMemo
src/DesctopMemo/CAppSetting.cs
6,137
C#
using System; using static BulletSharp.UnsafeNativeMethods; namespace BulletSharp { public class SoftRigidCollisionAlgorithm : CollisionAlgorithm { public class CreateFunc : CollisionAlgorithmCreateFunc { internal CreateFunc(IntPtr native, BulletObject owner) : base(ConstructionInfo.Null) { InitializeSubObject(native, owner); } public CreateFunc() : base(ConstructionInfo.Null) { IntPtr native = btSoftRigidCollisionAlgorithm_CreateFunc_new(); InitializeUserOwned(native); } public override CollisionAlgorithm CreateCollisionAlgorithm(CollisionAlgorithmConstructionInfo __unnamed0, CollisionObjectWrapper body0Wrap, CollisionObjectWrapper body1Wrap) { return new SoftRigidCollisionAlgorithm(btCollisionAlgorithmCreateFunc_CreateCollisionAlgorithm( Native, __unnamed0.Native, body0Wrap.Native, body1Wrap.Native), __unnamed0.Dispatcher); } } internal SoftRigidCollisionAlgorithm(IntPtr native, BulletObject owner) { InitializeSubObject(native, owner); } public SoftRigidCollisionAlgorithm(PersistentManifold mf, CollisionAlgorithmConstructionInfo ci, CollisionObjectWrapper col0, CollisionObjectWrapper col1Wrap, bool isSwapped) { IntPtr native = btSoftRigidCollisionAlgorithm_new(mf.Native, ci.Native, col0.Native, col1Wrap.Native, isSwapped); InitializeUserOwned(native); } } }
30.711111
109
0.79233
[ "Apache-2.0" ]
xtom0369/BulletPhysicsForUnity
BulletSharpPInvoke/BulletSharp/SoftBody/SoftRigidCollisionAlgorithm.cs
1,382
C#
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Portal; using Esri.ArcGISRuntime.Security; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.UI.Popups; using Windows.UI.Xaml; using Esri.ArcGISRuntime; namespace ArcGISRuntime.UWP.Samples.SearchPortalMaps { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Search for webmap", category: "Map", description: "Find webmap portal items by using a search term.", instructions: "Enter search terms into the search bar. Once the search is complete, a list is populated with the resultant webmaps. Tap on a webmap to set it to the map view. Scrolling to the bottom of the webmap recycler view will get more results.", tags: new[] { "keyword", "query", "search", "webmap" })] public partial class SearchPortalMaps { // Variables for OAuth with default values ... // URL of the server to authenticate with (ArcGIS Online) private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest"; // Client ID for the app registered with the server (Portal Maps) private string _appClientId = "2Gh53JRzkPtOENQq"; // Redirect URL after a successful authorization (configured for the Portal Maps application) private string _oAuthRedirectUrl = "https://developers.arcgis.com"; // Constructor for sample class public SearchPortalMaps() { InitializeComponent(); // Show the OAuth settings in the page ClientIdTextBox.Text = _appClientId; RedirectUrlTextBox.Text = _oAuthRedirectUrl; // Display a default map DisplayDefaultMap(); } private void DisplayDefaultMap() { // Create a new Map instance Map myMap = new Map(BasemapStyle.ArcGISLightGray); // Provide Map to the MapView MyMapView.Map = myMap; } private async void SearchButton_Click(object sender, RoutedEventArgs e) { try { // Get web map portal items in the current user's folder or from a keyword search IEnumerable<PortalItem> mapItems; ArcGISPortal portal; // See if the user wants to search public web map items if (SearchPublicMaps.IsChecked == true) { // Connect to the portal (anonymously) portal = await ArcGISPortal.CreateAsync(); // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags string queryExpression = string.Format("tags:\"{0}\" access:public type: (\"web map\" NOT \"web mapping application\")", SearchText.Text); // Create a query parameters object with the expression and a limit of 10 results PortalQueryParameters queryParams = new PortalQueryParameters(queryExpression, 10); // Search the portal using the query parameters and await the results PortalQueryResultSet<PortalItem> findResult = await portal.FindItemsAsync(queryParams); // Get the items from the query results mapItems = findResult.Results; } else { // Call a sub that will force the user to log in to ArcGIS Online (if they haven't already) bool loggedIn = await EnsureLoggedInAsync(); if (!loggedIn) { return; } // Connect to the portal (will connect using the provided credentials) portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl)); // Get the user's content (items in the root folder and a collection of sub-folders) PortalUserContent myContent = await portal.User.GetContentAsync(); // Get the web map items in the root folder mapItems = from item in myContent.Items where item.Type == PortalItemType.WebMap select item; // Loop through all sub-folders and get web map items, add them to the mapItems collection foreach (PortalFolder folder in myContent.Folders) { IEnumerable<PortalItem> folderItems = await portal.User.GetContentAsync(folder.FolderId); mapItems = mapItems.Concat(from item in folderItems where item.Type == PortalItemType.WebMap select item); } } // Show the web map portal items in the list box MapListBox.ItemsSource = mapItems; } catch (Exception ex) { await new MessageDialog(ex.ToString(), "Error").ShowAsync(); } } private void LoadMapButtonClick(object sender, RoutedEventArgs e) { // Get the selected web map item in the list box PortalItem selectedMap = MapListBox.SelectedItem as PortalItem; if (selectedMap == null) { return; } // Create a new map, pass the web map portal item to the constructor Map webMap = new Map(selectedMap); // Handle change in the load status (to report load errors) webMap.LoadStatusChanged += WebMapLoadStatusChanged; // Show the web map in the map view MyMapView.Map = webMap; } private async void WebMapLoadStatusChanged(object sender, LoadStatusEventArgs e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { // Report errors if map failed to load if (e.Status == LoadStatus.FailedToLoad) { Map map = (Map) sender; Exception err = map.LoadError; if (err != null) { await new MessageDialog(err.Message, "Map load error").ShowAsync(); } } }); } private void RadioButtonUnchecked(object sender, RoutedEventArgs e) { // When the search/user radio buttons are unchecked, clear the list box MapListBox.ItemsSource = null; // Set the map to the default (if necessary) if (MyMapView.Map.Item != null) { DisplayDefaultMap(); } } private async Task<bool> EnsureLoggedInAsync() { bool loggedIn = false; try { // Create a challenge request for portal credentials (OAuth credential request for arcgis.com) CredentialRequestInfo challengeRequest = new CredentialRequestInfo { // Use the OAuth implicit grant flow GenerateTokenOptions = new GenerateTokenOptions { TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }, // Indicate the url (portal) to authenticate with (ArcGIS Online) ServiceUri = new Uri(ArcGISOnlineUrl) }; // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler Credential cred = await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false); loggedIn = cred != null; } catch (OperationCanceledException) { // TODO: handle login canceled } catch (Exception) { // TODO: handle login failure } return loggedIn; } private void SaveOAuthSettingsClicked(object sender, RoutedEventArgs e) { // Settings were provided, update the configuration settings for OAuth authorization _appClientId = ClientIdTextBox.Text.Trim(); _oAuthRedirectUrl = RedirectUrlTextBox.Text.Trim(); // Update authentication manager with the OAuth settings UpdateAuthenticationManager(); // Hide the OAuth input, show the search UI OAuthSettingsGrid.Visibility = Visibility.Collapsed; SearchUI.Visibility = Visibility.Visible; } private async void CancelOAuthSettingsClicked(object sender, RoutedEventArgs e) { // Warn that browsing user's ArcGIS Online maps won't be available without OAuth settings string warning = "Without OAuth settings, you will not be able to browse maps from your ArcGIS Online account."; await new MessageDialog(warning, "No OAuth settings").ShowAsync(); // Disable browsing maps from your ArcGIS Online account BrowseMyMaps.IsEnabled = false; // Hide the OAuth input, show the search UI OAuthSettingsGrid.Visibility = Visibility.Collapsed; SearchUI.Visibility = Visibility.Visible; } private void UpdateAuthenticationManager() { // Define the server information for ArcGIS Online ServerInfo portalServerInfo = new ServerInfo { // ArcGIS Online URI ServerUri = new Uri(ArcGISOnlineUrl), // Type of token authentication to use TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Define the OAuth information OAuthClientInfo oAuthInfo = new OAuthClientInfo { ClientId = _appClientId, RedirectUri = new Uri(_oAuthRedirectUrl) }; portalServerInfo.OAuthClientInfo = oAuthInfo; // Get a reference to the (singleton) AuthenticationManager for the app AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current; // Register the ArcGIS Online server information with the AuthenticationManager thisAuthenticationManager.RegisterServer(portalServerInfo); // Create a new ChallengeHandler that uses a method in this class to challenge for credentials thisAuthenticationManager.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync); } // ChallengeHandler function that will be called whenever access to a secured resource is attempted public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { Credential credential = null; try { // User will be challenged for OAuth credentials credential = await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri); } catch (Exception) { // Exception will be reported in calling function throw; } return credential; } } }
42.102473
259
0.597146
[ "Apache-2.0" ]
alphadude11/arcgis-runtime-samples-dotnet
src/UWP/ArcGISRuntime.UWP.Viewer/Samples/Map/SearchPortalMaps/SearchPortalMaps.xaml.cs
11,915
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 29.11.2020. using System; using System.Data; using System.Globalization; using System.Threading; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.DateTime.String{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1=System.DateTime; using T_DATA2=System.String; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields public static class TestSet_001__fields { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_TIMESTAMP"; private const string c_NameOf__COL_DATA2 ="COL2_VARCHAR_10"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2,TypeName="VARCHAR(10)")] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 c_value1=new System.DateTime(2020,11,29,15,57,46).AddMilliseconds(32); const T_DATA2 c_value2="--cucu"; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var oldC=Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture=new CultureInfo("ru-RU"); Assert.AreEqual ("29.11.2020 15:57:46--cucu", c_value1+c_value2); } finally { Thread.CurrentThread.CurrentCulture=oldC; }//finally var recs=db.testTable.Where(r => (r.COL_DATA1+r.COL_DATA2)=="2020-11-29 15:57:46.0320--cucu" && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T("||").N_TXT_NP("t",c_NameOf__COL_DATA2).T(") = _utf8 '2020-11-29 15:57:46.0320--cucu') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_C02__LeftToObjectToString() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 c_value1=new System.DateTime(2020,11,29,15,57,46).AddMilliseconds(32); const T_DATA2 c_value2="--cucu"; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => ((string)(object)r.COL_DATA1+r.COL_DATA2)=="2020-11-29 15:57:46.0320--cucu" && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T("||").N_TXT_NP("t",c_NameOf__COL_DATA2).T(") = _utf8 '2020-11-29 15:57:46.0320--cucu') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_C02__LeftToObjectToString //----------------------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.DateTime.String
28.741228
199
0.567374
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Add/Complete/DateTime/String/TestSet_001__fields.cs
6,555
C#
using AutoMapper; using Microsoft.AspNetCore.DataProtection; using System; using System.Collections.Generic; using System.Text; using VoipProjectEntities.Application.Features.Menu.Queries.GetMenu; using VoipProjectEntities.Domain.Entities; namespace VoipProjectEntities.Application.Profiles { public class MenuVmCustomMapper : ITypeConverter<MenuAccess, MenuListVm> { private readonly IDataProtector _protector; public MenuVmCustomMapper(IDataProtectionProvider provider) { _protector = provider.CreateProtector(""); } public MenuListVm Convert(MenuAccess source, MenuListVm destination, ResolutionContext context) { MenuListVm des = new MenuListVm() { MenuAccessId = _protector.Protect(source.MenuAccessId.ToString()), MenuLink = source.MenuLink, CreatedAt = source.CreatedAt, UpdatedAt = source.UpdatedAt, CustomerID = _protector.Protect(source.CustomerId.ToString()), IsAccess = source.IsAccess, }; return des; } } }
33.735294
103
0.66347
[ "Apache-2.0" ]
Anagha1009/VoIPCustomerWebPortal-1
src/Core/VoipProjectEntities.Application/Profiles/MenuVmCustomMapper.cs
1,149
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Common.Merged { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Datatype.Lang; using Ca.Infoway.Messagebuilder.Model; using System; using System.Collections.Generic; /** * <summary>Business Name: RecommendedDosage</summary> * * <remarks>COCT_MT260030CA.SubstanceAdministrationEventCriterion: * Recommended Dosage <p>Provides a reference for calculating * optimum dose of medication for patients.</p> <p>Identifies * the outer dosage boundaries that were exceeded and triggered * the issue. Included in this information are the * drug-specific recommended dosage ranges for various age * groups and weight classes.</p> * COCT_MT260010CA.SubstanceAdministrationEventCriterion: * Recommended Dosage <p>Provides a reference for calculating * optimum dose of medication for patients.</p> <p>Identifies * the outer dosage boundaries that were exceeded and triggered * the issue. Included in this information are the * drug-specific recommended dosage ranges for various age * groups and weight classes.</p></remarks> */ [Hl7PartTypeMappingAttribute(new string[] {"COCT_MT260010CA.SubstanceAdministrationEventCriterion","COCT_MT260020CA.SubstanceAdministrationEventCriterion","COCT_MT260030CA.SubstanceAdministrationEventCriterion"})] public class RecommendedDosage : MessagePartBean { private IVL<TS, Interval<PlatformDate>> effectiveTime; private URG<PQ, PhysicalQuantity> doseQuantity; private IList<Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Common.Merged.DosagePreconditions> componentObservationEventCriterion; public RecommendedDosage() { this.effectiveTime = new IVLImpl<TS, Interval<PlatformDate>>(); this.doseQuantity = new URGImpl<PQ, PhysicalQuantity>(); this.componentObservationEventCriterion = new List<Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Common.Merged.DosagePreconditions>(); } /** * <summary>Business Name: DoseDuration</summary> * * <remarks>Un-merged Business Name: DoseDuration Relationship: * COCT_MT260010CA.SubstanceAdministrationEventCriterion.effectiveTime * Conformance/Cardinality: REQUIRED (0-1) <p>Recommended * Duration (width)</p> <p>Allows calculation of amount under * or over.</p> <p>Indicates the recommended duration for drug * therapy that was exceeded or not met.</p> Un-merged Business * Name: DoseDuration Relationship: * COCT_MT260030CA.SubstanceAdministrationEventCriterion.effectiveTime * Conformance/Cardinality: REQUIRED (0-1) <p>Recommended * Duration (width)</p> <p>Allows calculation of amount under * or over.</p> <p>Indicates the recommended duration for drug * therapy that was exceeded or not met.</p> Un-merged Business * Name: DoseDuration Relationship: * COCT_MT260020CA.SubstanceAdministrationEventCriterion.effectiveTime * Conformance/Cardinality: REQUIRED (0-1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"effectiveTime"})] public Interval<PlatformDate> EffectiveTime { get { return this.effectiveTime.Value; } set { this.effectiveTime.Value = value; } } /** * <summary>Business Name: DosageRange</summary> * * <remarks>Un-merged Business Name: DosageRange Relationship: * COCT_MT260010CA.SubstanceAdministrationEventCriterion.doseQuantity * Conformance/Cardinality: REQUIRED (0-1) * <p>ContraIndication.recommendedRange</p> <p>Maximum Dosage * Level (high)</p> <p>Minimum Dosage Level (low)</p> <p>Allows * calculation of amount over/under.</p> <p>This is a * specification of the range of quantity of medication * (Min/Max figures) that is recommended for the drug to avoid * triggering of dosage issues.</p> Un-merged Business Name: * DosageRange Relationship: * COCT_MT260030CA.SubstanceAdministrationEventCriterion.doseQuantity * Conformance/Cardinality: REQUIRED (0-1) * <p>ContraIndication.recommendedRange</p> <p>Maximum Dosage * Level (high)</p> <p>Minimum Dosage Level (low)</p> <p>Allows * calculation of amount over/under.</p> <p>This is a * specification of the range of quantity of medication * (Min/Max figures) that is recommended for the drug to avoid * triggering of dosage issues.</p> Un-merged Business Name: * DosageRange Relationship: * COCT_MT260020CA.SubstanceAdministrationEventCriterion.doseQuantity * Conformance/Cardinality: REQUIRED (0-1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"doseQuantity"})] public UncertainRange<PhysicalQuantity> DoseQuantity { get { return this.doseQuantity.Value; } set { this.doseQuantity.Value = value; } } /** * <summary>Un-merged Business Name: (no business name * specified)</summary> * * <remarks>Relationship: * COCT_MT260010CA.Component2.observationEventCriterion * Conformance/Cardinality: REQUIRED (1) Un-merged Business * Name: (no business name specified) Relationship: * COCT_MT260030CA.Component2.observationEventCriterion * Conformance/Cardinality: REQUIRED (1) Un-merged Business * Name: (no business name specified) Relationship: * COCT_MT260020CA.Component2.observationEventCriterion * Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"component/observationEventCriterion"})] public IList<Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Common.Merged.DosagePreconditions> ComponentObservationEventCriterion { get { return this.componentObservationEventCriterion; } } } }
52.746377
218
0.676879
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03_imm/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_imm/Common/Merged/RecommendedDosage.cs
7,279
C#
namespace LeetCode.Naive.Problems; /// <summary> /// Problem: https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/ /// Submission: https://leetcode.com/submissions/detail/625918149/ /// </summary> internal class P2148 { public class Solution { public int CountElements(int[] nums) { var min = nums.Min(); var max = nums.Max(); return nums.Count(x => x > min && x < max); } } }
23.8
105
0.615546
[ "MIT" ]
viacheslave/algo
leetcode/c#/Problems/P2148.cs
476
C#
/* Copyright 2017 Coin Foundry (coinfoundry.org) Authors: Oliver Weichhold (oliver@weichhold.com) Olaf Wasilewski (olaf.wasilewski@gmx.de) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Miningcore.Blockchain.Bitcoin.DaemonResponses { public class MiningInfo { public int Blocks { get; set; } public int CurrentBlockSize { get; set; } public int CurrentBlockWeight { get; set; } public double Difficulty { get; set; } public double NetworkHashps { get; set; } public double NetmHashps { get; set; } public string Chain { get; set; } } }
46.114286
104
0.745973
[ "MIT" ]
tross2015/miningcore
src/Miningcore/Blockchain/Bitcoin/DaemonResponses/GetMiningInfoResponse.cs
1,614
C#
using EmissionsLibrary; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; namespace EmissionsWeb { public class MeasurementsController : ApiController { public IEnumerable<string> GetIds() { var currentData = (HashSet<TransferData>)HttpContext.Current.Application["Measurements"]; var ids = new List<string>(); currentData.ToList().ForEach(value => { ids.Add(value.valueUuid); }); return ids; } public TransferData Get(string id) { var currentData = (HashSet<TransferData>)HttpContext.Current.Application["Measurements"]; return currentData.ToList().Where(value => value.valueUuid == id).SingleOrDefault(); } } }
26.903226
101
0.61271
[ "MIT" ]
sbannikov/csharpbmstu
2019/Homework/Teams/02/emissions-web/EmissionsWeb/MeasurementsController.cs
836
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using BulgarianCreators.Web; using BulgarianCreators.Web.Controllers; namespace BulgarianCreators.Web.Tests.Controllers { [TestClass] public class HomeControllerTest { [TestMethod] public void Index() { // Arrange HomeController controller = new HomeController(); // Act ViewResult result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result); } [TestMethod] public void About() { // Arrange HomeController controller = new HomeController(); // Act ViewResult result = controller.About() as ViewResult; // Assert Assert.AreEqual("Your application description page.", result.ViewBag.Message); } [TestMethod] public void Contact() { // Arrange HomeController controller = new HomeController(); // Act ViewResult result = controller.Contact() as ViewResult; // Assert Assert.IsNotNull(result); } } }
23.854545
90
0.580793
[ "MIT" ]
bbojkov/ContentCreators
BulgarianCreators.Web.Tests/Controllers/HomeControllerTest.cs
1,314
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Tools.Ribbon; using KinectPowerPointControl; using PowerPoint2013Control; using ControlCommon; namespace KinectPowerPointAddIn { public partial class KinectRibbon { private void KinectRibbon_Load(object sender, RibbonUIEventArgs e) { } private void kinectBtn_Click(object sender, RibbonControlEventArgs e) { KinectHandler kinect = new KinectHandler(); if (kinectBtn.Checked) { kinect.Handler = new PowerPointHandler(); kinect.Handler.PlayPresentation = this.chkStartPresentation.Checked; kinect.Start(); } else { kinect.Stop(); } } } }
23.833333
84
0.609557
[ "Apache-2.0" ]
becker-portilla/KinectPowerPoint2013Addin
KinectPowerPointAddIn/KinectRibbon.cs
860
C#
/* Copyright 2011 MCForge Dual-licensed under the Educational Community License, Version 2.0 and the GNU General Public License, Version 3 (the "Licenses"); you may not use this file except in compliance with the Licenses. You may obtain a copy of the Licenses at http://www.opensource.org/licenses/ecl2.php http://www.gnu.org/licenses/gpl-3.0.html Unless required by applicable law or agreed to in writing, software distributed under the Licenses are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licenses for the specific language governing permissions and limitations under the Licenses. */ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Timers; using MCForge; using System.Threading; public static class Checktimer { static System.Timers.Timer t; public static void StartTimer() { t = new System.Timers.Timer(); t.AutoReset = false; t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed); t.Interval = GetInterval(); t.Start(); } static double GetInterval() { DateTime now = DateTime.Now; return ((60 - now.Second) * 1000 - now.Millisecond); } /// <summary> /// Put methods to make them execute every 60 seconds /// </summary> /// <param name="sender">For the timer</param> /// <param name="e">For the timer</param> static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { t.Interval = GetInterval(); t.Start(); // methods to be executed every 60 seconds!: TRExpiryCheck(); } public static void TRExpiryCheck() { foreach (Player p in Player.players) { foreach (string line3 in File.ReadAllLines("text/tempranks.txt")) { if (line3.Contains(p.name)) { string player = line3.Split(' ')[0]; int period = Convert.ToInt32(line3.Split(' ')[3]); int minutes = Convert.ToInt32(line3.Split(' ')[4]); int hours = Convert.ToInt32(line3.Split(' ')[5]); int days = Convert.ToInt32(line3.Split(' ')[6]); int months = Convert.ToInt32(line3.Split(' ')[7]); int years = Convert.ToInt32(line3.Split(' ')[8]); Player who = Player.Find(player); DateTime ExpireDate = new DateTime(years, months, days, hours, minutes, 0); DateTime tocheck = ExpireDate.AddHours(Convert.ToDouble(period)); DateTime tochecknow = DateTime.Now; double datecompare = DateTime.Compare(tocheck, tochecknow); if (datecompare <= 0) Command.all.Find("deltemprank").Use(null, who.name); } } } } }
35.621951
95
0.610065
[ "Apache-2.0" ]
OMGasm/MCForge-Vanilla
Checktimer.cs
2,923
C#
using FluentAssertions; using MockGen.Model; using System.Collections.Generic; using Xunit; namespace MockGen.Tests.Model { public class MethodTests { [Fact] public void AddMethod_Should_set_a_unique_name_for_methods_overload() { var mock = new Mock(); var method1 = new Method { Name = "DoSomething" }; var method2 = new Method { Name = "DoSomething" }; var method3 = new Method { Name = "DoSomething" }; mock.AddMethod(method1); method1.UniqueName.Should().Be("DoSomething"); mock.AddMethod(method2); method2.UniqueName.Should().Be("DoSomething1"); mock.AddMethod(method3); method3.UniqueName.Should().Be("DoSomething2"); } } }
28.931034
78
0.57211
[ "MIT" ]
thomas-girotto/MockGen
tests/MockGen.Tests/Model/MethodTests.cs
841
C#
using System; using System.Threading; namespace NsqSharp.Utils { /// <summary> /// A WaitGroup waits for a collection of routines to finish. The main routine calls Add to set the number of routines to /// wait for. Then each of the routines runs and calls Done when finished. At the same time, Wait can be used to block until /// all routines have finished. See: http://golang.org/pkg/sync/#WaitGroup /// </summary> public class WaitGroup { private readonly ManualResetEvent _wait = new ManualResetEvent(initialState: true); private readonly object _doneLocker = new object(); private int _count; private bool _done = true; /// <summary> /// Add adds delta, which may be negative, to the WaitGroup counter. If the counter becomes zero, all goroutines blocked /// on Wait are released. If the counter goes negative, Add panics. /// /// Note that calls with a positive delta that occur when the counter is zero must happen before a Wait. Calls with a /// negative delta, or calls with a positive delta that start when the counter is greater than zero, may happen at any /// time. Typically this means the calls to Add should execute before the statement creating the routine or other event /// to be waited for. /// </summary> /// <param name="delta"></param> public void Add(int delta) { lock (_doneLocker) { if (_done) { _done = false; _wait.Reset(); } } int num = Interlocked.Add(ref _count, delta); if (num <= 0) { lock (_doneLocker) { _done = true; _wait.Set(); } if (num < 0) throw new Exception("sync: negative WaitGroup counter"); } } /// <summary> /// Done decrements the WaitGroup counter. /// </summary> public void Done() { Add(-1); } /// <summary> /// Wait blocks until the WaitGroup counter is zero. /// </summary> public void Wait() { _wait.WaitOne(); } } }
33.28169
128
0.541261
[ "MIT" ]
Misiu/NsqSharp
NsqSharp/Utils/WaitGroup.cs
2,365
C#
using System; namespace Imagin.Common.Globalization { [Serializable] public enum Language { [Culture("en")] English, [Culture("es-ES")] Spanish, [Culture("fr-FR")] French, [Culture("it-IT")] Italian, [Culture("ja-JP")] Japanese } }
17.315789
37
0.495441
[ "BSD-2-Clause" ]
fritzmark/Imagin.NET
Imagin.Common/Global/Language.cs
331
C#
using System; using System.IO; using System.Text.Json; using EfficientDynamoDb.DocumentModel; using EfficientDynamoDb.Internal.Extensions; namespace Benchmarks.Mocks { public static class UpdateItemResponseFactory { public static byte[] CreateResponse(Document entity) { using var stream = new MemoryStream(); using var writer = new Utf8JsonWriter(stream); writer.WriteStartObject(); writer.WritePropertyName("Attributes"); writer.WriteAttributesDictionary(entity); writer.WriteEndObject(); writer.Flush(); stream.Position = 0; return stream.ToArray(); } } }
26.535714
60
0.606999
[ "MIT" ]
AllocZero/EfficientDynamoDb
src/Benchmarks/Mocks/UpdateItemResponseFactory.cs
743
C#
namespace Silphid.Loadzup { public enum QueuePriority { Normal, High } }
12.625
29
0.554455
[ "MIT", "BSD-3-Clause" ]
Silphid/Silphid.Unity
Sources/Loadzup/Abstractions/QueuePriority.cs
103
C#
namespace WpfTestApplication { public partial class GetMultiple { public GetMultiple() { InitializeComponent(); } } }
16.090909
37
0.519774
[ "Apache-2.0", "MIT" ]
DaveWeath/White
src/TestApplications/WpfTestApplication/Scenarios/GetMultiple.xaml.cs
169
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Cryptography; namespace GRGcms.API.Payment.alipaymb { /// <summary> /// 类名:RSAFromPkcs8 /// 功能:RSA解密、签名、验签 /// 详细:该类对Java生成的密钥进行解密和签名以及验签专用类,不需要修改 /// 版本:2.0 /// 修改日期:2011-05-10 /// 说明: /// 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。 /// 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。 /// </summary> public sealed class RSAFromPkcs8 { /// <summary> /// 签名 /// </summary> /// <param name="content">需要签名的内容</param> /// <param name="privateKey">私钥</param> /// <param name="input_charset">编码格式</param> /// <returns></returns> public static string sign(string content, string privateKey, string input_charset) { Encoding code = Encoding.GetEncoding(input_charset); byte[] Data = code.GetBytes(content); RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey); SHA1 sh = new SHA1CryptoServiceProvider(); byte[] signData = rsa.SignData(Data, sh); return Convert.ToBase64String(signData); } /// <summary> /// 验证签名 /// </summary> /// <param name="content">需要验证的内容</param> /// <param name="signedString">签名结果</param> /// <param name="publicKey">公钥</param> /// <param name="input_charset">编码格式</param> /// <returns></returns> public static bool verify(string content, string signedString, string publicKey, string input_charset) { bool result = false; Encoding code = Encoding.GetEncoding(input_charset); byte[] Data = code.GetBytes(content); byte[] data = Convert.FromBase64String(signedString); RSAParameters paraPub = ConvertFromPublicKey(publicKey); RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider(); rsaPub.ImportParameters(paraPub); SHA1 sh = new SHA1CryptoServiceProvider(); result = rsaPub.VerifyData(Data, sh, data); return result; } /// <summary> /// 用RSA解密 /// </summary> /// <param name="resData">待解密字符串</param> /// <param name="privateKey">私钥</param> /// <param name="input_charset">编码格式</param> /// <returns>解密结果</returns> public static string decryptData(string resData, string privateKey, string input_charset) { byte[] DataToDecrypt = Convert.FromBase64String(resData); List<byte> result = new List<byte>(); for (int j = 0; j < DataToDecrypt.Length / 128; j++) { byte[] buf = new byte[128]; for (int i = 0; i < 128; i++) { buf[i] = DataToDecrypt[i + 128 * j]; } result.AddRange(decrypt(buf, privateKey, input_charset)); } byte[] source = result.ToArray(); char[] asciiChars = new char[Encoding.GetEncoding(input_charset).GetCharCount(source, 0, source.Length)]; Encoding.GetEncoding(input_charset).GetChars(source, 0, source.Length, asciiChars, 0); return new string(asciiChars); } private static byte[] decrypt(byte[] data, string privateKey, string input_charset) { RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey); SHA1 sh = new SHA1CryptoServiceProvider(); return rsa.Decrypt(data, false); } /// <summary> /// 解析java生成的pem文件私钥 /// </summary> /// <param name="pemstr"></param> /// <returns></returns> private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr) { byte[] pkcs8privatekey; pkcs8privatekey = Convert.FromBase64String(pemstr); if (pkcs8privatekey != null) { RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey); return rsa; } else return null; } private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8) { byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; byte[] seq = new byte[15]; MemoryStream mem = new MemoryStream(pkcs8); int lenstream = (int)mem.Length; BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading byte bt = 0; ushort twobytes = 0; try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes else return null; bt = binr.ReadByte(); if (bt != 0x02) return null; twobytes = binr.ReadUInt16(); if (twobytes != 0x0001) return null; seq = binr.ReadBytes(15); //read the Sequence OID if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct return null; bt = binr.ReadByte(); if (bt != 0x04) //expect an Octet string return null; bt = binr.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count if (bt == 0x81) binr.ReadByte(); else if (bt == 0x82) binr.ReadUInt16(); //------ at this stage, the remaining sequence should be the RSA private key byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position)); RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey); return rsacsp; } catch (Exception) { return null; } finally { binr.Close(); } } private static bool CompareBytearrays(byte[] a, byte[] b) { if (a.Length != b.Length) return false; int i = 0; foreach (byte c in a) { if (c != b[i]) return false; i++; } return true; } private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading byte bt = 0; ushort twobytes = 0; int elems = 0; try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes else return null; twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) //version number return null; bt = binr.ReadByte(); if (bt != 0x00) return null; //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); MODULUS = binr.ReadBytes(elems); elems = GetIntegerSize(binr); E = binr.ReadBytes(elems); elems = GetIntegerSize(binr); D = binr.ReadBytes(elems); elems = GetIntegerSize(binr); P = binr.ReadBytes(elems); elems = GetIntegerSize(binr); Q = binr.ReadBytes(elems); elems = GetIntegerSize(binr); DP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); DQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); IQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); RSAparams.Modulus = MODULUS; RSAparams.Exponent = E; RSAparams.D = D; RSAparams.P = P; RSAparams.Q = Q; RSAparams.DP = DP; RSAparams.DQ = DQ; RSAparams.InverseQ = IQ; RSA.ImportParameters(RSAparams); return RSA; } catch (Exception) { return null; } finally { binr.Close(); } } private static int GetIntegerSize(BinaryReader binr) { byte bt = 0; byte lowbyte = 0x00; byte highbyte = 0x00; int count = 0; bt = binr.ReadByte(); if (bt != 0x02) //expect integer return 0; bt = binr.ReadByte(); if (bt == 0x81) count = binr.ReadByte(); // data size in next byte else if (bt == 0x82) { highbyte = binr.ReadByte(); // data size in next 2 bytes lowbyte = binr.ReadByte(); byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; count = BitConverter.ToInt32(modint, 0); } else { count = bt; // we already have the data size } while (binr.ReadByte() == 0x00) { //remove high order zeros in data count -= 1; } binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte return count; } #region 解析.net 生成的Pem private static RSAParameters ConvertFromPublicKey(string pemFileConent) { byte[] keyData = Convert.FromBase64String(pemFileConent); if (keyData.Length < 162) { throw new ArgumentException("pem file content is incorrect."); } byte[] pemModulus = new byte[128]; byte[] pemPublicExponent = new byte[3]; Array.Copy(keyData, 29, pemModulus, 0, 128); Array.Copy(keyData, 159, pemPublicExponent, 0, 3); RSAParameters para = new RSAParameters(); para.Modulus = pemModulus; para.Exponent = pemPublicExponent; return para; } private static RSAParameters ConvertFromPrivateKey(string pemFileConent) { byte[] keyData = Convert.FromBase64String(pemFileConent); if (keyData.Length < 609) { throw new ArgumentException("pem file content is incorrect."); } int index = 11; byte[] pemModulus = new byte[128]; Array.Copy(keyData, index, pemModulus, 0, 128); index += 128; index += 2;//141 byte[] pemPublicExponent = new byte[3]; Array.Copy(keyData, index, pemPublicExponent, 0, 3); index += 3; index += 4;//148 byte[] pemPrivateExponent = new byte[128]; Array.Copy(keyData, index, pemPrivateExponent, 0, 128); index += 128; index += ((int)keyData[index + 1] == 64 ? 2 : 3);//279 byte[] pemPrime1 = new byte[64]; Array.Copy(keyData, index, pemPrime1, 0, 64); index += 64; index += ((int)keyData[index + 1] == 64 ? 2 : 3);//346 byte[] pemPrime2 = new byte[64]; Array.Copy(keyData, index, pemPrime2, 0, 64); index += 64; index += ((int)keyData[index + 1] == 64 ? 2 : 3);//412/413 byte[] pemExponent1 = new byte[64]; Array.Copy(keyData, index, pemExponent1, 0, 64); index += 64; index += ((int)keyData[index + 1] == 64 ? 2 : 3);//479/480 byte[] pemExponent2 = new byte[64]; Array.Copy(keyData, index, pemExponent2, 0, 64); index += 64; index += ((int)keyData[index + 1] == 64 ? 2 : 3);//545/546 byte[] pemCoefficient = new byte[64]; Array.Copy(keyData, index, pemCoefficient, 0, 64); RSAParameters para = new RSAParameters(); para.Modulus = pemModulus; para.Exponent = pemPublicExponent; para.D = pemPrivateExponent; para.P = pemPrime1; para.Q = pemPrime2; para.DP = pemExponent1; para.DQ = pemExponent2; para.InverseQ = pemCoefficient; return para; } #endregion } }
35.46875
121
0.50859
[ "MIT" ]
zengfanmao/mpds
LiveVideoSDK/VIMS.Cms/GRGcms.API/Payment/alipaymb/RSA.cs
14,038
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("c")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("c")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("60b11827-a360-4061-8ef9-e64a5ce31bc9")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.621622
57
0.739377
[ "MIT" ]
yu3mars/procon
atcoder/arc/arc082/c/Properties/AssemblyInfo.cs
1,628
C#
using OpenCvSharp.Tracking; using Xunit; namespace OpenCvSharp.Tests.Tracking { public class TrackerMOSSETest : TrackerTestBase { [Fact] public void Init() { using (var tracker = TrackerMOSSE.Create()) { InitBase(tracker); } } [Fact] public void Update() { using (var tracker = TrackerMOSSE.Create()) { UpdateBase(tracker); } } } }
19.074074
55
0.475728
[ "BSD-3-Clause" ]
AJEETX/opencvsharp
test/OpenCvSharp.Tests/tracking/TrackerMOSSETest.cs
517
C#
using System.Threading.Tasks; using Autofac; using Common; namespace MAVN.Service.AdminManagement.Domain.Services { public interface IRabbitPublisher<TMessage> : IStartable, IStopable { Task PublishAsync(TMessage message); } }
22.454545
71
0.753036
[ "MIT" ]
IliyanIlievPH/MAVN.Service.AdminManagement
src/MAVN.Service.AdminManagement.Domain/Services/IRabbitPublisher.cs
247
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Configuration; namespace Microsoft.Data.SqlClient { /// <summary> /// Authentication provider manager. /// </summary> internal class SqlAuthenticationProviderManager { private const string ActiveDirectoryPassword = "active directory password"; private const string ActiveDirectoryIntegrated = "active directory integrated"; private const string ActiveDirectoryInteractive = "active directory interactive"; static SqlAuthenticationProviderManager() { var activeDirectoryAuthNativeProvider = new ActiveDirectoryNativeAuthenticationProvider(); SqlAuthenticationProviderConfigurationSection configurationSection; try { configurationSection = (SqlAuthenticationProviderConfigurationSection)ConfigurationManager.GetSection(SqlAuthenticationProviderConfigurationSection.Name); } catch (ConfigurationErrorsException e) { throw SQL.CannotGetAuthProviderConfig(e); } Instance = new SqlAuthenticationProviderManager(configurationSection); Instance.SetProvider(SqlAuthenticationMethod.ActiveDirectoryIntegrated, activeDirectoryAuthNativeProvider); Instance.SetProvider(SqlAuthenticationMethod.ActiveDirectoryPassword, activeDirectoryAuthNativeProvider); Instance.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, activeDirectoryAuthNativeProvider); } public static readonly SqlAuthenticationProviderManager Instance; private readonly string _typeName; private readonly SqlAuthenticationInitializer _initializer; private readonly IReadOnlyCollection<SqlAuthenticationMethod> _authenticationsWithAppSpecifiedProvider; private readonly ConcurrentDictionary<SqlAuthenticationMethod, SqlAuthenticationProvider> _providers; private readonly SqlClientLogger _sqlAuthLogger = new SqlClientLogger(); /// <summary> /// Constructor. /// </summary> public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSection configSection) { _typeName = GetType().Name; var methodName = "Ctor"; _providers = new ConcurrentDictionary<SqlAuthenticationMethod, SqlAuthenticationProvider>(); var authenticationsWithAppSpecifiedProvider = new HashSet<SqlAuthenticationMethod>(); _authenticationsWithAppSpecifiedProvider = authenticationsWithAppSpecifiedProvider; if (configSection == null) { _sqlAuthLogger.LogInfo(_typeName, methodName, "No SqlAuthProviders configuration section found."); return; } // Create user-defined auth initializer, if any. // if (!string.IsNullOrEmpty(configSection.InitializerType)) { try { var initializerType = Type.GetType(configSection.InitializerType, true); _initializer = (SqlAuthenticationInitializer)Activator.CreateInstance(initializerType); _initializer.Initialize(); } catch (Exception e) { throw SQL.CannotCreateSqlAuthInitializer(configSection.InitializerType, e); } _sqlAuthLogger.LogInfo(_typeName, methodName, "Created user-defined SqlAuthenticationInitializer."); } else { _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined SqlAuthenticationInitializer found."); } // add user-defined providers, if any. // if (configSection.Providers != null && configSection.Providers.Count > 0) { foreach (ProviderSettings providerSettings in configSection.Providers) { SqlAuthenticationMethod authentication = AuthenticationEnumFromString(providerSettings.Name); SqlAuthenticationProvider provider; try { var providerType = Type.GetType(providerSettings.Type, true); provider = (SqlAuthenticationProvider)Activator.CreateInstance(providerType); } catch (Exception e) { throw SQL.CannotCreateAuthProvider(authentication.ToString(), providerSettings.Type, e); } if (!provider.IsSupported(authentication)) throw SQL.UnsupportedAuthenticationByProvider(authentication.ToString(), providerSettings.Type); _providers[authentication] = provider; authenticationsWithAppSpecifiedProvider.Add(authentication); _sqlAuthLogger.LogInfo(_typeName, methodName, $"Added user-defined auth provider: {providerSettings.Type} for authentication {authentication}."); } } else { _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined auth providers."); } } /// <summary> /// Get an authentication provider by method. /// </summary> /// <param name="authenticationMethod">Authentication method.</param> /// <returns>Authentication provider or null if not found.</returns> public SqlAuthenticationProvider GetProvider(SqlAuthenticationMethod authenticationMethod) { SqlAuthenticationProvider value; return _providers.TryGetValue(authenticationMethod, out value) ? value : null; } /// <summary> /// Set an authentication provider by method. /// </summary> /// <param name="authenticationMethod">Authentication method.</param> /// <param name="provider">Authentication provider.</param> /// <returns>True if succeeded, false otherwise, e.g., the existing provider disallows overriding.</returns> public bool SetProvider(SqlAuthenticationMethod authenticationMethod, SqlAuthenticationProvider provider) { if (!provider.IsSupported(authenticationMethod)) throw SQL.UnsupportedAuthenticationByProvider(authenticationMethod.ToString(), provider.GetType().Name); var methodName = "SetProvider"; if (_authenticationsWithAppSpecifiedProvider.Contains(authenticationMethod)) { _sqlAuthLogger.LogError(_typeName, methodName, $"Failed to add provider {GetProviderType(provider)} because a user-defined provider with type {GetProviderType(_providers[authenticationMethod])} already existed for authentication {authenticationMethod}."); return false; } _providers.AddOrUpdate(authenticationMethod, provider, (key, oldProvider) => { if (oldProvider != null) { oldProvider.BeforeUnload(authenticationMethod); } if (provider != null) { provider.BeforeLoad(authenticationMethod); } _sqlAuthLogger.LogInfo(_typeName, methodName, $"Added auth provider {GetProviderType(provider)}, overriding existed provider {GetProviderType(oldProvider)} for authentication {authenticationMethod}."); return provider; }); return true; } private static SqlAuthenticationMethod AuthenticationEnumFromString(string authentication) { switch (authentication.ToLowerInvariant()) { case ActiveDirectoryIntegrated: return SqlAuthenticationMethod.ActiveDirectoryIntegrated; case ActiveDirectoryPassword: return SqlAuthenticationMethod.ActiveDirectoryPassword; case ActiveDirectoryInteractive: return SqlAuthenticationMethod.ActiveDirectoryInteractive; default: throw SQL.UnsupportedAuthentication(authentication); } } private static string GetProviderType(SqlAuthenticationProvider provider) { if (provider == null) return "null"; return provider.GetType().FullName; } } /// <summary> /// The configuration section definition for reading app.config. /// </summary> internal class SqlAuthenticationProviderConfigurationSection : ConfigurationSection { public const string Name = "SqlAuthenticationProviders"; /// <summary> /// User-defined auth providers. /// </summary> [ConfigurationProperty("providers")] public ProviderSettingsCollection Providers => (ProviderSettingsCollection)base["providers"]; /// <summary> /// User-defined initializer. /// </summary> [ConfigurationProperty("initializerType")] public string InitializerType => base["initializerType"] as string; } /// <summary> /// The abstract initializer class that users can implement to initialize their component before SqlAuthenticationProviderManager starts. /// </summary> public abstract class SqlAuthenticationInitializer { /// <summary> /// The initialize callback from SqlAuthenticationProviderManager. This is called before SqlAuthenticationProviderManager loads providers. /// </summary> public abstract void Initialize(); } }
46.351852
271
0.644926
[ "MIT" ]
Gary-Zh/SqlClient
src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs
10,012
C#
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Net; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for BatchGetItem operation /// </summary> internal class BatchGetItemResponseUnmarshaller : JsonResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { BatchGetItemResponse response = new BatchGetItemResponse(); context.Read(); response.BatchGetItemResult = BatchGetItemResultUnmarshaller.GetInstance().Unmarshall(context); return response; } public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { ResourceNotFoundException ex = new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); return ex; } if (errorResponse.Code != null && errorResponse.Code.Equals("ProvisionedThroughputExceededException")) { ProvisionedThroughputExceededException ex = new ProvisionedThroughputExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); return ex; } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException")) { InternalServerErrorException ex = new InternalServerErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); return ex; } return new AmazonDynamoDBException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static BatchGetItemResponseUnmarshaller instance; public static BatchGetItemResponseUnmarshaller GetInstance() { if (instance == null) { instance = new BatchGetItemResponseUnmarshaller(); } return instance; } } }
40.691358
215
0.685983
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.DynamoDBv2/Model/Internal/MarshallTransformations/BatchGetItemResponseUnmarshaller.cs
3,296
C#
using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using Terminal.Gui; namespace ReactiveExample { public class TerminalScheduler : LocalScheduler { public static readonly TerminalScheduler Default = new TerminalScheduler(); TerminalScheduler () { } public override IDisposable Schedule<TState> ( TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action) { IDisposable PostOnMainLoop() { var composite = new CompositeDisposable(2); var cancellation = new CancellationDisposable(); Application.MainLoop.Invoke (() => { if (!cancellation.Token.IsCancellationRequested) composite.Add(action(this, state)); }); composite.Add(cancellation); return composite; } IDisposable PostOnMainLoopAsTimeout () { var composite = new CompositeDisposable (2); var timeout = Application.MainLoop.AddTimeout (dueTime, args => { composite.Add(action (this, state)); return false; }); composite.Add (Disposable.Create (() => Application.MainLoop.RemoveTimeout (timeout))); return composite; } return dueTime == TimeSpan.Zero ? PostOnMainLoop () : PostOnMainLoopAsTimeout (); } } }
29.878049
91
0.710204
[ "MIT" ]
BDisp/gui.cs
ReactiveExample/TerminalScheduler.cs
1,227
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.SqlServer.Internal; namespace Microsoft.EntityFrameworkCore.Metadata.Internal; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static class SqlServerIndexExtensions { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static bool AreCompatibleForSqlServer( this IReadOnlyIndex index, IReadOnlyIndex duplicateIndex, in StoreObjectIdentifier storeObject, bool shouldThrow) { if (index.GetIncludeProperties() != duplicateIndex.GetIncludeProperties()) { if (index.GetIncludeProperties() == null || duplicateIndex.GetIncludeProperties() == null || !SameColumnNames(index, duplicateIndex, storeObject)) { if (shouldThrow) { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexIncludedMismatch( index.DisplayName(), index.DeclaringEntityType.DisplayName(), duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject), FormatInclude(index, storeObject), FormatInclude(duplicateIndex, storeObject))); } return false; } } if (index.IsCreatedOnline() != duplicateIndex.IsCreatedOnline()) { if (shouldThrow) { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexOnlineMismatch( index.DisplayName(), index.DeclaringEntityType.DisplayName(), duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject))); } return false; } if (index.IsClustered(storeObject) != duplicateIndex.IsClustered(storeObject)) { if (shouldThrow) { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexClusteredMismatch( index.DisplayName(), index.DeclaringEntityType.DisplayName(), duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject))); } return false; } if (index.GetFillFactor() != duplicateIndex.GetFillFactor()) { if (shouldThrow) { throw new InvalidOperationException( SqlServerStrings.DuplicateIndexFillFactorMismatch( index.DisplayName(), index.DeclaringEntityType.DisplayName(), duplicateIndex.DisplayName(), duplicateIndex.DeclaringEntityType.DisplayName(), index.DeclaringEntityType.GetSchemaQualifiedTableName(), index.GetDatabaseName(storeObject))); } return false; } return true; static bool SameColumnNames(IReadOnlyIndex index, IReadOnlyIndex duplicateIndex, StoreObjectIdentifier storeObject) => index.GetIncludeProperties()!.Select( p => index.DeclaringEntityType.FindProperty(p)!.GetColumnName(storeObject)) .SequenceEqual( duplicateIndex.GetIncludeProperties()!.Select( p => duplicateIndex.DeclaringEntityType.FindProperty(p)!.GetColumnName(storeObject))); } private static string FormatInclude(IReadOnlyIndex index, StoreObjectIdentifier storeObject) => index.GetIncludeProperties() == null ? "{}" : "{'" + string.Join( "', '", index.GetIncludeProperties()!.Select( p => index.DeclaringEntityType.FindProperty(p) ?.GetColumnName(storeObject))) + "'}"; }
44.491935
123
0.585463
[ "MIT" ]
AraHaan/efcore
src/EFCore.SqlServer/Metadata/Internal/SqlServerIndexExtensions.cs
5,517
C#
namespace LogMeIn.Security { // TODO: what parameters are needed? public interface IUserProfileManager { bool Exists(string userName); void Add(string userName); } }
21.888889
40
0.659898
[ "MIT" ]
OdeToCode/Memflex
src/Sample.Mongo/Security/IUserProfileManager.cs
197
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using ExcelUtility.Utils; namespace ExcelUtility.Impl { internal class Row : IRow { public static Row FromExisting(XElementData data, ISheetData sheetData) { return new Row(data, sheetData); } public static Row New(XElementData data, int index, ISheetData sheetData) { return new Row(data, index, sheetData); } private List<ICell> cells = null; // lazy load private ISheetData sheetData; private SharedStrings SharedStrings { get { return sheetData.Worksheet.Workbook.SharedStrings; } } public XElementData Data { get; set; } public int Index { get; private set; } public IEnumerable<ICell> DefinedCells { get { return LazyLoadCells(); } } private bool CustomHeight { get { return object.Equals(Data["customHeight"], "1"); } set { Data.SetAttributeValue("customHeight", value ? "1" : null); } } public double Height { get { var ht = Data["ht"]; return ht == null ? sheetData.Worksheet.DefaultRowHeight : double.Parse(ht, NumberFormatInfo.InvariantInfo); } set { var customHeight = value != sheetData.Worksheet.DefaultRowHeight; CustomHeight = customHeight; Data.SetAttributeValue("ht", customHeight ? (object)value : null); } } // existing rows constructor private Row(XElementData data, ISheetData sheetData) { this.Data = data; this.sheetData = sheetData; Index = int.Parse(data["r"], NumberFormatInfo.InvariantInfo); data.RemoveAttribute("spans"); // clear spans attribute, will be recalculated } // new rows constructor private Row(XElementData data, int index, ISheetData sheetData) { if (index == 0) throw new ArgumentException("Row index can't be zero (0)", "index"); this.Data = data; this.sheetData = sheetData; Index = index; data.SetAttributeValue("r", index); } public ICell GetCell(string columnName) { LazyLoadCells(); var search = new FakeCell() { Name = columnName + Index }; int insert = cells.BinarySearch(search, CompareCells); if (insert < 0) { insert = ~insert; AddCell(columnName, insert); } return cells[insert]; } public void Remove(ICell cell) { LazyLoadCells(); cells.Remove(cell); } private void AddCell(string columnName, int cellIndex) { XElementData cellData; if (cellIndex == 0) cellData = Data.Add("c"); else cellData = ((Cell)cells[cellIndex - 1]).Data.AddAfterSelf("c"); var newCell = Cell.New(cellData, this, columnName + Index, SharedStrings); newCell.Style = sheetData.Worksheet.SheetColumns.GetColumn(columnName).Style; cells.Insert(cellIndex, newCell); } public ICell GetCell(int columnIndex) { return GetCell(ColumnUtil.GetColumnName(columnIndex)); } private int CompareCells(ICell cell1, ICell cell2) { int compare = cell1.Name.Length.CompareTo(cell2.Name.Length); if (compare == 0) return cell1.Name.CompareTo(cell2.Name); return compare; } private IList<ICell> LazyLoadCells() { if (cells == null) cells = Data.Descendants("c").Select(c => (ICell)(Cell.FromExisting(c, this, SharedStrings))).ToList(); return cells; } private class FakeCell : ICell { public string StringValue { get; set; } public double DoubleValue { get; set; } public string Name { get; set; } public long LongValue { get; set; } public bool IsTypeString { get; set; } public int? Style { get; set; } public void Remove() { } } } }
34.212121
163
0.536537
[ "MIT" ]
zbra-solutions/excel-utility
ExcelUtility/Impl/Row.cs
4,518
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Identity.Areas.Identity.Data; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; namespace Identity.Areas.Identity.Pages.Account { [AllowAnonymous] public class ResetPasswordModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; public ResetPasswordModel(UserManager<ApplicationUser> userManager) { _userManager = userManager; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public IActionResult OnGet(string code = null) { if (code == null) { return BadRequest("A code must be supplied for password reset."); } else { Input = new InputModel { Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)) }; return Page(); } } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToPage("./ResetPasswordConfirmation"); } var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password); if (result.Succeeded) { return RedirectToPage("./ResetPasswordConfirmation"); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } } }
30.380435
129
0.571377
[ "MIT" ]
namchokGithub/AuthSystem
Identity/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs
2,797
C#
using System.Collections.Generic; using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.DateTime { public interface IDatePeriodExtractorConfiguration : IOptionsConfiguration { IEnumerable<Regex> SimpleCasesRegexes { get; } Regex IllegalYearRegex { get; } Regex YearRegex { get; } Regex TillRegex { get; } Regex DateUnitRegex { get; } Regex TimeUnitRegex { get; } Regex FollowedDateUnit { get; } Regex NumberCombinedWithDateUnit { get; } Regex PastRegex { get; } Regex FutureRegex { get; } Regex FutureSuffixRegex { get; } Regex WeekOfRegex { get; } Regex MonthOfRegex { get; } Regex RangeUnitRegex { get; } Regex InConnectorRegex { get; } Regex WithinNextPrefixRegex { get; } Regex YearPeriodRegex { get; } Regex RelativeDecadeRegex { get; } Regex ComplexDatePeriodRegex { get; } Regex ReferenceDatePeriodRegex { get; } Regex AgoRegex { get; } Regex LaterRegex { get; } Regex LessThanRegex { get; } Regex MoreThanRegex { get; } Regex CenturySuffixRegex { get; } IDateTimeExtractor DatePointExtractor { get; } IExtractor CardinalExtractor { get; } IExtractor OrdinalExtractor { get; } IDateTimeExtractor DurationExtractor { get; } IParser NumberParser { get; } bool GetFromTokenIndex(string text, out int index); bool HasConnectorToken(string text); bool GetBetweenTokenIndex(string text, out int index); string[] DurationDateRestrictions { get; } } }
22.236842
78
0.630178
[ "MIT" ]
ZeroInfinite/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Extractors/IDatePeriodExtractorConfiguration.cs
1,692
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Xunit.Abstractions; namespace Xunit.Sdk { /// <summary> /// The test assembly runner for xUnit.net v2 tests. /// </summary> public class XunitTestAssemblyRunner : TestAssemblyRunner<IXunitTestCase> { IAttributeInfo collectionBehaviorAttribute; bool disableParallelization; bool initialized; int maxParallelThreads; SynchronizationContext originalSyncContext; MaxConcurrencySyncContext syncContext; /// <summary> /// Initializes a new instance of the <see cref="XunitTestAssemblyRunner"/> class. /// </summary> /// <param name="testAssembly">The assembly that contains the tests to be run.</param> /// <param name="testCases">The test cases to be run.</param> /// <param name="messageSink">The message sink to report run status to.</param> /// <param name="executionOptions">The user's requested execution options.</param> public XunitTestAssemblyRunner(ITestAssembly testAssembly, IEnumerable<IXunitTestCase> testCases, IMessageSink messageSink, ITestFrameworkExecutionOptions executionOptions) : base(testAssembly, testCases, messageSink, executionOptions) { } /// <inheritdoc/> public override void Dispose() { var disposable = syncContext as IDisposable; if (disposable != null) disposable.Dispose(); } /// <inheritdoc/> protected override string GetTestFrameworkDisplayName() { return XunitTestFrameworkDiscoverer.DisplayName; } /// <inheritdoc/> protected override string GetTestFrameworkEnvironment() { Initialize(); var testCollectionFactory = ExtensibilityPointFactory.GetXunitTestCollectionFactory(collectionBehaviorAttribute, TestAssembly); return String.Format("{0} [{1}, {2}{3}]", base.GetTestFrameworkEnvironment(), testCollectionFactory.DisplayName, disableParallelization ? "non-parallel" : "parallel", maxParallelThreads > 0 ? String.Format(" ({0} threads)", maxParallelThreads) : ""); } /// <summary> /// Gets the synchronization context used when potentially running tests in parallel. /// If <paramref name="maxParallelThreads"/> is greater than 0, it creates /// and uses an instance of <see cref="MaxConcurrencySyncContext"/>. /// </summary> /// <param name="maxParallelThreads">The maximum number of parallel threads.</param> protected virtual void SetupSyncContext(int maxParallelThreads) { if (maxParallelThreads < 1) maxParallelThreads = Environment.ProcessorCount; syncContext = new MaxConcurrencySyncContext(maxParallelThreads); SetSynchronizationContext(syncContext); } /// <summary> /// Ensures the assembly runner is initialized (sets up the collection behavior, /// parallelization options, and test orderers from their assembly attributes). /// </summary> protected void Initialize() { if (initialized) return; collectionBehaviorAttribute = TestAssembly.Assembly.GetCustomAttributes(typeof(CollectionBehaviorAttribute)).SingleOrDefault(); if (collectionBehaviorAttribute != null) { disableParallelization = collectionBehaviorAttribute.GetNamedArgument<bool>("DisableTestParallelization"); maxParallelThreads = collectionBehaviorAttribute.GetNamedArgument<int>("MaxParallelThreads"); } disableParallelization = ExecutionOptions.GetValue<bool>(TestOptionsNames.Execution.DisableParallelization, disableParallelization); var maxParallelThreadsOption = ExecutionOptions.GetValue<int>(TestOptionsNames.Execution.MaxParallelThreads, 0); if (maxParallelThreadsOption > 0) maxParallelThreads = maxParallelThreadsOption; var testCaseOrdererAttribute = TestAssembly.Assembly.GetCustomAttributes(typeof(TestCaseOrdererAttribute)).SingleOrDefault(); if (testCaseOrdererAttribute != null) TestCaseOrderer = ExtensibilityPointFactory.GetTestCaseOrderer(testCaseOrdererAttribute); var testCollectionOrdererAttribute = TestAssembly.Assembly.GetCustomAttributes(typeof(TestCollectionOrdererAttribute)).SingleOrDefault(); if (testCollectionOrdererAttribute != null) TestCollectionOrderer = ExtensibilityPointFactory.GetTestCollectionOrderer(testCollectionOrdererAttribute); initialized = true; } /// <inheritdoc/> protected override Task AfterTestAssemblyStartingAsync() { Initialize(); return Task.FromResult(0); } /// <inheritdoc/> protected override Task BeforeTestAssemblyFinishedAsync() { SetSynchronizationContext(originalSyncContext); return Task.FromResult(0); } /// <inheritdoc/> protected override async Task<RunSummary> RunTestCollectionsAsync(IMessageBus messageBus, CancellationTokenSource cancellationTokenSource) { originalSyncContext = SynchronizationContext.Current; if (disableParallelization) return await base.RunTestCollectionsAsync(messageBus, cancellationTokenSource); SetupSyncContext(maxParallelThreads); var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); var tasks = OrderTestCases().Select( collection => Task.Factory.StartNew(() => RunTestCollectionAsync(messageBus, collection.Item1, collection.Item2, cancellationTokenSource), cancellationTokenSource.Token, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler, scheduler) ).ToArray(); var summaries = await Task.WhenAll(tasks.Select(t => t.Unwrap())); return new RunSummary() { Total = summaries.Sum(s => s.Total), Failed = summaries.Sum(s => s.Failed), Skipped = summaries.Sum(s => s.Skipped) }; } /// <inheritdoc/> protected override Task<RunSummary> RunTestCollectionAsync(IMessageBus messageBus, ITestCollection testCollection, IEnumerable<IXunitTestCase> testCases, CancellationTokenSource cancellationTokenSource) { return new XunitTestCollectionRunner(testCollection, testCases, messageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), cancellationTokenSource).RunAsync(); } [SecuritySafeCritical] static void SetSynchronizationContext(SynchronizationContext context) { SynchronizationContext.SetSynchronizationContext(context); } } }
45.185629
210
0.632388
[ "Apache-2.0" ]
appveyor/xunit
src/xunit.execution/Sdk/Frameworks/Runners/XunitTestAssemblyRunner.cs
7,548
C#