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 |
|---|---|---|---|---|---|---|---|---|
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenSearch.OpenSearch.Xunit.XunitPlumbing;
using OpenSearch.Net;
using Osc;
using Tests.Core.Client;
using Tests.Framework;
using static Tests.Core.Serialization.SerializationTestHelper;
namespace Tests.ClientConcepts.HighLevel.Mapping
{
/**
* [[auto-map]]
* === Auto mapping
*
* When creating a mapping either when creating an index or through the Put Mapping API,
* OSC offers a feature called auto mapping that can automagically infer the correct
* OpenSearch field datatypes from the CLR POCO property types you are mapping.
**/
public class AutoMap
{
private readonly IOpenSearchClient _client = TestClient.DisabledStreaming;
/**
* We'll look at the features of auto mapping with a number of examples. For this,
* we'll define two POCOs, `Company`, which has a name
* and a collection of Employees, and `Employee` which has various properties of
* different types, and itself has a collection of `Employee` types.
*/
public abstract class Document
{
public JoinField Join { get; set; }
}
public class Company : Document
{
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee : Document
{
public string LastName { get; set; }
public int Salary { get; set; }
public DateTime Birthday { get; set; }
public bool IsManager { get; set; }
public List<Employee> Employees { get; set; }
public TimeSpan Hours { get; set; }
}
[U]
public void UsingAutoMap()
{
/**
* Auto mapping can take the pain out of having to define a manual mapping for all properties
* on the POCO. In this case we want to index two subclasses into a single index. We call Map
* for the base class and then call AutoMap foreach of the types we want it to implement
*/
var createIndexResponse = _client.Indices.Create("myindex", c => c
.Map<Document>(m => m
.AutoMap<Company>() // <1> Auto map `Company` using the generic method
.AutoMap(typeof(Employee)) // <2> Auto map `Employee` using the non-generic method
)
);
/**
* This produces the following JSON request
*/
// json
var expected = new
{
mappings = new
{
properties = new
{
birthday = new {type = "date"},
employees = new
{
properties = new
{
birthday = new {type = "date"},
employees = new
{
properties = new { },
type = "object"
},
hours = new {type = "long"},
isManager = new {type = "boolean"},
join = new
{
properties = new { },
type = "object"
},
lastName = new
{
fields = new
{
keyword = new
{
ignore_above = 256,
type = "keyword"
}
},
type = "text"
},
salary = new {type = "integer"}
},
type = "object"
},
hours = new {type = "long"},
isManager = new {type = "boolean"},
join = new
{
properties = new { },
type = "object"
},
lastName = new
{
fields = new
{
keyword = new
{
ignore_above = 256,
type = "keyword"
}
},
type = "text"
},
name = new
{
fields = new
{
keyword = new
{
ignore_above = 256,
type = "keyword"
}
},
type = "text"
},
salary = new {type = "integer"}
}
}
};
// hide
Expect(expected).FromRequest(createIndexResponse);
}
/**
* Observe that OSC has inferred the OpenSearch types based on the CLR type of our POCO properties.
* In this example,
*
* - Birthday is mapped as a `date`,
* - Hours is mapped as a `long` (`TimeSpan` ticks)
* - IsManager is mapped as a `boolean`,
* - Salary is mapped as an `integer`
* - Employees is mapped as an `object`
*
* and the remaining string properties as multi field `text` datatypes, each with a `keyword` datatype
* sub field.
*
* [float]
* [[inferred-dotnet-type-mapping]]
* === Inferred .NET type mapping
*
* OSC has inferred mapping support for the following .NET types
*
* [horizontal]
* `String`:: maps to `"text"` with a `"keyword"` sub field. See <<multi-fields, Multi Fields>>.
* `Int32`:: maps to `"integer"`
* `UInt16`:: maps to `"integer"`
* `Int16`:: maps to `"short"`
* `Byte`:: maps to `"short"`
* `Int64`:: maps to `"long"`
* `UInt32`:: maps to `"long"`
* `TimeSpan`:: maps to `"long"`
* `Single`:: maps to `"float"`
* `Double`:: maps to `"double"`
* `Decimal`:: maps to `"double"`
* `UInt64`:: maps to `"double"`
* `DateTime`:: maps to `"date"`
* `DateTimeOffset`:: maps to `"date"`
* `Boolean`:: maps to `"boolean"`
* `Char`:: maps to `"keyword"`
* `Guid`:: maps to `"keyword"`
*
* and supports a number of special types defined in OSC
*
* [horizontal]
* `Osc.QueryContainer`:: maps to `"percolator"`
* `Osc.GeoLocation`:: maps to `"geo_point"`
* `Osc.IGeoShape`:: maps to `"geo_shape"` (if you want to map to a `"shape"` type use explicit mapping or the [Shape] attribute on the property)
* `Osc.CompletionField`:: maps to `"completion"`
* `Osc.DateRange`:: maps to `"date_range"`
* `Osc.DoubleRange`:: maps to `"double_range"`
* `Osc.FloatRange`:: maps to `"float_range"`
* `Osc.IntegerRange`:: maps to `"integer_range"`
* `Osc.LongRange`:: maps to `"long_range"`
* `Osc.IpAddressRange`:: maps to `"ip_range"`
*
* All other types map to `"object"` by default.
*
*[IMPORTANT]
* --
* Some .NET types do not have direct equivalent OpenSearch types. For example, `System.Decimal` is a type
* commonly used to express currencies and other financial calculations that require large numbers of significant
* integral and fractional digits and no round-off errors. There is no equivalent type in OpenSearch, and the
* nearest type is {ref_current}/number.html[double], a double-precision 64-bit IEEE 754 floating point.
*
* When a POCO has a `System.Decimal` property, it is automapped to the OpenSearch `double` type. With the caveat
* of a potential loss of precision, this is generally acceptable for a lot of use cases, but it can however cause
* problems in _some_ edge cases.
*
* As the https://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/csharp%20language%20specification.doc[C# Specification states],
*
* [quote, C# Specification section 6.2.1]
* For a conversion from `decimal` to `float` or `double`, the `decimal` value is rounded to the nearest `double` or `float` value.
* While this conversion may lose precision, it never causes an exception to be thrown.
*
* This conversion does cause an exception to be thrown at deserialization time for `Decimal.MinValue` and `Decimal.MaxValue` because, at
* serialization time, the nearest `double` value that is converted to is outside of the bounds of `Decimal.MinValue` or `Decimal.MaxValue`,
* respectively. In these cases, it is advisable to use `double` as the POCO property type.
* --
*/
/**[float]
* === Mapping Recursion
* If you notice in our previous `Company` and `Employee` example, the `Employee` type is recursive
* in that the `Employee` class itself contains a collection of type `Employee`. By default, `.AutoMap()` will only
* traverse a single depth when it encounters recursive instances like this; the collection of type `Employee`
* on the `Employee` class did not get any of its properties mapped.
*
* This is done as a safe-guard to prevent stack overflows and all the fun that comes with
* __infinite__ recursion. Additionally, in most cases, when it comes to OpenSearch mappings, it is
* often an edge case to have deeply nested mappings like this. However, you may still have
* the need to do this, so you can control the recursion depth of `.AutoMap()`.
*
* Let's introduce a very simple class, `A`, which itself has a property
* Child of type `A`.
*/
public class A
{
public A Child { get; set; }
}
[U]
public void ControllingRecursionDepth()
{
/** By default, `.AutoMap()` only goes as far as depth 1 */
var createIndexResponse = _client.Indices.Create("myindex", c => c
.Map<A>(m => m.AutoMap())
);
/** Thus we do not map properties on the second occurrence of our Child property */
//json
var expected = new
{
mappings = new
{
properties = new
{
child = new
{
properties = new { },
type = "object"
}
}
}
};
//hide
Expect(expected).FromRequest(createIndexResponse);
/** Now let's specify a maxRecursion of `3` */
createIndexResponse = _client.Indices.Create("myindex", c => c
.Map<A>(m => m.AutoMap(3))
);
/** `.AutoMap()` has now mapped three levels of our Child property */
//json
var expectedWithMaxRecursion = new
{
mappings = new
{
properties = new
{
child = new
{
type = "object",
properties = new
{
child = new
{
type = "object",
properties = new
{
child = new
{
type = "object",
properties = new
{
child = new
{
type = "object",
properties = new { }
}
}
}
}
}
}
}
}
}
};
//hide
Expect(expectedWithMaxRecursion).FromRequest(createIndexResponse);
}
//hide
[U]
public void PutMappingAlsoAdheresToMaxRecursion()
{
var descriptor = new PutMappingDescriptor<A>().AutoMap();
var expected = new
{
properties = new
{
child = new
{
properties = new { },
type = "object"
}
}
};
Expect(expected).WhenSerializing((IPutMappingRequest) descriptor);
var withMaxRecursionDescriptor = new PutMappingDescriptor<A>().AutoMap(3);
var expectedWithMaxRecursion = new
{
properties = new
{
child = new
{
type = "object",
properties = new
{
child = new
{
type = "object",
properties = new
{
child = new
{
type = "object",
properties = new
{
child = new
{
type = "object",
properties = new { }
}
}
}
}
}
}
}
}
};
Expect(expectedWithMaxRecursion).WhenSerializing((IPutMappingRequest)withMaxRecursionDescriptor);
}
}
}
| 28.956204 | 158 | 0.610285 | [
"Apache-2.0"
] | Bit-Quill/opensearch-net | tests/Tests/ClientConcepts/HighLevel/Mapping/AutoMap.doc.cs | 11,901 | C# |
#pragma warning disable 1591
// ReSharper disable UnusedParameter.Global
namespace NServiceBus.Unicast
{
using System;
public partial class UnicastBus
{
[ObsoleteEx(RemoveInVersion = "6", TreatAsErrorFromVersion = "5", Message = "InMemory.Raise has been removed from the core please see http://docs.particular.net/nservicebus/inmemoryremoval")]
public void Raise<T>(Action<T> messageConstructor)
{
ThrowInMemoryException();
}
[ObsoleteEx(RemoveInVersion = "6", TreatAsErrorFromVersion = "5", Message = "InMemory.Raise has been removed from the core please see http://docs.particular.net/nservicebus/inmemoryremoval")]
public void Raise<T>(T @event)
{
ThrowInMemoryException();
}
static void ThrowInMemoryException()
{
throw new Exception("InMemory.Raise has been removed from the core please see http://docs.particular.net/nservicebus/inmemoryremoval");
}
[ObsoleteEx(RemoveInVersion = "6", TreatAsErrorFromVersion = "5", Message = "InMemory has been removed from the core please see http://docs.particular.net/nservicebus/inmemoryremoval")]
public IInMemoryOperations InMemory
{
get
{
ThrowInMemoryException();
return null;
}
}
}
}
| 38.189189 | 200 | 0.631989 | [
"Apache-2.0",
"MIT"
] | ChrisMissal/NServiceBus | src/NServiceBus.Core/Unicast/UnicastBus_Obsolete.cs | 1,377 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Roslynator.CSharp.CodeFixes.Test
{
internal static class RemoveRedundantAssignment
{
}
}
| 27.4 | 160 | 0.755474 | [
"Apache-2.0"
] | TechnoridersForks/Roslynator | source/Test/CodeFixesTest/RemoveRedundantAssignment.cs | 276 | C# |
namespace Eventus
{
using Domain;
using Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class AggregateCache
{
private static List<Assembly>? _internalAggregateAssemblies;
private static Dictionary<Type, Dictionary<Type, MethodInfo>>? _internalAggregateEventHandlerCache;
private static Dictionary<Type, Dictionary<Type, MethodInfo>> AggregateEventHandlerCache
{
get
{
_internalAggregateEventHandlerCache ??= BuildAggregateEventHandlerCache();
return _internalAggregateEventHandlerCache;
}
}
public static List<Assembly> AggregateAssemblies
{
get
{
if (_internalAggregateAssemblies != null)
{
return _internalAggregateAssemblies;
}
_internalAggregateAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
return _internalAggregateAssemblies;
}
set
{
_internalAggregateAssemblies = value;
}
}
public static Dictionary<Type, MethodInfo> GetEventHandlersForAggregate(Type aggregateType)
{
return AggregateEventHandlerCache[aggregateType];
}
public static List<Type> GetAggregateTypes()
{
var aggregateType = typeof(Aggregate);
var assemblies = AggregateAssemblies;
var types = assemblies.SelectMany(t => t.GetTypes())
.Where(t => t != aggregateType && aggregateType.IsAssignableFrom(t))
.ToList();
return types;
}
private static Dictionary<Type, Dictionary<Type, MethodInfo>> BuildAggregateEventHandlerCache()
{
var cache = new Dictionary<Type, Dictionary<Type, MethodInfo>>();
var aggregateTypes = GetAggregateTypes();
foreach (Type aggregateType in aggregateTypes)
{
var eventHandlers = new Dictionary<Type, MethodInfo>();
var methods = aggregateType.GetMethodsBySig(typeof(void), true, typeof(IEvent)).ToList();
if (methods.Any())
{
foreach (var m in methods)
{
var parameter = m.GetParameters().First();
eventHandlers.Add(parameter.ParameterType, m);
}
}
cache.Add(aggregateType, eventHandlers);
}
return cache;
}
}
} | 32.452381 | 107 | 0.557594 | [
"MIT"
] | ForrestTech/Eventus | src/Eventus/AggregateCache.cs | 2,728 | C# |
using System;
namespace Bridge
{
[Ignore]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate | AttributeTargets.Interface, AllowMultiple = true)]
public class AllowAttribute : Attribute
{
}
} | 27.9 | 173 | 0.749104 | [
"Apache-2.0"
] | corefan/Bridge | Bridge/Attributes/AllowAttribute.cs | 281 | C# |
namespace DotNetty.Transport.Tests.Channel
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using DotNetty.Common.Concurrency;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Embedded;
using Xunit;
public class CombinedChannelDuplexHandlerTest
{
private static readonly object MSG = new object();
private static IPEndPoint ADDRESS = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort);
private enum Event
{
REGISTERED,
UNREGISTERED,
ACTIVE,
INACTIVE,
CHANNEL_READ,
CHANNEL_READ_COMPLETE,
EXCEPTION_CAUGHT,
USER_EVENT_TRIGGERED,
CHANNEL_WRITABILITY_CHANGED,
HANDLER_ADDED,
HANDLER_REMOVED,
BIND,
CONNECT,
WRITE,
FLUSH,
READ,
REGISTER,
DEREGISTER,
CLOSE,
DISCONNECT
}
[Fact]
public void TestInboundRemoveBeforeAdded()
{
CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter> handler =
new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
new ChannelHandlerAdapter(), new ChannelHandlerAdapter());
Assert.Throws<InvalidOperationException>(() => handler.RemoveInboundHandler());
}
[Fact]
public void TestOutboundRemoveBeforeAdded()
{
CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter> handler =
new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
new ChannelHandlerAdapter(), new ChannelHandlerAdapter());
Assert.Throws<InvalidOperationException>(() => handler.RemoveOutboundHandler());
}
//[Fact]
//public void TestInboundHandlerImplementsOutboundHandler()
//{
// Assert.Throws<ArgumentException>(() =>
// new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
// new ChannelDuplexHandler(), new ChannelHandlerAdapter()));
//}
//[Fact]
//public void TestOutboundHandlerImplementsInboundHandler()
//{
// Assert.Throws<ArgumentException>(() =>
// new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
// new ChannelHandlerAdapter(), new ChannelDuplexHandler()));
//}
[Fact]
public void TestInitNotCalledBeforeAdded()
{
CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter> handler =
new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>() { };
Assert.Throws<InvalidOperationException>(() => handler.HandlerAdded(null));
}
[Fact]
public void TestExceptionCaughtBothCombinedHandlers()
{
Exception exception = new Exception();
Queue<IChannelHandler> queue = new Queue<IChannelHandler>();
var inboundHandler = new ChannelInboundHandlerAdapter0(exception, queue);
var outboundHandler = new ChannelOutboundHandlerAdapter0(exception, queue);
var lastHandler = new ChannelInboundHandlerAdapter1(exception, queue);
EmbeddedChannel channel = new EmbeddedChannel(
new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
inboundHandler, outboundHandler), lastHandler);
channel.Pipeline.FireExceptionCaught(exception);
Assert.False(channel.Finish());
Assert.Same(inboundHandler, queue.Dequeue());
Assert.Same(outboundHandler, queue.Dequeue());
Assert.Same(lastHandler, queue.Dequeue());
Assert.Empty(queue);
}
class ChannelInboundHandlerAdapter0 : ChannelHandlerAdapter
{
private readonly Exception _exception;
private readonly Queue<IChannelHandler> _queue;
public ChannelInboundHandlerAdapter0(Exception exception, Queue<IChannelHandler> queue)
{
_exception = exception;
_queue = queue;
}
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Assert.Same(_exception, exception);
_queue.Enqueue(this);
context.FireExceptionCaught(exception);
}
}
class ChannelOutboundHandlerAdapter0 : ChannelHandlerAdapter
{
private readonly Exception _exception;
private readonly Queue<IChannelHandler> _queue;
public ChannelOutboundHandlerAdapter0(Exception exception, Queue<IChannelHandler> queue)
{
_exception = exception;
_queue = queue;
}
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Assert.Same(_exception, exception);
_queue.Enqueue(this);
context.FireExceptionCaught(exception);
}
}
class ChannelInboundHandlerAdapter1 : ChannelHandlerAdapter
{
private readonly Exception _exception;
private readonly Queue<IChannelHandler> _queue;
public ChannelInboundHandlerAdapter1(Exception exception, Queue<IChannelHandler> queue)
{
_exception = exception;
_queue = queue;
}
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Assert.Same(_exception, exception);
_queue.Enqueue(this);
}
}
[Fact]
public void TestInboundEvents()
{
Queue<Event> queue = new Queue<Event>();
var inboundHandler = new ChannelInboundHandlerAdapter2(queue);
CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter> handler =
new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
inboundHandler, new ChannelHandlerAdapter());
EmbeddedChannel channel = new EmbeddedChannel(handler);
channel.Pipeline.FireChannelWritabilityChanged();
channel.Pipeline.FireUserEventTriggered(MSG);
channel.Pipeline.FireChannelRead(MSG);
channel.Pipeline.FireChannelReadComplete();
Assert.Equal(Event.HANDLER_ADDED, queue.Dequeue());
Assert.Equal(Event.REGISTERED, queue.Dequeue());
Assert.Equal(Event.ACTIVE, queue.Dequeue());
Assert.Equal(Event.CHANNEL_WRITABILITY_CHANGED, queue.Dequeue());
Assert.Equal(Event.USER_EVENT_TRIGGERED, queue.Dequeue());
Assert.Equal(Event.CHANNEL_READ, queue.Dequeue());
Assert.Equal(Event.CHANNEL_READ_COMPLETE, queue.Dequeue());
handler.RemoveInboundHandler();
Assert.Equal(Event.HANDLER_REMOVED, queue.Dequeue());
// These should not be handled by the inboundHandler anymore as it was removed before
channel.Pipeline.FireChannelWritabilityChanged();
channel.Pipeline.FireUserEventTriggered(MSG);
channel.Pipeline.FireChannelRead(MSG);
channel.Pipeline.FireChannelReadComplete();
// Should have not received any more events as it was removed before via removeInboundHandler()
Assert.Empty(queue);
Assert.True(channel.Finish());
Assert.Empty(queue);
}
class ChannelInboundHandlerAdapter2 : ChannelHandlerAdapter
{
private readonly Queue<Event> _queue;
public ChannelInboundHandlerAdapter2(Queue<Event> queue) => _queue = queue;
public override void HandlerAdded(IChannelHandlerContext context)
{
_queue.Enqueue(Event.HANDLER_ADDED);
}
public override void HandlerRemoved(IChannelHandlerContext context)
{
_queue.Enqueue(Event.HANDLER_REMOVED);
}
public override void ChannelRegistered(IChannelHandlerContext context)
{
_queue.Enqueue(Event.REGISTERED);
}
public override void ChannelUnregistered(IChannelHandlerContext context)
{
_queue.Enqueue(Event.UNREGISTERED);
}
public override void ChannelActive(IChannelHandlerContext context)
{
_queue.Enqueue(Event.ACTIVE);
}
public override void ChannelInactive(IChannelHandlerContext context)
{
_queue.Enqueue(Event.INACTIVE);
}
public override void ChannelRead(IChannelHandlerContext context, object message)
{
_queue.Enqueue(Event.CHANNEL_READ);
}
public override void ChannelReadComplete(IChannelHandlerContext context)
{
_queue.Enqueue(Event.CHANNEL_READ_COMPLETE);
}
public override void UserEventTriggered(IChannelHandlerContext context, object evt)
{
_queue.Enqueue(Event.USER_EVENT_TRIGGERED);
}
public override void ChannelWritabilityChanged(IChannelHandlerContext context)
{
_queue.Enqueue(Event.CHANNEL_WRITABILITY_CHANGED);
}
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
_queue.Enqueue(Event.EXCEPTION_CAUGHT);
}
}
[Fact]
public void TestOutboundEvents()
{
Queue<Event> queue = new Queue<Event>();
var inboundHandler = new ChannelHandlerAdapter();
var outboundHandler = new ChannelOutboundHandlerAdapter2(queue);
CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter> handler =
new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
inboundHandler, outboundHandler);
EmbeddedChannel channel = new EmbeddedChannel();
channel.Pipeline.AddFirst(handler);
DoOutboundOperations(channel);
Assert.Equal(Event.HANDLER_ADDED, queue.Dequeue());
Assert.Equal(Event.BIND, queue.Dequeue());
Assert.Equal(Event.CONNECT, queue.Dequeue());
Assert.Equal(Event.WRITE, queue.Dequeue());
Assert.Equal(Event.FLUSH, queue.Dequeue());
Assert.Equal(Event.READ, queue.Dequeue());
Assert.Equal(Event.CLOSE, queue.Dequeue());
Assert.Equal(Event.CLOSE, queue.Dequeue());
Assert.Equal(Event.DEREGISTER, queue.Dequeue());
handler.RemoveOutboundHandler();
Assert.Equal(Event.HANDLER_REMOVED, queue.Dequeue());
// These should not be handled by the inboundHandler anymore as it was removed before
DoOutboundOperations(channel);
// Should have not received any more events as it was removed before via removeInboundHandler()
Assert.Empty(queue);
Assert.True(channel.Finish());
Assert.Empty(queue);
}
private static void DoOutboundOperations(IChannel channel)
{
channel.Pipeline.BindAsync(ADDRESS);
channel.Pipeline.ConnectAsync(ADDRESS);
channel.Pipeline.WriteAsync(MSG);
channel.Pipeline.Flush();
channel.Pipeline.Read();
channel.Pipeline.DisconnectAsync();
channel.Pipeline.CloseAsync();
channel.Pipeline.DeregisterAsync();
}
class ChannelOutboundHandlerAdapter2 : ChannelHandlerAdapter
{
private readonly Queue<Event> _queue;
public ChannelOutboundHandlerAdapter2(Queue<Event> queue) => _queue = queue;
public override void HandlerAdded(IChannelHandlerContext context)
{
_queue.Enqueue(Event.HANDLER_ADDED);
}
public override void HandlerRemoved(IChannelHandlerContext context)
{
_queue.Enqueue(Event.HANDLER_REMOVED);
}
public override Task BindAsync(IChannelHandlerContext context, EndPoint localAddress)
{
_queue.Enqueue(Event.BIND);
return TaskUtil.Completed;
}
public override Task ConnectAsync(IChannelHandlerContext context, EndPoint remoteAddress, EndPoint localAddress)
{
_queue.Enqueue(Event.CONNECT);
return TaskUtil.Completed;
}
public override void Disconnect(IChannelHandlerContext context, IPromise promise)
{
_queue.Enqueue(Event.DISCONNECT);
}
public override void Close(IChannelHandlerContext context, IPromise promise)
{
_queue.Enqueue(Event.CLOSE);
}
public override void Deregister(IChannelHandlerContext context, IPromise promise)
{
_queue.Enqueue(Event.DEREGISTER);
}
public override void Read(IChannelHandlerContext context)
{
_queue.Enqueue(Event.READ);
}
public override void Write(IChannelHandlerContext context, object message, IPromise promise)
{
_queue.Enqueue(Event.WRITE);
}
public override void Flush(IChannelHandlerContext context)
{
_queue.Enqueue(Event.FLUSH);
}
}
[Fact]
public async Task TestPromisesPassed()
{
var outboundHandler = new ChannelOutboundHandlerAdapter3();
EmbeddedChannel ch = new EmbeddedChannel(outboundHandler,
new CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>(
new ChannelHandlerAdapter(), new ChannelHandlerAdapter()));
IChannelPipeline pipeline = ch.Pipeline;
IPromise promise = null;
await pipeline.ConnectAsync(ADDRESS);
await pipeline.BindAsync(ADDRESS);
promise = ch.NewPromise();
pipeline.CloseAsync(promise).Ignore();
await promise.Task;
promise = ch.NewPromise();
pipeline.DisconnectAsync(promise).Ignore();
await promise.Task;
promise = ch.NewPromise();
pipeline.WriteAsync("test", promise).Ignore();
await promise.Task;
promise = ch.NewPromise();
pipeline.DeregisterAsync(promise).Ignore();
await promise.Task;
ch.Finish();
}
class ChannelOutboundHandlerAdapter3 : ChannelHandlerAdapter
{
public override Task BindAsync(IChannelHandlerContext context, EndPoint localAddress)
{
return TaskUtil.Completed;
}
public override Task ConnectAsync(IChannelHandlerContext context, EndPoint remoteAddress, EndPoint localAddress)
{
return TaskUtil.Completed;
}
public override void Disconnect(IChannelHandlerContext context, IPromise promise)
{
promise.Complete();
}
public override void Close(IChannelHandlerContext context, IPromise promise)
{
promise.Complete();
}
public override void Deregister(IChannelHandlerContext context, IPromise promise)
{
promise.Complete();
}
public override void Write(IChannelHandlerContext context, object message, IPromise promise)
{
promise.Complete();
}
}
[Fact]
public void TestNotSharable()
{
Assert.Throws<InvalidOperationException>(() => new CombinedChannelDuplexHandler0());
}
class CombinedChannelDuplexHandler0 : CombinedChannelDuplexHandler<ChannelHandlerAdapter, ChannelHandlerAdapter>
{
public override bool IsSharable => true;
}
}
} | 37.652466 | 124 | 0.607039 | [
"MIT"
] | cuteant/SpanNetty | test/DotNetty.Transport.Tests/Channel/CombinedChannelDuplexHandlerTest.cs | 16,795 | C# |
using Game.IO;
namespace Game.Items.Weapons
{
class Club : Weapon
{
public Club()
{
Name = TextResources.GetStringByResourceName("club");
Damage = 13;
}
}
}
| 15.642857 | 65 | 0.515982 | [
"MIT"
] | Rinkton/console_game-forest_demon | NewRpgGame/Game/Items/Weapons/Club.cs | 221 | C# |
using System;
using System.Collections.Generic;
using System.IO;
namespace Consolus
{
public enum ConsoleStyleKind
{
Color,
Format,
Reset,
}
public readonly struct ConsoleStyle : IEquatable<ConsoleStyle>
{
/// https://en.wikipedia.org/wiki/ANSI_escape_code
public static readonly ConsoleStyle Black = new ConsoleStyle("\u001b[30m");
public static readonly ConsoleStyle Red = new ConsoleStyle("\u001b[31m");
public static readonly ConsoleStyle Green = new ConsoleStyle("\u001b[32m");
public static readonly ConsoleStyle Yellow = new ConsoleStyle("\u001b[33m");
public static readonly ConsoleStyle Blue = new ConsoleStyle("\u001b[34m");
public static readonly ConsoleStyle Magenta = new ConsoleStyle("\u001b[35m");
public static readonly ConsoleStyle Cyan = new ConsoleStyle("\u001b[36m");
public static readonly ConsoleStyle White = new ConsoleStyle("\u001b[37m");
public static readonly ConsoleStyle BrightBlack = new ConsoleStyle("\u001b[30;1m");
public static readonly ConsoleStyle BrightRed = new ConsoleStyle("\u001b[31;1m");
public static readonly ConsoleStyle BrightGreen = new ConsoleStyle("\u001b[32;1m");
public static readonly ConsoleStyle BrightYellow = new ConsoleStyle("\u001b[33;1m");
public static readonly ConsoleStyle BrightBlue = new ConsoleStyle("\u001b[34;1m");
public static readonly ConsoleStyle BrightMagenta = new ConsoleStyle("\u001b[35;1m");
public static readonly ConsoleStyle BrightCyan = new ConsoleStyle("\u001b[36;1m");
public static readonly ConsoleStyle BrightWhite = new ConsoleStyle("\u001b[37;1m");
public static readonly ConsoleStyle BackgroundBlack = new ConsoleStyle("\u001b[40m");
public static readonly ConsoleStyle BackgroundRed = new ConsoleStyle("\u001b[41m");
public static readonly ConsoleStyle BackgroundGreen = new ConsoleStyle("\u001b[42m");
public static readonly ConsoleStyle BackgroundYellow = new ConsoleStyle("\u001b[43m");
public static readonly ConsoleStyle BackgroundBlue = new ConsoleStyle("\u001b[44m");
public static readonly ConsoleStyle BackgroundMagenta = new ConsoleStyle("\u001b[45m");
public static readonly ConsoleStyle BackgroundCyan = new ConsoleStyle("\u001b[46m");
public static readonly ConsoleStyle BackgroundWhite = new ConsoleStyle("\u001b[47m");
public static readonly ConsoleStyle BackgroundBrightBlack = new ConsoleStyle("\u001b[40;1m");
public static readonly ConsoleStyle BackgroundBrightRed = new ConsoleStyle("\u001b[41;1m");
public static readonly ConsoleStyle BackgroundBrightGreen = new ConsoleStyle("\u001b[42;1m");
public static readonly ConsoleStyle BackgroundBrightYellow = new ConsoleStyle("\u001b[43;1m");
public static readonly ConsoleStyle BackgroundBrightBlue = new ConsoleStyle("\u001b[44;1m");
public static readonly ConsoleStyle BackgroundBrightMagenta = new ConsoleStyle("\u001b[45;1m");
public static readonly ConsoleStyle BackgroundBrightCyan = new ConsoleStyle("\u001b[46;1m");
public static readonly ConsoleStyle BackgroundBrightWhite = new ConsoleStyle("\u001b[47;1m");
public static readonly ConsoleStyle Bold = new ConsoleStyle("\u001b[1m", ConsoleStyleKind.Format);
public static readonly ConsoleStyle Underline = new ConsoleStyle("\u001b[4m", ConsoleStyleKind.Format);
public static readonly ConsoleStyle Reversed = new ConsoleStyle("\u001b[7m", ConsoleStyleKind.Format);
public static readonly ConsoleStyle Reset = new ConsoleStyle("\u001b[0m", ConsoleStyleKind.Reset);
private static readonly Dictionary<string, ConsoleStyle> MapKnownEscapeToConsoleStyle = new Dictionary<string, ConsoleStyle>(StringComparer.OrdinalIgnoreCase);
static ConsoleStyle()
{
MapKnownEscapeToConsoleStyle.Add(Black.EscapeSequence, Black);
MapKnownEscapeToConsoleStyle.Add(Red.EscapeSequence, Red);
MapKnownEscapeToConsoleStyle.Add(Green.EscapeSequence, Green);
MapKnownEscapeToConsoleStyle.Add(Yellow.EscapeSequence, Yellow);
MapKnownEscapeToConsoleStyle.Add(Blue.EscapeSequence, Blue);
MapKnownEscapeToConsoleStyle.Add(Magenta.EscapeSequence, Magenta);
MapKnownEscapeToConsoleStyle.Add(Cyan.EscapeSequence, Cyan);
MapKnownEscapeToConsoleStyle.Add(White.EscapeSequence, White);
MapKnownEscapeToConsoleStyle.Add(BrightBlack.EscapeSequence, BrightBlack);
MapKnownEscapeToConsoleStyle.Add(BrightRed.EscapeSequence, BrightRed);
MapKnownEscapeToConsoleStyle.Add(BrightGreen.EscapeSequence, BrightGreen);
MapKnownEscapeToConsoleStyle.Add(BrightYellow.EscapeSequence, BrightYellow);
MapKnownEscapeToConsoleStyle.Add(BrightBlue.EscapeSequence, BrightBlue);
MapKnownEscapeToConsoleStyle.Add(BrightMagenta.EscapeSequence, BrightMagenta);
MapKnownEscapeToConsoleStyle.Add(BrightCyan.EscapeSequence, BrightCyan);
MapKnownEscapeToConsoleStyle.Add(BrightWhite.EscapeSequence, BrightWhite);
MapKnownEscapeToConsoleStyle.Add(BackgroundBlack.EscapeSequence, BackgroundBlack);
MapKnownEscapeToConsoleStyle.Add(BackgroundRed.EscapeSequence, BackgroundRed);
MapKnownEscapeToConsoleStyle.Add(BackgroundGreen.EscapeSequence, BackgroundGreen);
MapKnownEscapeToConsoleStyle.Add(BackgroundYellow.EscapeSequence, BackgroundYellow);
MapKnownEscapeToConsoleStyle.Add(BackgroundBlue.EscapeSequence, BackgroundBlue);
MapKnownEscapeToConsoleStyle.Add(BackgroundMagenta.EscapeSequence, BackgroundMagenta);
MapKnownEscapeToConsoleStyle.Add(BackgroundCyan.EscapeSequence, BackgroundCyan);
MapKnownEscapeToConsoleStyle.Add(BackgroundWhite.EscapeSequence, BackgroundWhite);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightBlack.EscapeSequence, BackgroundBrightBlack);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightRed.EscapeSequence, BackgroundBrightRed);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightGreen.EscapeSequence, BackgroundBrightGreen);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightYellow.EscapeSequence, BackgroundBrightYellow);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightBlue.EscapeSequence, BackgroundBrightBlue);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightMagenta.EscapeSequence, BackgroundBrightMagenta);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightCyan.EscapeSequence, BackgroundBrightCyan);
MapKnownEscapeToConsoleStyle.Add(BackgroundBrightWhite.EscapeSequence, BackgroundBrightWhite);
MapKnownEscapeToConsoleStyle.Add(Bold.EscapeSequence, Bold);
MapKnownEscapeToConsoleStyle.Add(Underline.EscapeSequence, Underline);
MapKnownEscapeToConsoleStyle.Add(Reversed.EscapeSequence, Reversed);
MapKnownEscapeToConsoleStyle.Add(Reset.EscapeSequence, Reset);
}
public ConsoleStyle(string escapeSequence) : this()
{
EscapeSequence = escapeSequence;
Kind = ConsoleStyleKind.Color;
}
public ConsoleStyle(string escapeSequence, ConsoleStyleKind kind) : this()
{
EscapeSequence = escapeSequence;
Kind = kind;
}
private ConsoleStyle(string escapeSequence, ConsoleStyleKind kind, bool isInline)
{
EscapeSequence = escapeSequence;
Kind = kind;
IsInline = isInline;
}
public static ConsoleStyle Inline(string escape, ConsoleStyleKind kind = ConsoleStyleKind.Color)
{
if (escape == null) throw new ArgumentNullException(nameof(escape));
if (kind == ConsoleStyleKind.Color)
{
if (MapKnownEscapeToConsoleStyle.TryGetValue(escape, out var style))
{
kind = style.Kind;
}
}
return new ConsoleStyle(escape, kind, true);
}
public static ConsoleStyle Rgb(int r, int g, int b)
{
return new ConsoleStyle($"\x1b[38;2;{r};{g};{b}m", ConsoleStyleKind.Color);
}
public static ConsoleStyle BackgroundRgb(int r, int g, int b)
{
return new ConsoleStyle($"\x1b[48;2;{r};{g};{b}m", ConsoleStyleKind.Color);
}
public readonly string EscapeSequence;
public readonly ConsoleStyleKind Kind;
public readonly bool IsInline;
public void Render(TextWriter writer)
{
writer.Write(EscapeSequence);
}
#if NETSTANDARD2_0
public static implicit operator ConsoleStyle(ConsoleColor color)
{
switch (color)
{
case ConsoleColor.Black:
return Black;
case ConsoleColor.Blue:
return BrightBlue;
case ConsoleColor.Cyan:
return BrightCyan;
case ConsoleColor.DarkBlue:
return Blue;
case ConsoleColor.DarkCyan:
return Cyan;
case ConsoleColor.DarkGray:
return BrightBlack;
case ConsoleColor.DarkGreen:
return Green;
case ConsoleColor.DarkMagenta:
return Magenta;
case ConsoleColor.DarkRed:
return Red;
case ConsoleColor.DarkYellow:
return Yellow;
case ConsoleColor.Gray:
return BrightBlack;
case ConsoleColor.Green:
return BrightGreen;
case ConsoleColor.Magenta:
return BrightMagenta;
case ConsoleColor.Red:
return BrightRed;
case ConsoleColor.White:
return BrightWhite;
case ConsoleColor.Yellow:
return BrightYellow;
default:
throw new ArgumentOutOfRangeException(nameof(color), color, null);
}
}
#endif
public bool Equals(ConsoleStyle other)
{
return EscapeSequence == other.EscapeSequence && Kind == other.Kind && IsInline == other.IsInline;
}
public override bool Equals(object obj)
{
return obj is ConsoleStyle other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return ((((EscapeSequence?.GetHashCode() ?? 0) * 397) ^ (int) Kind) * 397) & IsInline.GetHashCode();
}
}
public static bool operator ==(ConsoleStyle left, ConsoleStyle right)
{
return left.Equals(right);
}
public static bool operator !=(ConsoleStyle left, ConsoleStyle right)
{
return !left.Equals(right);
}
public override string ToString()
{
return EscapeSequence;
}
}
} | 49.583333 | 167 | 0.665635 | [
"BSD-2-Clause"
] | thild/kalk | src/Consolus/ConsoleStyle.cs | 11,307 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UGUIModel : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 14.235294 | 40 | 0.698347 | [
"MIT"
] | Aver58/ColaFrameWork | Assets/Scripts/UIBase/UGUIModel.cs | 244 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Microsoft.Web.WebView2.Core;
using Windows.ApplicationModel.DataTransfer;
using muxc = Microsoft.UI.Xaml.Controls;
using Windows.System;
using Windows.UI.Core;
// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板
namespace edgium
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class BrowserTab : Page
{
public BrowserTab()
{
this.InitializeComponent();
MyWebView.NavigationStarting += onNavigationStarting;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//将传过来的数据 类型转换一下
navigate((string)e.Parameter);
}
private void navigate(string url)
{
try
{
MyWebView.Source = new Uri(url);
}
catch (FormatException ex)
{
// Incorrect address entered.
}
}
private void go()
{
navigate(addressBar.Text);
}
private void back()//后退
{
MyWebView.GoBack();
}
private void back_click(object sender, RoutedEventArgs e)//后退按钮事件处理
{
back();
}
private void forward()//前进
{
MyWebView.GoForward();
}
private void forward_click(object sender, RoutedEventArgs e)//前进按钮事件处理
{
forward();
}
private void refresh()//刷新
{
MyWebView.Reload();
}
private void refresh_click(object sender, RoutedEventArgs e)//刷新按钮事件处理
{
refresh();
}
private void newtab(object sender, RoutedEventArgs e)//新建标签页
{
}
private void newwindow(object sender, RoutedEventArgs e)//新建窗口
{
}
private void onNavigationStarting(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
//网址跳转时修改地址栏
{
String uri = args.Uri;
addressBar.Text = uri;
}
private void IndexPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
//分享一个链接
string shareLinkString = addressBar.Text;
//创建一个数据包
DataPackage dataPackage = new DataPackage();
//把要分享的链接放到数据包里
dataPackage.SetWebLink(new Uri(shareLinkString));
//数据包的标题(内容和标题必须提供)
dataPackage.Properties.Title = "Title";
//数据包的描述
dataPackage.Properties.Description = "Description";
//给dataRequest对象赋值
DataRequest request = args.Request;
request.Data = dataPackage;
}
private void share(object sender, RoutedEventArgs e)//分享
{
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += IndexPage_DataRequested;
//展示系统的共享ui
DataTransferManager.ShowShareUI();
}
private void print()//打印
{
MyWebView.ExecuteScriptAsync($"window.print()");
}
private void print_click(object sender, RoutedEventArgs e)//打印
{
print();
}
private static bool IsCtrlKeyPressed()
{
var ctrlState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control);
return (ctrlState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down;
}
private static bool IsAltKeyPressed()
{
var altState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Menu);
return (altState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down;
}
private void Grid_KeyDown(object sender, KeyRoutedEventArgs e)//处理快捷键
{
if (IsCtrlKeyPressed())
{
switch (e.Key)
{
case VirtualKey.P: print(); break;
case VirtualKey.R: refresh(); break;
}
}
if(IsAltKeyPressed())
{
switch(e.Key)
{
case VirtualKey.Left: back(); break;
case VirtualKey.Right: forward(); break;
}
}
}
private void addressBar_KeyDown(object sender, KeyRoutedEventArgs e)
{
switch (e.Key)
{
case VirtualKey.Enter:go();break;
}
}
}
}
| 31.72561 | 105 | 0.547953 | [
"MIT"
] | oxygen-dioxide/edgium | edgium/BrowserTab.xaml.cs | 5,529 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Sql;
namespace Azure.ResourceManager.Sql.Models
{
/// <summary> Creates or updates the database's vulnerability assessment. </summary>
public partial class ServerDatabaseVulnerabilityAssessmentCreateOrUpdateOperation : Operation<ServerDatabaseVulnerabilityAssessment>
{
private readonly OperationOrResponseInternals<ServerDatabaseVulnerabilityAssessment> _operation;
/// <summary> Initializes a new instance of ServerDatabaseVulnerabilityAssessmentCreateOrUpdateOperation for mocking. </summary>
protected ServerDatabaseVulnerabilityAssessmentCreateOrUpdateOperation()
{
}
internal ServerDatabaseVulnerabilityAssessmentCreateOrUpdateOperation(ArmClient armClient, Response<DatabaseVulnerabilityAssessmentData> response)
{
_operation = new OperationOrResponseInternals<ServerDatabaseVulnerabilityAssessment>(Response.FromValue(new ServerDatabaseVulnerabilityAssessment(armClient, response.Value), response.GetRawResponse()));
}
/// <inheritdoc />
public override string Id => _operation.Id;
/// <inheritdoc />
public override ServerDatabaseVulnerabilityAssessment Value => _operation.Value;
/// <inheritdoc />
public override bool HasCompleted => _operation.HasCompleted;
/// <inheritdoc />
public override bool HasValue => _operation.HasValue;
/// <inheritdoc />
public override Response GetRawResponse() => _operation.GetRawResponse();
/// <inheritdoc />
public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response<ServerDatabaseVulnerabilityAssessment>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response<ServerDatabaseVulnerabilityAssessment>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken);
}
}
| 44.196721 | 252 | 0.758531 | [
"MIT"
] | danielortega-msft/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/LongRunningOperation/ServerDatabaseVulnerabilityAssessmentCreateOrUpdateOperation.cs | 2,696 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Market;
using Market.Controllers;
namespace Market.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.036364 | 90 | 0.568272 | [
"MIT"
] | AyudanteDeSanta/Market | Market/Market.Tests/Controllers/HomeControllerTest.cs | 1,269 | C# |
using SC2APIProtocol;
using SC2Sharp.Agents;
using SC2Sharp.Managers;
using SC2Sharp.Util;
namespace SC2Sharp.Micro
{
public class StalkerAttackNaturalController : CustomController
{
private Unit Bunker = null;
private Point2D EnemyNatural;
private int UpdateFrame = 0;
public override bool DetermineAction(Agent agent, Point2D target)
{
if (agent.Unit.UnitType != UnitTypes.STALKER)
return false;
if (agent.Unit.WeaponCooldown == 0)
return false;
Unit bunker = GetNaturalBunker();
if (bunker == null)
return false;
PotentialHelper potential = new PotentialHelper(EnemyNatural, 8);
potential.From(bunker.Pos);
Point2D attackTarget = potential.Get();
Point2D minePos = null;
float dist = 10 * 10;
foreach (UnitLocation mine in Bot.Main.EnemyMineManager.Mines)
{
float newDist = agent.DistanceSq(mine.Pos);
if (newDist < dist)
{
dist = newDist;
minePos = SC2Util.To2D(mine.Pos);
}
}
potential = new PotentialHelper(agent.Unit.Pos, 4);
potential.To(attackTarget, 2);
if (minePos != null)
potential.To(minePos, 1);
agent.Order(Abilities.MOVE, potential.Get());
return true;
}
private Unit GetNaturalBunker()
{
if (UpdateFrame == Bot.Main.Frame)
return Bunker;
UpdateFrame = Bot.Main.Frame;
Bunker = null;
if (EnemyNatural == null)
EnemyNatural = Bot.Main.MapAnalyzer.GetEnemyNatural().Pos;
if (EnemyNatural == null)
return null;
Unit bunker = null;
Unit cc = null;
foreach (Unit enemy in Bot.Main.Enemies())
{
if (enemy.UnitType == UnitTypes.BUNKER && enemy.BuildProgress >= 0.99)
{
if (SC2Util.DistanceSq(enemy.Pos, EnemyNatural) <= 15 * 15)
bunker = enemy;
}
else if (enemy.UnitType == UnitTypes.COMMAND_CENTER || enemy.UnitType == UnitTypes.ORBITAL_COMMAND)
{
if (SC2Util.DistanceSq(enemy.Pos, EnemyNatural) <= 15 * 15)
cc = enemy;
}
}
if (cc == null)
return null;
Bunker = bunker;
return bunker;
}
}
}
| 31.964286 | 115 | 0.503166 | [
"MIT"
] | SimonPrins/TyrSc2 | Tyr/Micro/StalkerAttackNaturalController.cs | 2,687 | C# |
using System;
namespace AdvantureWork.Common.Request
{
public class UserDeleteRequest
{
public Guid Id { get; set; }
}
} | 15.777778 | 38 | 0.647887 | [
"Apache-2.0"
] | thanhntggsunday/AdvantureWork2017 | AdvantureWork.Common/Request/UserDeleteRequest.cs | 144 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Funq;
using ServiceStack;
using CoreLayerADC.CipherMetricsExporter.ServiceInterface;
using ServiceStack.Logging;
using Prometheus;
using ServiceStack.Api.OpenApi;
namespace CoreLayerADC.CipherMetricsExporter
{
public class Startup : ModularStartup
{
// 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 new void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMetricServer();
app.UseServiceStack(new AppHost
{
AppSettings = new NetCoreAppSettings(Configuration)
});
}
}
public class AppHost : AppHostBase
{
public AppHost() : base("CoreLayerADC.CipherMetricsExporter", typeof(CipherMetricsServices).Assembly) { }
// Configure your AppHost with the necessary configuration and dependencies your App needs
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
DefaultRedirectPath = "/swagger-ui",
DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false),
EnableFeatures = Feature.Json | Feature.Metadata
});
LogManager.LogFactory = new ConsoleLogFactory();
Plugins.Add(new OpenApiFeature());
Plugins.Add(new RequestLogsFeature(100)
{
RequiredRoles = null
});
}
}
}
| 33.83871 | 122 | 0.642993 | [
"Apache-2.0"
] | CoreLayer/CoreLayerADC.CipherMetricsExporter | CoreLayerADC.CipherMetricsExporter/CoreLayerADC.CipherMetricsExporter/Startup.cs | 2,098 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SSTDeskBooks.english.atrium.content_manager {
public partial class SAMPageSelector {
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// pgContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal pgContent;
}
}
| 32.676471 | 84 | 0.50045 | [
"MIT"
] | chris-weekes/atrium | lmras/DeskbookSAM/english/atrium/content_manager/SAMPageSelector.aspx.designer.cs | 1,113 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json.Serialization;
namespace EasyModular.Utils
{
/// <summary>
/// 查询结果模型
/// </summary>
/// <typeparam name="T"></typeparam>
public class QueryResultModel<T>
{
/// <summary>
/// 总数
/// </summary>
public int Total { get; set; }
/// <summary>
/// 数据集
/// </summary>
public IList<T> Rows { get; set; }
/// <summary>
/// 其他数据
/// </summary>
[JsonIgnore]
public object Data { get; set; }
}
}
| 19.677419 | 42 | 0.504918 | [
"MIT"
] | doordie1991/EasyModular | src/EasyModular.Utils/Result/QueryResultModel.cs | 642 | C# |
using System;
namespace Jira.WallboardScreensaver.EditPreferences {
public interface IEditPreferencesView {
string JiraUrl { get; set; }
IDashboardDisplayItem[] DashboardItems { get; set; }
IDashboardDisplayItem SelectedDashboardItem { get; set; }
bool DisplayHasCredentials { get; set; }
event EventHandler SelectedDashboardItemChanged;
event EventHandler JiraLoginButtonClicked;
event EventHandler LoadDashboardsButtonClicked;
event EventHandler SaveButtonClicked;
event EventHandler CancelButtonClicked;
IJiraLoginView CreateJiraLoginView();
void ShowJiraLoginView(IJiraLoginView view);
void Close();
}
public interface IDashboardDisplayItem {
string ToString();
}
} | 33.083333 | 65 | 0.707809 | [
"MIT"
] | jonscheiding/jira-wallboard-screensaver | Jira.WallboardScreensaver/EditPreferences/IEditPreferencesView.cs | 796 | C# |
using System;
namespace RogueSharp.DiceNotation.Exceptions
{
/// <summary>
/// Exception that is thrown when a dice term is constructed with a negative number of dice.
/// </summary>
public class InvalidMultiplicityException : Exception
{
/// <summary>
/// Initializes a new instance of the InvalidMultiplicityException class.
/// </summary>
public InvalidMultiplicityException()
{
}
/// <summary>
/// Initializes a new instance of the InvalidMultiplicityException class with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public InvalidMultiplicityException( string message )
: base( message )
{
}
/// <summary>
/// Initializes a new instance of the InvalidMultiplicityException class with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception. If the innerException parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param>
public InvalidMultiplicityException( string message, Exception innerException )
: base( message, innerException )
{
}
}
} | 44.647059 | 244 | 0.688406 | [
"MIT"
] | hybrid1969/RogueSharp | RogueSharp/DiceNotation/Exceptions/InvalidMultiplicityException.cs | 1,518 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ThreeSum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ThreeSum")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ecefc6b9-a8a4-426d-822b-0c04947b248a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.405405 | 84 | 0.746387 | [
"MIT"
] | domEnriquez/Algorithms | ThreeSum/ThreeSum/Properties/AssemblyInfo.cs | 1,387 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
public interface IGetInfluencersResponse : IResponse
{
[JsonProperty("count")]
long Count { get; }
[JsonProperty("influencers")]
IReadOnlyCollection<BucketInfluencer> Influencers { get; }
}
public class GetInfluencersResponse : ResponseBase, IGetInfluencersResponse
{
public long Count { get; internal set; }
public IReadOnlyCollection<BucketInfluencer> Influencers { get; internal set; } = EmptyReadOnly<BucketInfluencer>.Collection;
}
}
| 24.363636 | 127 | 0.766791 | [
"Apache-2.0"
] | Henr1k80/elasticsearch-net | src/Nest/XPack/MachineLearning/GetInfluencers/GetInfluencersResponse.cs | 538 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.Devices
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum MediaCapturePauseBehavior
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
RetainHardwareResources,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ReleaseHardwareResources,
#endif
}
#endif
}
| 27.65 | 62 | 0.721519 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Devices/MediaCapturePauseBehavior.cs | 553 | C# |
/*
* Copyright 2013 Splunk, 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.
*/
namespace Splunk.Examples.Search
{
using System;
using System.Threading;
using Splunk;
using SplunkSDKHelper;
/// <summary>
/// An example program to perform a normal search.
/// </summary>
public class Program
{
/// <summary>
/// The main program
/// </summary>
/// <param name="argv">The command line arguments</param>
public static void Main(string[] argv)
{
// Load connection info for Splunk server in .splunkrc file.
var cli = Command.Splunk("search");
cli.AddRule("search", typeof(string), "search string");
cli.Parse(argv);
if (!cli.Opts.ContainsKey("search"))
{
System.Console.WriteLine("Search query string required, use --search=\"query\"");
Environment.Exit(1);
}
var service = Service.Connect(cli.Opts);
var jobs = service.GetJobs();
var job = jobs.Create((string)cli.Opts["search"]);
while (!job.IsDone)
{
Thread.Sleep(1000);
}
var outArgs = new JobResultsArgs
{
OutputMode = JobResultsArgs.OutputModeEnum.Xml,
// Return all entries.
Count = 0
};
using (var stream = job.Results(outArgs))
{
using (var rr = new ResultsReaderXml(stream))
{
foreach (var @event in rr)
{
System.Console.WriteLine("EVENT:");
foreach (string key in @event.Keys)
{
System.Console.WriteLine(" " + key + " -> " + @event[key]);
}
}
}
}
}
}
}
| 32.897436 | 98 | 0.507794 | [
"Apache-2.0"
] | splunk/splunk-sdk-csharp | examples/search/Program.cs | 2,568 | C# |
using System.ComponentModel.DataAnnotations;
using Boilerplate.Common.Data;
namespace Boilerplate.MongoDB.Sample.Models;
public class Customer : IEntity<string>
{
[Key]
[Required]
public string Id { get; set; }
[Required]
public string Name { get; set; }
}
| 18.666667 | 44 | 0.707143 | [
"MIT"
] | mkozhevnikov/boilerplate | samples/MongoDB.Sample/Models/Customer.cs | 280 | C# |
using System;
using EZNEW.ValueType;
using EZNEW.Develop.Domain.Aggregation;
using EZNEW.Domain.Sys.Repository;
using EZNEW.Develop.CQuery;
using EZNEW.Entity.Sys;
using EZNEW.Module.Sys;
using EZNEW.Domain.Sys.Service;
using EZNEW.DependencyInjection;
namespace EZNEW.Domain.Sys.Model
{
/// <summary>
/// 授权操作
/// </summary>
public class Operation : AggregationRoot<Operation>
{
/// <summary>
/// 操作分组服务
/// </summary>
static readonly IOperationGroupService operationGroupService = ContainerManager.Resolve<IOperationGroupService>();
#region 字段
/// <summary>
/// 操作分组
/// </summary>
protected LazyMember<OperationGroup> group;
#endregion
#region 构造方法
/// <summary>
/// 实例化授权操作对象
/// </summary>
private Operation()
{
group = new LazyMember<OperationGroup>(LoadOperationGroup);
repository = this.Instance<IOperationRepository>();
}
#endregion
#region 属性
/// <summary>
/// 主键编号
/// </summary>
public long Id { get; set; }
/// <summary>
/// 控制器
/// </summary>
public string ControllerCode { get; set; }
/// <summary>
/// 操作方法
/// </summary>
public string ActionCode { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 状态
/// </summary>
public OperationStatus Status { get; set; }
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 操作分组
/// </summary>
public OperationGroup Group
{
get
{
return group.Value;
}
protected set
{
group.SetValue(value, false);
}
}
/// <summary>
/// 访问级别
/// </summary>
public OperationAccessLevel AccessLevel { get; set; }
/// <summary>
/// 方法描述
/// </summary>
public string Remark { get; set; }
#endregion
#region 内部方法
#region 加载操作对应的分组
/// <summary>
/// 加载操作对应的分组
/// </summary>
/// <returns></returns>
OperationGroup LoadOperationGroup()
{
if (AllowLoad(o => o.Group, group))
{
return operationGroupService.Get(group.CurrentValue.Id);
}
return group.CurrentValue;
}
#endregion
#region 保存数据验证
/// <summary>
/// 保存数据验证
/// </summary>
/// <returns></returns>
protected override bool SaveValidation()
{
bool valResult = base.SaveValidation();
if (!valResult)
{
return valResult;
}
if (group.CurrentValue?.IdentityValueIsNone() ?? true)
{
throw new Exception($"请设置操作功能:{Name} 的分组");
}
if (!operationGroupService.Exist(group.CurrentValue.Id))
{
throw new Exception("操作功能设置的分组: {group.CurrentValue.Id} 不存在");
}
ActionCode = ActionCode?.ToUpper() ?? string.Empty;
ControllerCode = ControllerCode?.ToUpper() ?? string.Empty;
return true;
}
#endregion
#region 获取对象的标识值
/// <summary>
/// 获取对象的标识值
/// </summary>
/// <returns>返回对象的标识值</returns>
protected override string GetIdentityValue()
{
return Id.ToString();
}
#endregion
#region 更新对象值
/// <summary>
/// 更新对象值
/// </summary>
/// <param name="newData">新的数据对象</param>
/// <returns>返回更新后的对象</returns>
protected override Operation OnUpdating(Operation newData)
{
if (newData != null)
{
SetGroup(newData.Group);
Name = newData.Name;
ControllerCode = newData.ControllerCode;
ActionCode = newData.ActionCode;
Status = newData.Status;
Remark = newData.Remark;
AccessLevel = newData.AccessLevel;
}
return this;
}
#endregion
#endregion
#region 静态方法
#region 生成一个操作编号
/// <summary>
/// 生成一个操作编号
/// </summary>
/// <returns>返回一个操作编号</returns>
public static long GenerateOperationId()
{
return SysManager.GetId(SysModuleObject.Operation);
}
#endregion
#region 创建授权操作
/// <summary>
/// 创建一个授权操作对象
/// </summary>
/// <param name="id">编号</param>
/// <param name="name">名称</param>
/// <param name="controllerCode">控制编码</param>
/// <param name="actionCode">方法编码</param>
/// <returns>返回一个新的操作对象</returns>
public static Operation Create(long id = 0, string name = "", string controllerCode = "", string actionCode = "")
{
id = id < 1 ? GenerateOperationId() : id;
return new Operation()
{
Id = id,
Name = name,
ControllerCode = controllerCode,
ActionCode = actionCode
};
}
#endregion
#endregion
#region 功能方法
#region 验证对象标识是否为空
/// <summary>
/// 验证对象标识是否为空
/// </summary>
/// <returns>返回对象标识是否为空</returns>
public override bool IdentityValueIsNone()
{
return Id < 1;
}
#endregion
#region 设置操作分组
/// <summary>
/// 设置操作分组
/// </summary>
/// <param name="group">分组信息</param>
/// <param name="init">是否初始化</param>
public void SetGroup(OperationGroup group, bool init = true)
{
this.group.SetValue(group, init);
}
#endregion
#region 初始化标识信息
/// <summary>
/// 初始化标识信息
/// </summary>
public override void InitIdentityValue()
{
base.InitIdentityValue();
Id = GenerateOperationId();
}
#endregion
#endregion
}
} | 23.436364 | 122 | 0.483476 | [
"MIT"
] | eznew-net/Demo | Modules/Sys/Business/Domain/EZNEW.Domain.Sys/Model/Operation.cs | 7,043 | C# |
namespace AstArangoDbConnector.Syntax
{
public sealed class SyntaxDotInterfaceDeclarationSyntax : BaseSyntaxCollection
{
}
} | 23.5 | 83 | 0.758865 | [
"MIT"
] | arise-project/iso3 | AstGraphDbConnector/AstArangoDbConnector/SyntaxCollections/SyntaxDotInterfaceDeclarationSyntax.cs | 141 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.CodeDom.Tests
{
public class CodeIterationStatementTests : CodeStatementTestBase<CodeIterationStatement>
{
[Fact]
public void Ctor_Default()
{
var iteration = new CodeIterationStatement();
Assert.Null(iteration.InitStatement);
Assert.Null(iteration.TestExpression);
Assert.Null(iteration.IncrementStatement);
Assert.Empty(iteration.Statements);
}
public static IEnumerable<object[]> Ctor_TestData()
{
yield return new object[] { null, null, null, new CodeStatement[0] };
yield return new object[] { new CodeCommentStatement("1"), new CodePrimitiveExpression("2"), new CodeCommentStatement("3"), new CodeStatement[] { new CodeCommentStatement("4") } };
}
[Theory]
[MemberData(nameof(Ctor_TestData))]
public void Ctor(CodeStatement initStatement, CodeExpression testExpression, CodeStatement incrementStatement, CodeStatement[] statements)
{
var iteration = new CodeIterationStatement(initStatement, testExpression, incrementStatement, statements);
Assert.Equal(initStatement, iteration.InitStatement);
Assert.Equal(testExpression, iteration.TestExpression);
Assert.Equal(incrementStatement, iteration.IncrementStatement);
Assert.Equal(statements, iteration.Statements.Cast<CodeStatement>());
}
[Fact]
public void Ctor_NullStatements_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => new CodeIterationStatement(null, null, null, null));
}
[Fact]
public void Ctor_NullObjectInStatements_ThrowsArgumentNullException()
{
CodeStatement[] statements = new CodeStatement[] { null };
AssertExtensions.Throws<ArgumentNullException>("value", () => new CodeIterationStatement(null, null, null, statements));
}
[Theory]
[MemberData(nameof(CodeStatement_TestData))]
public void InitStatement_Set_Get_ReturnsExpected(CodeStatement value)
{
var iteration = new CodeIterationStatement();
iteration.InitStatement = value;
Assert.Equal(value, iteration.InitStatement);
}
[Theory]
[MemberData(nameof(CodeExpression_TestData))]
public void TestExpression_Set_Get_ReturnsExpected(CodeExpression value)
{
var iteration = new CodeIterationStatement();
iteration.TestExpression = value;
Assert.Equal(value, iteration.TestExpression);
}
[Theory]
[MemberData(nameof(CodeStatement_TestData))]
public void IncrementStatement_Set_Get_ReturnsExpected(CodeStatement value)
{
var iteration = new CodeIterationStatement();
iteration.IncrementStatement = value;
Assert.Equal(value, iteration.IncrementStatement);
}
[Fact]
public void Statements_AddMultiple_ReturnsExpected()
{
var iteration = new CodeIterationStatement();
CodeStatement statement1 = new CodeCommentStatement("Value1");
iteration.Statements.Add(statement1);
Assert.Equal(new CodeStatement[] { statement1 }, iteration.Statements.Cast<CodeStatement>());
CodeStatement statement2 = new CodeCommentStatement("Value2");
iteration.Statements.Add(statement2);
Assert.Equal(new CodeStatement[] { statement1, statement2 }, iteration.Statements.Cast<CodeStatement>());
}
}
}
| 40.726316 | 192 | 0.663479 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.CodeDom/tests/System/CodeDom/CodeIterationStatementTests.cs | 3,869 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FoiceAtk : MonoBehaviour
{
[SerializeField]GameObject target;
[SerializeField]GameObject boss;
float speedSet;
bool grounded, hit;
bool controlFlag1 = true;
bool controlFlag2 = true;
int hitCount;
[SerializeField]LayerMask ground,player;
// Use this for initialization
void Start () {
speedSet = 15f;
target = FindObjectOfType<NewPlayer>().gameObject;
boss = FindObjectOfType<Kura>().gameObject;
transform.rotation = Quaternion.Euler(0, 0, CalculateAngle(transform.position,target.transform.position,1));
StartCoroutine(FakeUpdate());
}
IEnumerator FakeUpdate(){
//Debug.Log(hitCount);
speedSet -= 0.2f;
transform.Translate((15 /Mathf.Clamp(speedSet, 0.8f,15)) * Time.deltaTime, 0, 0);
if(grounded)
{
Collider2D col = Physics2D.OverlapCircle(transform.position, 2f, ground);
if (transform.position.y > col.bounds.max.y)
{
if(controlFlag1)
{
controlFlag1 = false;
ColGround();
}
}
else
{
if (controlFlag2)
{
controlFlag2 = false;
ColWall();
}
}
}
if(Vector3.Distance(transform.position, boss.transform.position) < 1f && !controlFlag2)
{
var kurinha = boss.GetComponent<Kura>();
kurinha.GrabFoice();
Destroy(this.gameObject);
}
else if (Vector3.Distance(transform.position, boss.transform.position) >25f)
{
ColWall();
}
grounded = Physics2D.OverlapCircle(transform.position,1.3f,ground);
hit = Physics2D.OverlapCircle(transform.position,1.3f,player);
if(hit)
{
target.GetComponent<PlayerHealth>().TakeDamage(1);
}
yield return new WaitForSeconds(.005f);
StartCoroutine(FakeUpdate());
}
void ColGround()
{
if (!controlFlag1)
{
speedSet = 15;
var alt = Random.Range(0, 45);
if (boss.transform.position.x > transform.position.x)
{
transform.rotation = Quaternion.Euler(0, 0, 180 - alt);
}
else
{
transform.rotation = Quaternion.Euler(0, 0, alt);
}
}
else
{
speedSet = 15;
transform.rotation = Quaternion.Euler(0, 0, CalculateAngle(transform.position, boss.transform.position, 0));
}
}
void ColWall()
{
speedSet = 15;
transform.rotation = Quaternion.Euler(0, 0, CalculateAngle(transform.position,boss.transform.position,0));
}
float CalculateAngle(Vector3 thisPos,Vector3 targetPos, float ajust)
{
var pos1 = thisPos;
var pos2 = targetPos;
var anglezin = Mathf.Atan2(pos2.y - pos1.y + ajust, pos2.x - pos1.x) * 180 / Mathf.PI;
return anglezin;
}
}
| 28.876106 | 120 | 0.538155 | [
"MIT"
] | reegomes/Nekomancer | Assets/Scripts/FoiceAtk.cs | 3,265 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Efs
{
[Serializable]
[EfsFile("/nv/item_files/rfnv/00022634", true, 0xE1FF)]
[Attributes(9)]
public class TdscdmaB34MprBasedPaSwitchpointsShift
{
[ElementsCount(7)]
[ElementType("uint16")]
[Description("")]
public ushort[] Value { get; set; }
}
}
| 22.52381 | 60 | 0.630021 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Efs/TdscdmaB34MprBasedPaSwitchpointsShiftI.cs | 473 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orchard.Environment.Shell.Builders.Models;
namespace Harvest.Two.HelloWorld.Models
{
public class HelloModel
{
public ShellBlueprint Blueprint { get; set; }
public bool Exists { get; set; }
}
}
| 21.8 | 53 | 0.718654 | [
"BSD-3-Clause"
] | Jetski5822/OrchardHarvestFeb2017 | runthough/Harvest.Two/Modules/Harvest.Two.HelloWorld/Models/HelloModel.cs | 329 | C# |
// Copyright 2013 Zynga 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.
using System;
#if PLATFORM_MONOMAC
using MonoMac.OpenGL;
#elif PLATFORM_MONOTOUCH
using OpenTK.Graphics.ES20;
#elif PLATFORM_MONODROID
using OpenTK.Graphics.ES20;
using ErrorCode = OpenTK.Graphics.ES20.All;
#endif
namespace flash.display3D {
public class GLUtils {
public static void CheckGLError()
{
#if PLATFORM_MONOTOUCH || PLATFORM_MONODROID
ErrorCode error = GL.GetError ();
if (error != 0) {
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
throw new InvalidOperationException("Error calling openGL api. Error: " + error + "\n" + trace.ToString());
}
#endif
}
}
}
| 28.409091 | 111 | 0.7184 | [
"Apache-2.0"
] | drewgreenwell/playscript-mono | mcs/class/pscorlib/flash/display3D/GLUtils.cs | 1,250 | C# |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// 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.
#endregion
using System;
using System.Collections;
namespace SQLAzureMWUtils
{
public class TSQLNotSupportedByAzure : IConfigurationData
{
private string _defaultMessage;
private SupportedStatementList _Skip;
private NotSupportedTable _Table;
private NotSupportedIndex _Index;
private NotSupportedViews _Views;
private NotSupportedSchema _Schema;
private NotSupportedSynonym _Synonym;
private NotSupportedList _TSQL;
private NotSupportedList _ActiveDirectorySP;
private NotSupportedList _BackupandRestoreTable;
private NotSupportedList _ChangeDataCapture;
private NotSupportedList _ChangeDataCaptureTable;
private NotSupportedList _DatabaseEngineSP;
private NotSupportedList _DatabaseMailSP;
private NotSupportedList _DatabaseMaintenancePlan;
private NotSupportedList _DataControl;
private NotSupportedList _DistributedQueriesSP;
private NotSupportedList _FullTextSearchSP;
private NotSupportedList _GeneralExtendedSPs;
private NotSupportedList _IntegrationServicesTable;
private NotSupportedList _LogShipping;
private NotSupportedList _MetadataFunction;
private NotSupportedList _OLEAutomationSP;
private NotSupportedList _OLEDBTable;
private NotSupportedList _ProfilerSP;
private NotSupportedList _ReplicationSP;
private NotSupportedList _ReplicationTable;
private NotSupportedList _RowsetFunction;
private NotSupportedList _SecurityFunction;
private NotSupportedList _SecuritySP;
private NotSupportedList _SQLMailSP;
private NotSupportedList _SQLServerAgentSP;
private NotSupportedList _SQLServerAgentTable;
private NotSupportedList _SystemCatalogView;
private NotSupportedList _SystemFunction;
private NotSupportedList _SystemStatisticalFunction;
private NotSupportedList _Unclassified;
public string DefaultMessage
{
get { return _defaultMessage; }
set { _defaultMessage = value; }
}
public NotSupportedSchema Schema
{
get { return _Schema; }
set { _Schema = value; }
}
public NotSupportedSynonym Synonym
{
get { return _Synonym; }
set { _Synonym = value; }
}
public SupportedStatementList Skip
{
get { return _Skip; }
set { _Skip = value; }
}
public NotSupportedTable Table
{
get { return _Table; }
set { _Table = value; }
}
public NotSupportedViews View
{
get { return _Views; }
set { _Views = value; }
}
public NotSupportedIndex Index
{
get { return _Index; }
set { _Index = value; }
}
public NotSupportedList GeneralTSQL
{
get { return _TSQL; }
set { _TSQL = value; }
}
public NotSupportedList ActiveDirectorySP
{
get { return _ActiveDirectorySP; }
set { _ActiveDirectorySP = value; }
}
public NotSupportedList BackupandRestoreTable
{
get { return _BackupandRestoreTable; }
set { _BackupandRestoreTable = value; }
}
public NotSupportedList ChangeDataCapture
{
get { return _ChangeDataCapture; }
set { _ChangeDataCapture = value; }
}
public NotSupportedList ChangeDataCaptureTable
{
get { return _ChangeDataCaptureTable; }
set { _ChangeDataCaptureTable = value; }
}
public NotSupportedList DatabaseEngineSP
{
get { return _DatabaseEngineSP; }
set { _DatabaseEngineSP = value; }
}
public NotSupportedList DatabaseMailSP
{
get { return _DatabaseMailSP; }
set { _DatabaseMailSP = value; }
}
public NotSupportedList DatabaseMaintenancePlan
{
get { return _DatabaseMaintenancePlan; }
set { _DatabaseMaintenancePlan = value; }
}
public NotSupportedList DataControl
{
get { return _DataControl; }
set { _DataControl = value; }
}
public NotSupportedList DistributedQueriesSP
{
get { return _DistributedQueriesSP; }
set { _DistributedQueriesSP = value; }
}
public NotSupportedList FullTextSearchSP
{
get { return _FullTextSearchSP; }
set { _FullTextSearchSP = value; }
}
public NotSupportedList GeneralExtendedSPs
{
get { return _GeneralExtendedSPs; }
set { _GeneralExtendedSPs = value; }
}
public NotSupportedList IntegrationServicesTable
{
get { return _IntegrationServicesTable; }
set { _IntegrationServicesTable = value; }
}
public NotSupportedList LogShipping
{
get { return _LogShipping; }
set { _LogShipping = value; }
}
public NotSupportedList MetadataFunction
{
get { return _MetadataFunction; }
set { _MetadataFunction = value; }
}
public NotSupportedList OLEAutomationSP
{
get { return _OLEAutomationSP; }
set { _OLEAutomationSP = value; }
}
public NotSupportedList OLEDBTable
{
get { return _OLEDBTable; }
set { _OLEDBTable = value; }
}
public NotSupportedList ProfilerSP
{
get { return _ProfilerSP; }
set { _ProfilerSP = value; }
}
public NotSupportedList ReplicationSP
{
get { return _ReplicationSP; }
set { _ReplicationSP = value; }
}
public NotSupportedList ReplicationTable
{
get { return _ReplicationTable; }
set { _ReplicationTable = value; }
}
public NotSupportedList RowsetFunction
{
get { return _RowsetFunction; }
set { _RowsetFunction = value; }
}
public NotSupportedList SecurityFunction
{
get { return _SecurityFunction; }
set { _SecurityFunction = value; }
}
public NotSupportedList SecuritySP
{
get { return _SecuritySP; }
set { _SecuritySP = value; }
}
public NotSupportedList SQLMailSP
{
get { return _SQLMailSP; }
set { _SQLMailSP = value; }
}
public NotSupportedList SQLServerAgentSP
{
get { return _SQLServerAgentSP; }
set { _SQLServerAgentSP = value; }
}
public NotSupportedList SQLServerAgentTable
{
get { return _SQLServerAgentTable; }
set { _SQLServerAgentTable = value; }
}
public NotSupportedList SystemCatalogView
{
get { return _SystemCatalogView; }
set { _SystemCatalogView = value; }
}
public NotSupportedList SystemFunction
{
get { return _SystemFunction; }
set { _SystemFunction = value; }
}
public NotSupportedList SystemStatisticalFunction
{
get { return _SystemStatisticalFunction; }
set { _SystemStatisticalFunction = value; }
}
public NotSupportedList Unclassified
{
get { return _Unclassified; }
set { _Unclassified = value; }
}
public TSQLNotSupportedByAzure()
{
}
}
}
| 30.829932 | 116 | 0.609665 | [
"MIT"
] | LaudateCorpus1/Dnn.EVS | SQLAzureMigration/SQLAzureMWUtils/RulesEngine/TSQLNotSupportedByAzure.cs | 9,067 | C# |
/*
File Generated by NetTiers templates [www.nettiers.com]
Important: Do not modify this file. Edit the file SqlTestTimestampProvider.cs instead.
*/
#region using directives
using System;
using System.Data;
using System.Data.Common;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Data;
using Nettiers.AdventureWorks.Data.Bases;
#endregion
namespace Nettiers.AdventureWorks.Data.SqlClient
{
///<summary>
/// This class is the SqlClient Data Access Logic Component implementation for the <see cref="TestTimestamp"/> entity.
///</summary>
public abstract partial class SqlTestTimestampProviderBase : TestTimestampProviderBase
{
#region Declarations
string _connectionString;
bool _useStoredProcedure;
string _providerInvariantName;
#endregion "Declarations"
#region Constructors
/// <summary>
/// Creates a new <see cref="SqlTestTimestampProviderBase"/> instance.
/// </summary>
public SqlTestTimestampProviderBase()
{
}
/// <summary>
/// Creates a new <see cref="SqlTestTimestampProviderBase"/> instance.
/// Uses connection string to connect to datasource.
/// </summary>
/// <param name="connectionString">The connection string to the database.</param>
/// <param name="useStoredProcedure">A boolean value that indicates if we should use stored procedures or embedded queries.</param>
/// <param name="providerInvariantName">Name of the invariant provider use by the DbProviderFactory.</param>
public SqlTestTimestampProviderBase(string connectionString, bool useStoredProcedure, string providerInvariantName)
{
this._connectionString = connectionString;
this._useStoredProcedure = useStoredProcedure;
this._providerInvariantName = providerInvariantName;
}
#endregion "Constructors"
#region Public properties
/// <summary>
/// Gets or sets the connection string.
/// </summary>
/// <value>The connection string.</value>
public string ConnectionString
{
get {return this._connectionString;}
set {this._connectionString = value;}
}
/// <summary>
/// Gets or sets a value indicating whether to use stored procedures.
/// </summary>
/// <value><c>true</c> if we choose to use use stored procedures; otherwise, <c>false</c>.</value>
public bool UseStoredProcedure
{
get {return this._useStoredProcedure;}
set {this._useStoredProcedure = value;}
}
/// <summary>
/// Gets or sets the invariant provider name listed in the DbProviderFactories machine.config section.
/// </summary>
/// <value>The name of the provider invariant.</value>
public string ProviderInvariantName
{
get { return this._providerInvariantName; }
set { this._providerInvariantName = value; }
}
#endregion
#region Get Many To Many Relationship Functions
#endregion
#region Delete Functions
/// <summary>
/// Deletes a row from the DataSource.
/// </summary>
/// <param name="_testTimestampId">. Primary Key.</param>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="_version">The timestamp field used for concurrency check.</param>
/// <remarks>Deletes based on primary key(s).</remarks>
/// <returns>Returns true if operation suceeded.</returns>
/// <exception cref="System.Exception">The command could not be executed.</exception>
/// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
/// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
/// <exception cref="DBConcurrencyException">The record has been modified by an other user. Please reload the instance before deleting.</exception>
public override bool Delete(TransactionManager transactionManager, System.Int32 _testTimestampId, byte[] _version)
{
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_Delete", _useStoredProcedure);
database.AddInParameter(commandWrapper, "@TestTimestampId", DbType.Int32, _testTimestampId);
database.AddInParameter(commandWrapper, "@Version", DbType.Binary, _version);
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "Delete"));
int results = 0;
if (transactionManager != null)
{
results = Utility.ExecuteNonQuery(transactionManager, commandWrapper);
}
else
{
results = Utility.ExecuteNonQuery(database,commandWrapper);
}
//Stop Tracking Now that it has been updated and persisted.
if (DataRepository.Provider.EnableEntityTracking)
{
string entityKey = EntityLocator.ConstructKeyFromPkItems(typeof(TestTimestamp)
,_testTimestampId);
EntityManager.StopTracking(entityKey);
}
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "Delete"));
if (results == 0)
{
throw new DBConcurrencyException ("The record has been modified by an other user. Please reload the instance before deleting.");
}
commandWrapper = null;
return Convert.ToBoolean(results);
}//end Delete
#endregion
#region Find Functions
#region Parsed Find Methods
/// <summary>
/// Returns rows meeting the whereClause condition from the DataSource.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out. The number of rows that match this query.</param>
/// <remarks>Operators must be capitalized (OR, AND).</remarks>
/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TestTimestamp objects.</returns>
public override TList<TestTimestamp> Find(TransactionManager transactionManager, string whereClause, int start, int pageLength, out int count)
{
count = -1;
if (whereClause.IndexOf(";") > -1)
return new TList<TestTimestamp>();
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_Find", _useStoredProcedure);
bool searchUsingOR = false;
if (whereClause.IndexOf(" OR ") > 0) // did they want to do "a=b OR c=d OR..."?
searchUsingOR = true;
database.AddInParameter(commandWrapper, "@SearchUsingOR", DbType.Boolean, searchUsingOR);
database.AddInParameter(commandWrapper, "@TestTimestampId", DbType.Int32, DBNull.Value);
database.AddInParameter(commandWrapper, "@DumbField", DbType.Boolean, DBNull.Value);
database.AddInParameter(commandWrapper, "@Version", DbType.Binary, DBNull.Value);
// replace all instances of 'AND' and 'OR' because we already set searchUsingOR
whereClause = whereClause.Replace(" AND ", "|").Replace(" OR ", "|") ;
string[] clauses = whereClause.ToLower().Split('|');
// Here's what's going on below: Find a field, then to get the value we
// drop the field name from the front, trim spaces, drop the '=' sign,
// trim more spaces, and drop any outer single quotes.
// Now handles the case when two fields start off the same way - like "Friendly='Yes' AND Friend='john'"
char[] equalSign = {'='};
char[] singleQuote = {'\''};
foreach (string clause in clauses)
{
if (clause.Trim().StartsWith("testtimestampid ") || clause.Trim().StartsWith("testtimestampid="))
{
database.SetParameterValue(commandWrapper, "@TestTimestampId",
clause.Trim().Remove(0,15).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
continue;
}
if (clause.Trim().StartsWith("dumbfield ") || clause.Trim().StartsWith("dumbfield="))
{
database.SetParameterValue(commandWrapper, "@DumbField",
clause.Trim().Remove(0,9).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
continue;
}
if (clause.Trim().StartsWith("version ") || clause.Trim().StartsWith("version="))
{
database.SetParameterValue(commandWrapper, "@Version",
clause.Trim().Remove(0,7).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
continue;
}
throw new ArgumentException("Unable to use this part of the where clause in this version of Find: " + clause);
}
IDataReader reader = null;
//Create Collection
TList<TestTimestamp> rows = new TList<TestTimestamp>();
try
{
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows));
if (transactionManager != null)
{
reader = Utility.ExecuteReader(transactionManager, commandWrapper);
}
else
{
reader = Utility.ExecuteReader(database, commandWrapper);
}
Fill(reader, rows, start, pageLength);
if(reader.NextResult())
{
if(reader.Read())
{
count = reader.GetInt32(0);
}
}
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows));
}
finally
{
if (reader != null)
reader.Close();
commandWrapper = null;
}
return rows;
}
#endregion Parsed Find Methods
#region Parameterized Find Methods
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out. The number of rows that match this query.</param>
/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TestTimestamp objects.</returns>
public override TList<TestTimestamp> Find(TransactionManager transactionManager, IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count)
{
SqlFilterParameterCollection filter = null;
if (parameters == null)
filter = new SqlFilterParameterCollection();
else
filter = parameters.GetParameters();
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_Find_Dynamic", typeof(TestTimestampColumn), filter, orderBy, start, pageLength);
SqlFilterParameter param;
for ( int i = 0; i < filter.Count; i++ )
{
param = filter[i];
database.AddInParameter(commandWrapper, param.Name, param.DbType, param.GetValue());
}
TList<TestTimestamp> rows = new TList<TestTimestamp>();
IDataReader reader = null;
try
{
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows));
if ( transactionManager != null )
{
reader = Utility.ExecuteReader(transactionManager, commandWrapper);
}
else
{
reader = Utility.ExecuteReader(database, commandWrapper);
}
Fill(reader, rows, 0, int.MaxValue);
count = rows.Count;
if ( reader.NextResult() )
{
if ( reader.Read() )
{
count = reader.GetInt32(0);
}
}
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows));
}
finally
{
if ( reader != null )
reader.Close();
commandWrapper = null;
}
return rows;
}
#endregion Parameterized Find Methods
#endregion Find Functions
#region GetAll Methods
/// <summary>
/// Gets All rows from the DataSource.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out. The number of rows that match this query.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TestTimestamp objects.</returns>
/// <exception cref="System.Exception">The command could not be executed.</exception>
/// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
/// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
public override TList<TestTimestamp> GetAll(TransactionManager transactionManager, int start, int pageLength, out int count)
{
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_Get_List", _useStoredProcedure);
IDataReader reader = null;
//Create Collection
TList<TestTimestamp> rows = new TList<TestTimestamp>();
try
{
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "GetAll", rows));
if (transactionManager != null)
{
reader = Utility.ExecuteReader(transactionManager, commandWrapper);
}
else
{
reader = Utility.ExecuteReader(database, commandWrapper);
}
Fill(reader, rows, start, pageLength);
count = -1;
if(reader.NextResult())
{
if(reader.Read())
{
count = reader.GetInt32(0);
}
}
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "GetAll", rows));
}
finally
{
if (reader != null)
reader.Close();
commandWrapper = null;
}
return rows;
}//end getall
#endregion
#region GetPaged Methods
/// <summary>
/// Gets a page of rows from the DataSource.
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">Number of rows in the DataSource.</param>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.TestTimestamp objects.</returns>
public override TList<TestTimestamp> GetPaged(TransactionManager transactionManager, string whereClause, string orderBy, int start, int pageLength, out int count)
{
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_GetPaged", _useStoredProcedure);
if (commandWrapper.CommandType == CommandType.Text
&& commandWrapper.CommandText != null)
{
commandWrapper.CommandText = commandWrapper.CommandText.Replace(SqlUtil.PAGE_INDEX, string.Concat(SqlUtil.PAGE_INDEX, Guid.NewGuid().ToString("N").Substring(0, 8)));
}
database.AddInParameter(commandWrapper, "@WhereClause", DbType.String, whereClause);
database.AddInParameter(commandWrapper, "@OrderBy", DbType.String, orderBy);
database.AddInParameter(commandWrapper, "@PageIndex", DbType.Int32, start);
database.AddInParameter(commandWrapper, "@PageSize", DbType.Int32, pageLength);
IDataReader reader = null;
//Create Collection
TList<TestTimestamp> rows = new TList<TestTimestamp>();
try
{
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "GetPaged", rows));
if (transactionManager != null)
{
reader = Utility.ExecuteReader(transactionManager, commandWrapper);
}
else
{
reader = Utility.ExecuteReader(database, commandWrapper);
}
Fill(reader, rows, 0, int.MaxValue);
count = rows.Count;
if(reader.NextResult())
{
if(reader.Read())
{
count = reader.GetInt32(0);
}
}
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "GetPaged", rows));
}
catch(Exception)
{
throw;
}
finally
{
if (reader != null)
reader.Close();
commandWrapper = null;
}
return rows;
}
#endregion
#region Get By Foreign Key Functions
#endregion
#region Get By Index Functions
#region GetByTestTimestampId
/// <summary>
/// Gets rows from the datasource based on the PK_TestTimestamp index.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="_testTimestampId"></param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out parameter to get total records for query.</param>
/// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TestTimestamp"/> class.</returns>
/// <remarks></remarks>
/// <exception cref="System.Exception">The command could not be executed.</exception>
/// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
/// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
public override Nettiers.AdventureWorks.Entities.TestTimestamp GetByTestTimestampId(TransactionManager transactionManager, System.Int32 _testTimestampId, int start, int pageLength, out int count)
{
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_GetByTestTimestampId", _useStoredProcedure);
database.AddInParameter(commandWrapper, "@TestTimestampId", DbType.Int32, _testTimestampId);
IDataReader reader = null;
TList<TestTimestamp> tmp = new TList<TestTimestamp>();
try
{
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByTestTimestampId", tmp));
if (transactionManager != null)
{
reader = Utility.ExecuteReader(transactionManager, commandWrapper);
}
else
{
reader = Utility.ExecuteReader(database, commandWrapper);
}
//Create collection and fill
Fill(reader, tmp, start, pageLength);
count = -1;
if(reader.NextResult())
{
if(reader.Read())
{
count = reader.GetInt32(0);
}
}
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "GetByTestTimestampId", tmp));
}
finally
{
if (reader != null)
reader.Close();
commandWrapper = null;
}
if (tmp.Count == 1)
{
return tmp[0];
}
else if (tmp.Count == 0)
{
return null;
}
else
{
throw new DataException("Cannot find the unique instance of the class.");
}
//return rows;
}
#endregion
#endregion Get By Index Functions
#region Insert Methods
/// <summary>
/// Lets you efficiently bulk insert many entities to the database.
/// </summary>
/// <param name="transactionManager">The transaction manager.</param>
/// <param name="entities">The entities.</param>
/// <remarks>
/// After inserting into the datasource, the Nettiers.AdventureWorks.Entities.TestTimestamp object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
public override void BulkInsert(TransactionManager transactionManager, TList<Nettiers.AdventureWorks.Entities.TestTimestamp> entities)
{
//System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);
System.Data.SqlClient.SqlBulkCopy bulkCopy = null;
if (transactionManager != null && transactionManager.IsOpen)
{
System.Data.SqlClient.SqlConnection cnx = transactionManager.TransactionObject.Connection as System.Data.SqlClient.SqlConnection;
System.Data.SqlClient.SqlTransaction transaction = transactionManager.TransactionObject as System.Data.SqlClient.SqlTransaction;
bulkCopy = new System.Data.SqlClient.SqlBulkCopy(cnx, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints, transaction); //, null);
}
else
{
bulkCopy = new System.Data.SqlClient.SqlBulkCopy(this._connectionString, System.Data.SqlClient.SqlBulkCopyOptions.CheckConstraints); //, null);
}
bulkCopy.BulkCopyTimeout = 360;
bulkCopy.DestinationTableName = "TestTimestamp";
DataTable dataTable = new DataTable();
DataColumn col0 = dataTable.Columns.Add("TestTimestampId", typeof(System.Int32));
col0.AllowDBNull = false;
DataColumn col1 = dataTable.Columns.Add("DumbField", typeof(System.Boolean));
col1.AllowDBNull = true;
DataColumn col2 = dataTable.Columns.Add("Version", typeof(System.Byte[]));
col2.AllowDBNull = false;
bulkCopy.ColumnMappings.Add("TestTimestampId", "TestTimestampId");
bulkCopy.ColumnMappings.Add("DumbField", "DumbField");
bulkCopy.ColumnMappings.Add("Version", "Version");
foreach(Nettiers.AdventureWorks.Entities.TestTimestamp entity in entities)
{
if (entity.EntityState != EntityState.Added)
continue;
DataRow row = dataTable.NewRow();
row["TestTimestampId"] = entity.TestTimestampId;
row["DumbField"] = entity.DumbField.HasValue ? (object) entity.DumbField : System.DBNull.Value;
row["Version"] = entity.Version;
dataTable.Rows.Add(row);
}
// send the data to the server
bulkCopy.WriteToServer(dataTable);
// update back the state
foreach(Nettiers.AdventureWorks.Entities.TestTimestamp entity in entities)
{
if (entity.EntityState != EntityState.Added)
continue;
entity.AcceptChanges();
}
}
/// <summary>
/// Inserts a Nettiers.AdventureWorks.Entities.TestTimestamp object into the datasource using a transaction.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="entity">Nettiers.AdventureWorks.Entities.TestTimestamp object to insert.</param>
/// <remarks>
/// After inserting into the datasource, the Nettiers.AdventureWorks.Entities.TestTimestamp object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns true if operation is successful.</returns>
/// <exception cref="System.Exception">The command could not be executed.</exception>
/// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
/// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
public override bool Insert(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TestTimestamp entity)
{
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_Insert", _useStoredProcedure);
database.AddOutParameter(commandWrapper, "@TestTimestampId", DbType.Int32, 4);
database.AddInParameter(commandWrapper, "@DumbField", DbType.Boolean, (entity.DumbField.HasValue ? (object) entity.DumbField : System.DBNull.Value));
database.AddOutParameter(commandWrapper, "@Version", DbType.Binary, 8);
int results = 0;
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "Insert", entity));
if (transactionManager != null)
{
results = Utility.ExecuteNonQuery(transactionManager, commandWrapper);
}
else
{
results = Utility.ExecuteNonQuery(database,commandWrapper);
}
object _testTimestampId = database.GetParameterValue(commandWrapper, "@TestTimestampId");
entity.TestTimestampId = (System.Int32)_testTimestampId;
object _version = database.GetParameterValue(commandWrapper, "@Version");
entity.Version = (System.Byte[])_version;
entity.AcceptChanges();
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "Insert", entity));
return Convert.ToBoolean(results);
}
#endregion
#region Update Methods
/// <summary>
/// Update an existing row in the datasource.
/// </summary>
/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
/// <param name="entity">Nettiers.AdventureWorks.Entities.TestTimestamp object to update.</param>
/// <remarks>
/// After updating the datasource, the Nettiers.AdventureWorks.Entities.TestTimestamp object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns true if operation is successful.</returns>
/// <exception cref="System.Exception">The command could not be executed.</exception>
/// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
/// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
/// <exception cref="DBConcurrencyException">The record has been modified by an other user. Please reload the instance before updating.</exception>
public override bool Update(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TestTimestamp entity)
{
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test.usp_adwTiers_TestTimestamp_Update", _useStoredProcedure);
database.AddInParameter(commandWrapper, "@TestTimestampId", DbType.Int32, entity.TestTimestampId );
database.AddInParameter(commandWrapper, "@DumbField", DbType.Boolean, (entity.DumbField.HasValue ? (object) entity.DumbField : System.DBNull.Value) );
database.AddInParameter(commandWrapper, "@Version", DbType.Binary, entity.Version );
database.AddOutParameter(commandWrapper, "@ReturnedVersion", DbType.Binary, 8);
int results = 0;
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "Update", entity));
if (transactionManager != null)
{
results = Utility.ExecuteNonQuery(transactionManager, commandWrapper);
}
else
{
results = Utility.ExecuteNonQuery(database,commandWrapper);
}
//Stop Tracking Now that it has been updated and persisted.
if (DataRepository.Provider.EnableEntityTracking)
EntityManager.StopTracking(entity.EntityTrackingKey);
if (results == 0)
{
throw new DBConcurrencyException("Concurrency exception");
}
entity.Version = (System.Byte[])database.GetParameterValue(commandWrapper, "@ReturnedVersion");
entity.AcceptChanges();
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "Update", entity));
return Convert.ToBoolean(results);
}
#endregion
#region Custom Methods
#region _TestTimestamp_GetAllTimestamp
/// <summary>
/// This method wraps the '_TestTimestamp_GetAllTimestamp' stored procedure.
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="transactionManager"><see cref="TransactionManager"/> object.</param>
/// <remark>This method is generated from a stored procedure.</remark>
/// <returns>A <see cref="TList<TestTimestamp>"/> instance.</returns>
public override TList<TestTimestamp> GetAllTimestamp(TransactionManager transactionManager, int start, int pageLength )
{
SqlDatabase database = new SqlDatabase(this._connectionString);
DbCommand commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Test._TestTimestamp_GetAllTimestamp", true);
IDataReader reader = null;
//Create Collection
TList<TestTimestamp> rows = new TList<TestTimestamp>();
//Provider Data Requesting Command Event
OnDataRequesting(new CommandEventArgs(commandWrapper, "GetAllTimestamp", rows));
if (transactionManager != null)
{
reader = Utility.ExecuteReader(transactionManager, commandWrapper);
}
else
{
reader = Utility.ExecuteReader(database, commandWrapper);
}
try
{
Fill(reader, rows, start, pageLength);
}
finally
{
if (reader != null)
reader.Close();
}
//Provider Data Requested Command Event
OnDataRequested(new CommandEventArgs(commandWrapper, "GetAllTimestamp", rows));
return rows;
}
#endregion
#endregion
}//end class
} // end namespace
| 37.876074 | 198 | 0.688393 | [
"MIT"
] | aqua88hn/netTiers | Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Data.SqlClient/SqlTestTimestampProviderBase.generated.cs | 30,871 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.Sven_Torben.Serialization_Benchmark.Logging
{
sealed class ConsoleLogger : AbstractDetailsLogger
{
protected override void Log(string serializerName, int bytes, int iterations, long minWrite, long minRead, double avgWrite, double avgRead, long maxWrite, long maxRead)
{
Console.Out.WriteLine("{0,-60} : {1,8} bytes, {2,4} iterations, {3,5}ms min write, {4,5}ms min read, {5,5:0.0}ms avg write, {6,5:0.0}ms avg read, {7,5}ms max write, {8,5}ms max read", serializerName, bytes, iterations, minWrite,
minRead, avgWrite, avgRead, maxWrite, maxRead);
}
}
}
| 37.5 | 240 | 0.690667 | [
"MIT"
] | sventorben/serialization-benchmark | net/Logging/ConsoleLogger.cs | 752 | C# |
// Decompiled with JetBrains decompiler
// Type: OnyxServer.xmpp.query.ClanCreate
// Assembly: OnyxServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 55A849F0-90C5-4313-B057-B0361B81D824
// Assembly location: C:\Users\Дмитрий\Downloads\New Compressed (zipped) Folder\servers\tls\OnyxServer.dll
using MySql.Data.MySqlClient;
using WARTLS.CLASSES;
using WARTLS.EXCEPTION;
using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace WARTLS.xmpp.query
{
public class ClanCreate : Stanza
{
private Clan Clan;
public ClanCreate(Client User, XmlDocument Packet)
: base(User, Packet)
{
using (MySqlConnection result = SQL.GetConnection().GetAwaiter().GetResult())
{
using (MySqlDataReader mySqlDataReader = new MySqlCommand("SELECT * FROM clans WHERE Name='" + this.Query.Attributes["clan_name"].InnerText + "'", result).ExecuteReader())
{
if (mySqlDataReader.HasRows)
{
mySqlDataReader.Close();
throw new StanzaException(User, Packet, 4);
}
mySqlDataReader.Close();
}
this.Clan = new Clan(this.Query.Attributes["clan_name"].InnerText, Encoding.UTF8.GetString(Convert.FromBase64String(this.Query.Attributes["description"].InnerText)), User);
this.Process();
if (User.Player.RoomPlayer.Room != null)
User.Player.RoomPlayer.Room.Sync((Client) null);
Console.WriteLine(User.Player.Nickname + "clan created with name:" + this.Query.Attributes["clan_name"].InnerText);
result.Close();
}
}
public override void Process()
{
XDocument xDocument = new XDocument();
XElement xelement1 = new XElement(Gateway.JabberNS + "iq");
xelement1.Add((object) new XAttribute((XName) "type", (object) "result"));
xelement1.Add((object) new XAttribute((XName) "from", (object) this.To));
xelement1.Add((object) new XAttribute((XName) "to", (object) this.User.JID));
xelement1.Add((object) new XAttribute((XName) "id", (object) this.Id));
XElement xelement2 = new XElement(Stanza.NameSpace + "query");
XElement xelement3 = new XElement((XName) "clan_create");
xelement3.Add((object) this.Clan.Serialize(this.User));
xelement2.Add((object) xelement3);
xelement1.Add((object) xelement2);
xDocument.Add((object) xelement1);
this.Compress(ref xDocument);
this.User.Send(xDocument.ToString());
}
}
}
| 39.809524 | 180 | 0.669458 | [
"MIT"
] | myrka32/wartls | xmpp/query/ClanCreate.cs | 2,517 | 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 BenchmarkDotNet.Attributes;
using Microsoft.Data.DataView;
using Microsoft.ML.Benchmarks.Harness;
using Microsoft.ML.Data;
using Microsoft.ML.TestFramework;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms;
namespace Microsoft.ML.Benchmarks
{
[CIBenchmark]
public class PredictionEngineBench
{
private IrisData _irisExample;
private PredictionEngine<IrisData, IrisPrediction> _irisModel;
private SentimentData _sentimentExample;
private PredictionEngine<SentimentData, SentimentPrediction> _sentimentModel;
private BreastCancerData _breastCancerExample;
private PredictionEngine<BreastCancerData, BreastCancerPrediction> _breastCancerModel;
[GlobalSetup(Target = nameof(MakeIrisPredictions))]
public void SetupIrisPipeline()
{
_irisExample = new IrisData()
{
SepalLength = 3.3f,
SepalWidth = 1.6f,
PetalLength = 0.2f,
PetalWidth = 5.1f,
};
string _irisDataPath = BaseTestClass.GetDataPath("iris.txt");
var env = new MLContext(seed: 1);
// Create text loader.
var options = new TextLoader.Options()
{
Columns = new[]
{
new TextLoader.Column("Label", DataKind.Single, 0),
new TextLoader.Column("SepalLength", DataKind.Single, 1),
new TextLoader.Column("SepalWidth", DataKind.Single, 2),
new TextLoader.Column("PetalLength", DataKind.Single, 3),
new TextLoader.Column("PetalWidth", DataKind.Single, 4),
},
HasHeader = true,
};
var loader = new TextLoader(env, options: options);
IDataView data = loader.Load(_irisDataPath);
var pipeline = new ColumnConcatenatingEstimator(env, "Features", new[] { "SepalLength", "SepalWidth", "PetalLength", "PetalWidth" })
.Append(env.Transforms.Conversion.MapValueToKey("Label"))
.Append(env.MulticlassClassification.Trainers.StochasticDualCoordinateAscent(
new SdcaMultiClassTrainer.Options { NumberOfThreads = 1, ConvergenceTolerance = 1e-2f, }));
var model = pipeline.Fit(data);
_irisModel = model.CreatePredictionEngine<IrisData, IrisPrediction>(env);
}
[GlobalSetup(Target = nameof(MakeSentimentPredictions))]
public void SetupSentimentPipeline()
{
_sentimentExample = new SentimentData()
{
SentimentText = "Not a big fan of this."
};
string _sentimentDataPath = BaseTestClass.GetDataPath("wikipedia-detox-250-line-data.tsv");
var mlContext = new MLContext(seed: 1);
// Create text loader.
var options = new TextLoader.Options()
{
Columns = new[]
{
new TextLoader.Column("Label", DataKind.Boolean, 0),
new TextLoader.Column("SentimentText", DataKind.String, 1)
},
HasHeader = true,
};
var loader = new TextLoader(mlContext, options: options);
IDataView data = loader.Load(_sentimentDataPath);
var pipeline = mlContext.Transforms.Text.FeaturizeText("Features", "SentimentText")
.Append(mlContext.BinaryClassification.Trainers.StochasticDualCoordinateAscentNonCalibrated(
new SdcaNonCalibratedBinaryTrainer.Options { NumberOfThreads = 1, ConvergenceTolerance = 1e-2f, }));
var model = pipeline.Fit(data);
_sentimentModel = model.CreatePredictionEngine<SentimentData, SentimentPrediction>(mlContext);
}
[GlobalSetup(Target = nameof(MakeBreastCancerPredictions))]
public void SetupBreastCancerPipeline()
{
_breastCancerExample = new BreastCancerData()
{
Features = new[] { 5f, 1f, 1f, 1f, 2f, 1f, 3f, 1f, 1f }
};
string _breastCancerDataPath = BaseTestClass.GetDataPath("breast-cancer.txt");
var env = new MLContext(seed: 1);
// Create text loader.
var options = new TextLoader.Options()
{
Columns = new[]
{
new TextLoader.Column("Label", DataKind.Boolean, 0),
new TextLoader.Column("Features", DataKind.Single, new[] { new TextLoader.Range(1, 9) })
},
HasHeader = false,
};
var loader = new TextLoader(env, options: options);
IDataView data = loader.Load(_breastCancerDataPath);
var pipeline = env.BinaryClassification.Trainers.StochasticDualCoordinateAscentNonCalibrated(
new SdcaNonCalibratedBinaryTrainer.Options { NumberOfThreads = 1, ConvergenceTolerance = 1e-2f, });
var model = pipeline.Fit(data);
_breastCancerModel = model.CreatePredictionEngine<BreastCancerData, BreastCancerPrediction>(env);
}
[Benchmark]
public void MakeIrisPredictions()
{
for (int i = 0; i < 10000; i++)
{
_irisModel.Predict(_irisExample);
}
}
[Benchmark]
public void MakeSentimentPredictions()
{
for (int i = 0; i < 10000; i++)
{
_sentimentModel.Predict(_sentimentExample);
}
}
[Benchmark]
public void MakeBreastCancerPredictions()
{
for (int i = 0; i < 10000; i++)
{
_breastCancerModel.Predict(_breastCancerExample);
}
}
}
public class SentimentData
{
[ColumnName("Label"), LoadColumn(0)]
public bool Sentiment;
[LoadColumn(1)]
public string SentimentText;
}
public class SentimentPrediction
{
[ColumnName("PredictedLabel")]
public bool Sentiment;
public float Score;
}
public class BreastCancerData
{
[ColumnName("Label")]
public bool Label;
[ColumnName("Features"), VectorType(9)]
public float[] Features;
}
public class BreastCancerPrediction
{
[ColumnName("Score")]
public float Score;
}
}
| 33.878788 | 144 | 0.585719 | [
"MIT"
] | calcbench/machinelearning | test/Microsoft.ML.Benchmarks/PredictionEngineBench.cs | 6,708 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FastOSStartupMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FastOSStartupMod")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91311736-0a7f-466c-a575-e9a901654b9d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.837838 | 84 | 0.749286 | [
"Unlicense"
] | oxygencraft/FastOSStartupMod | FastOSStartupMod/FastOSStartupMod/Properties/AssemblyInfo.cs | 1,403 | C# |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using CouchDB.Driver.ChangesFeed.Filters;
using CouchDB.Driver.Types;
namespace CouchDB.Driver.ChangesFeed
{
/// <summary>
/// Represent a filter for the changes feed.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1052:Static holder types should be Static or NotInheritable", Justification = "<Pending>")]
public class ChangesFeedFilter
{
/// <summary>
/// Create a filter for document IDs.
/// </summary>
/// <param name="documentIds">The document IDs to use as filters.</param>
/// <returns></returns>
public static ChangesFeedFilter DocumentIds(IList<string> documentIds)
=> new DocumentIdsChangesFeedFilter(documentIds);
/// <summary>
/// Create a filter using the same syntax used to query.
/// </summary>
/// <remarks>
/// This is significantly more efficient than using a JavaScript filter function and is the recommended option if filtering on document attributes only.
/// </remarks>
/// <typeparam name="TSource">The type of database documents.</typeparam>
/// <param name="selector">The function used to filter.</param>
/// <returns></returns>
public static ChangesFeedFilter Selector<TSource>(Expression<Func<TSource, bool>> selector) where TSource : CouchDocument
=> new SelectorChangesFeedFilter<TSource>(selector);
/// <summary>
/// Create a filter that accepts only changes for any design document within the requested database.
/// </summary>
/// <returns></returns>
public static ChangesFeedFilter Design()
=> new DesignChangesFeedFilter();
/// <summary>
/// Create a filter that uses an existing map function to the filter.
/// </summary>
/// <remarks>
/// If the map function emits anything for the processed document it counts as accepted and the changes event emits to the feed.
/// </remarks>
/// <param name="view">The view.</param>
/// <returns></returns>
public static ChangesFeedFilter View(string view)
=> new ViewChangesFeedFilter(view);
}
}
| 42.648148 | 160 | 0.645245 | [
"MIT"
] | AlexandrSHad/couchdb-net | src/CouchDB.Driver/ChangesFeed/ChangesFeedFilter.cs | 2,305 | C# |
/*
* https://github.com/PandaWood/ExceptionReporter.NET
*/
using System.Linq;
using System.Windows.Forms;
using ExceptionReporting.SystemInfo;
namespace ExceptionReporting.WinForms
{
///<summary>
/// WinForms extension
///</summary>
// ReSharper disable once ClassNeverInstantiated.Global
internal class SysInfoResultMapperWinForm : SysInfoResultMapper
{
/// <summary>
/// Add a tree node to an existing parentNode, by passing the SysInfoResult
/// </summary>
public static void AddTreeViewNode(TreeNode parentNode, SysInfoResult result)
{
var nodeRoot = new TreeNode(result.Name);
foreach (var nodeLeaf in result.Nodes.Select(nodeValueParent => new TreeNode(nodeValueParent)))
{
nodeRoot.Nodes.Add(nodeLeaf);
foreach (var nodeValue in result.ChildResults.SelectMany(childResult => childResult.Nodes))
{
nodeLeaf.Nodes.Add(new TreeNode(nodeValue));
}
}
parentNode.Nodes.Add(nodeRoot);
}
}
} | 26.444444 | 98 | 0.734244 | [
"MIT"
] | OGMichel/ExceptionReporter.NET | src/ExceptionReporter.WinForms/WinForms/SysInfoResultMapperWinForm.cs | 952 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newbe.Claptrap.Localization;
namespace Newbe.Claptrap.Core
{
public class ClaptrapActor : IClaptrap
{
private readonly IClaptrapIdentity _claptrapIdentity;
private readonly ILogger<ClaptrapActor> _logger;
private readonly StateSavingOptions _stateSavingOptions;
private readonly IStateAccessor _stateAccessor;
private readonly IStateRestorer _stateRestorer;
private readonly IEventHandlerFLow _eventHandlerFLow;
private readonly IStateSavingFlow _stateSavingFlow;
private readonly IEventHandledNotificationFlow _eventHandledNotificationFlow;
private readonly IL _l;
public ClaptrapActor(
IClaptrapIdentity claptrapIdentity,
ILogger<ClaptrapActor> logger,
StateSavingOptions stateSavingOptions,
IStateAccessor stateAccessor,
IStateRestorer stateRestorer,
IEventHandlerFLow eventHandlerFLow,
IStateSavingFlow stateSavingFlow,
IEventHandledNotificationFlow eventHandledNotificationFlow,
IL l)
{
_claptrapIdentity = claptrapIdentity;
_logger = logger;
_stateSavingOptions = stateSavingOptions;
_stateAccessor = stateAccessor;
_stateRestorer = stateRestorer;
_eventHandlerFLow = eventHandlerFLow;
_stateSavingFlow = stateSavingFlow;
_eventHandledNotificationFlow = eventHandledNotificationFlow;
_l = l;
}
public IState State => _stateAccessor.State;
public async Task ActivateAsync()
{
try
{
_logger.LogTrace("Start to activate async");
_eventHandledNotificationFlow.Activate();
await _stateRestorer.RestoreAsync();
_stateSavingFlow.Activate();
_eventHandlerFLow.Activate();
_logger.LogTrace("Activated");
}
catch (Exception e)
{
_logger.LogError(e, _l[LK.failed_to_activate_claptrap__identity_], _claptrapIdentity);
throw new ActivateFailException(e, _claptrapIdentity);
}
}
public async Task DeactivateAsync()
{
if (_stateSavingOptions.SaveWhenDeactivateAsync)
{
await _stateSavingFlow.SaveStateAsync(State);
}
_eventHandledNotificationFlow.Deactivate();
_stateSavingFlow.Deactivate();
_eventHandlerFLow.Deactivate();
}
public Task HandleEventAsync(IEvent @event)
{
return _eventHandlerFLow.OnNewEventReceived(@event);
}
}
} | 36.658228 | 103 | 0.61982 | [
"MIT"
] | Z4t4r/Newbe.Claptrap | src/Newbe.Claptrap/Core/ClaptrapActor.cs | 2,896 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GraphQL.Subscription;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Xunit;
namespace GraphQL.Server.Transports.Subscriptions.Abstractions.Tests
{
public class SubscriptionServerFacts
{
public SubscriptionServerFacts()
{
_messageListener = Substitute.For<IOperationMessageListener>();
_transport = new TestableSubscriptionTransport();
_transportReader = _transport.Reader as TestableReader;
_transportWriter = _transport.Writer as TestableWriter;
_documentExecuter = Substitute.For<IGraphQLExecuter>();
_documentExecuter.ExecuteAsync(null, null, null, null).ReturnsForAnyArgs(
new SubscriptionExecutionResult
{
Streams = new Dictionary<string, IObservable<ExecutionResult>>
{
{"1", Substitute.For<IObservable<ExecutionResult>>()}
}
});
_subscriptionManager = new SubscriptionManager(_documentExecuter, new NullLoggerFactory());
_sut = new SubscriptionServer(
_transport,
_subscriptionManager,
new[] {_messageListener},
new NullLogger<SubscriptionServer>());
}
private readonly TestableSubscriptionTransport _transport;
private readonly SubscriptionServer _sut;
private readonly ISubscriptionManager _subscriptionManager;
private readonly IGraphQLExecuter _documentExecuter;
private readonly IOperationMessageListener _messageListener;
private readonly TestableReader _transportReader;
private readonly TestableWriter _transportWriter;
[Fact]
public async Task Listener_BeforeHandle()
{
/* Given */
var expected = new OperationMessage
{
Type = MessageType.GQL_CONNECTION_INIT
};
_transportReader.AddMessageToRead(expected);
await _transportReader.Complete();
/* When */
await _sut.OnConnect();
/* Then */
await _messageListener.Received().BeforeHandleAsync(Arg.Is<MessageHandlingContext>(context =>
context.Writer == _transportWriter
&& context.Reader == _transportReader
&& context.Subscriptions == _subscriptionManager
&& context.Message == expected));
}
[Fact]
public async Task Listener_Handle()
{
/* Given */
var expected = new OperationMessage
{
Type = MessageType.GQL_CONNECTION_INIT
};
_transportReader.AddMessageToRead(expected);
await _transportReader.Complete();
/* When */
await _sut.OnConnect();
/* Then */
await _messageListener.Received().HandleAsync(Arg.Is<MessageHandlingContext>(context =>
context.Writer == _transportWriter
&& context.Reader == _transportReader
&& context.Subscriptions == _subscriptionManager
&& context.Message == expected));
}
[Fact]
public async Task Listener_AfterHandle()
{
/* Given */
var expected = new OperationMessage
{
Type = MessageType.GQL_CONNECTION_INIT
};
_transportReader.AddMessageToRead(expected);
await _transportReader.Complete();
/* When */
await _sut.OnConnect();
/* Then */
await _messageListener.Received().AfterHandleAsync(Arg.Is<MessageHandlingContext>(context =>
context.Writer == _transportWriter
&& context.Reader == _transportReader
&& context.Subscriptions == _subscriptionManager
&& context.Message == expected));
}
}
} | 36.855856 | 105 | 0.593253 | [
"MIT"
] | OneCyrus/server | tests/Transports.Subscriptions.Abstractions.Tests/SubscriptionServerFacts.cs | 4,093 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace TFLiteTestApp
{
public class App : Application
{
public App()
{
TFLite.Interpreter interpreter = null;
try
{
interpreter = new TFLite.Interpreter(Tizen.Applications.Application.Current.DirectoryInfo.Resource + "mobilenet_v1_1.0_224.tflite");
}
catch(Exception e)
{
Tizen.Log.Debug("tflite", "Error: " + e);
}
Tizen.Log.Debug("tflite", "Interpreter Initialised");
Array Output = new byte[1000];
Array input = new byte[150582];
input = File.ReadAllBytes(Tizen.Applications.Application.Current.DirectoryInfo.Resource + "mouse_224.bmp");
interpreter.Run(input, ref Output);
//val variable to check if the Output array is being populated or not.
byte val = ((byte[])Output)[0];
// The root page of your application
MainPage = new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
}
}
}
};
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| 28.575758 | 148 | 0.510074 | [
"Apache-2.0"
] | BalyshevArtem/ONE | runtime/contrib/TFLiteSharp/TFLiteTestApp/TFLiteTestApp_App.cs | 1,888 | C# |
/*
This file is a part of JustLogic product which is distributed under
the BSD 3-clause "New" or "Revised" License
Copyright (c) 2015. All rights reserved.
Authors: Vladyslav Taranov.
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 JustLogic 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 HOLDER 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.
*/
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("Color/Get Linear")]
[UnitFriendlyName("Color.Get Linear")]
[UnitUsage(typeof(Color), HideExpressionInActionsList = true)]
public class JLColorGetLinear : JLExpression
{
[Parameter(ExpressionType = typeof(Color))]
public JLExpression OperandValue;
public override object GetAnyResult(IExecutionContext context)
{
Color opValue = OperandValue.GetResult<Color>(context);
return opValue.linear;
}
}
| 40.203704 | 79 | 0.777982 | [
"BSD-3-Clause"
] | AqlaSolutions/JustLogic | Assets/JustLogicUnits/Generated/Color/JLColorGetLinear.cs | 2,171 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
/// <summary>
/// This Class throws the Standart SharpReport Error
/// </summary>
/// <remarks>
/// created by - Forstmeier Peter
/// created on - 15.01.2005 09:39:32
/// </remarks>
///
namespace ICSharpCode.Reports.Core {
[Serializable()]
public class ReportException : Exception {
string errorMessage = String.Empty;
public ReportException():base(){
}
public ReportException(string errorMessage) :base (errorMessage){
this.errorMessage = errorMessage;
}
public ReportException(string errorMessage,
Exception exception):base (errorMessage,exception){
}
protected ReportException(SerializationInfo info,
StreamingContext context) : base(info, context){
// Implement type-specific serialization constructor logic.
}
public string ErrorMessage {
get {
return errorMessage;
}
}
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context){
if (info == null) {
throw new ArgumentNullException("info");
}
info.AddValue("errorMessage", this.errorMessage);
base.GetObjectData(info, context);
}
}
}
| 27.473684 | 103 | 0.684547 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | src/AddIns/Misc/Reports/ICSharpCode.Reports.Core/Project/Exceptions/ReportException.cs | 1,568 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CoursesApp.Models
{
public class TraineeCourseModel
{
public int CourseId { get; set; }
public DateTime Registration_Date { get; set; }
public TraineeModel Trainee { get; set; }
}
public class TraineeModel
{
public string Name { get; set; }
public string Email { get; set; }
}
} | 22 | 55 | 0.640909 | [
"MIT"
] | ahmadomar/bosla-courses-app | App/CoursesApp/Models/TraineeModel.cs | 442 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
/// <summary> The Azure Data Factory nested object which identifies data within different data stores, such as tables, files, folders, and documents. </summary>
public partial class Dataset : IDictionary<string, object>
{
/// <summary> Initializes a new instance of Dataset. </summary>
/// <param name="linkedServiceName"> Linked service reference. </param>
/// <exception cref="ArgumentNullException"> <paramref name="linkedServiceName"/> is null. </exception>
public Dataset(LinkedServiceReference linkedServiceName)
{
if (linkedServiceName == null)
{
throw new ArgumentNullException(nameof(linkedServiceName));
}
LinkedServiceName = linkedServiceName;
Parameters = new ChangeTrackingDictionary<string, ParameterSpecification>();
Annotations = new ChangeTrackingList<object>();
AdditionalProperties = new ChangeTrackingDictionary<string, object>();
Type = "Dataset";
}
/// <summary> Initializes a new instance of Dataset. </summary>
/// <param name="type"> Type of dataset. </param>
/// <param name="description"> Dataset description. </param>
/// <param name="structure"> Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement. </param>
/// <param name="schema"> Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement. </param>
/// <param name="linkedServiceName"> Linked service reference. </param>
/// <param name="parameters"> Parameters for dataset. </param>
/// <param name="annotations"> List of tags that can be used for describing the Dataset. </param>
/// <param name="folder"> The folder that this Dataset is in. If not specified, Dataset will appear at the root level. </param>
/// <param name="additionalProperties"> . </param>
internal Dataset(string type, string description, object structure, object schema, LinkedServiceReference linkedServiceName, IDictionary<string, ParameterSpecification> parameters, IList<object> annotations, DatasetFolder folder, IDictionary<string, object> additionalProperties)
{
Type = type ?? "Dataset";
Description = description;
Structure = structure;
Schema = schema;
LinkedServiceName = linkedServiceName;
Parameters = parameters;
Annotations = annotations;
Folder = folder;
AdditionalProperties = additionalProperties;
}
/// <summary> Type of dataset. </summary>
internal string Type { get; set; }
/// <summary> Dataset description. </summary>
public string Description { get; set; }
/// <summary> Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement. </summary>
public object Structure { get; set; }
/// <summary> Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement. </summary>
public object Schema { get; set; }
/// <summary> Linked service reference. </summary>
public LinkedServiceReference LinkedServiceName { get; set; }
/// <summary> Parameters for dataset. </summary>
public IDictionary<string, ParameterSpecification> Parameters { get; }
/// <summary> List of tags that can be used for describing the Dataset. </summary>
public IList<object> Annotations { get; }
/// <summary> The folder that this Dataset is in. If not specified, Dataset will appear at the root level. </summary>
public DatasetFolder Folder { get; set; }
internal IDictionary<string, object> AdditionalProperties { get; }
/// <inheritdoc />
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => AdditionalProperties.GetEnumerator();
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => AdditionalProperties.GetEnumerator();
/// <inheritdoc />
public bool TryGetValue(string key, out object value) => AdditionalProperties.TryGetValue(key, out value);
/// <inheritdoc />
public bool ContainsKey(string key) => AdditionalProperties.ContainsKey(key);
/// <inheritdoc />
public ICollection<string> Keys => AdditionalProperties.Keys;
/// <inheritdoc />
public ICollection<object> Values => AdditionalProperties.Values;
/// <inheritdoc cref="ICollection{T}.Count"/>
int ICollection<KeyValuePair<string, object>>.Count => AdditionalProperties.Count;
/// <inheritdoc />
public void Add(string key, object value) => AdditionalProperties.Add(key, value);
/// <inheritdoc />
public bool Remove(string key) => AdditionalProperties.Remove(key);
/// <inheritdoc cref="ICollection{T}.IsReadOnly"/>
bool ICollection<KeyValuePair<string, object>>.IsReadOnly => AdditionalProperties.IsReadOnly;
/// <inheritdoc cref="ICollection{T}.Add"/>
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> value) => AdditionalProperties.Add(value);
/// <inheritdoc cref="ICollection{T}.Remove"/>
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> value) => AdditionalProperties.Remove(value);
/// <inheritdoc cref="ICollection{T}.Contains"/>
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> value) => AdditionalProperties.Contains(value);
/// <inheritdoc cref="ICollection{T}.CopyTo"/>
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] destination, int offset) => AdditionalProperties.CopyTo(destination, offset);
/// <inheritdoc cref="ICollection{T}.Clear"/>
void ICollection<KeyValuePair<string, object>>.Clear() => AdditionalProperties.Clear();
/// <inheritdoc />
public object this[string key]
{
get => AdditionalProperties[key];
set => AdditionalProperties[key] = value;
}
}
}
| 59.088496 | 287 | 0.67066 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/Dataset.cs | 6,677 | C# |
using System.Collections.Generic;
namespace InertiaAdapter.Models
{
public class Props
{
public object? Controller { get; set; }
public IDictionary<string, object>? SharedProps { get; set; }
public object? With { get; set; }
}
}
| 22.166667 | 69 | 0.639098 | [
"MIT"
] | JPBetley/pingcrm-dotnetcore | InertiaAdapter/Models/Props.cs | 266 | C# |
using Volo.Abp.Bundling;
namespace OpenIddictDemo.Blazor;
/* Add your global styles/scripts here.
* See https://docs.abp.io/en/abp/latest/UI/Blazor/Global-Scripts-Styles to learn how to use it
*/
public class OpenIddictDemoBundleContributor : IBundleContributor
{
public void AddScripts(BundleContext context)
{
}
public void AddStyles(BundleContext context)
{
context.Add("main.css", true);
}
}
| 21.75 | 95 | 0.714943 | [
"MIT"
] | JadynWong/Abp.OpenIddict | OpenIddictDemo/src/OpenIddictDemo.Blazor/OpenIddictDemoBundleContributor.cs | 437 | C# |
using CloudObjects.App.Services;
using Dapper.CX.SqlServer.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
namespace CloudObjects.App.Extensions
{
public static class ServiceCollectionExtensions
{
public static void AddTokenGenerator(this IServiceCollection services, string jwtSecret)
{
services.AddScoped((sp) =>
{
var data = sp.GetRequiredService<DapperCX<long>>();
return new TokenGenerator(jwtSecret, data);
});
}
public static void AddHttpContext(this IServiceCollection services)
{
services.AddScoped((sp) =>
{
var contextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
return contextAccessor.HttpContext;
});
}
/// <summary>
/// help from https://www.thecodebuzz.com/jwt-authorization-token-swagger-open-api-asp-net-core-3-0/
/// </summary>
public static void AddCloudObjectsAuthentication(this IServiceCollection services, string jwtSecret)
{
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
public static void AddSwagger(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
[new OpenApiSecurityScheme()
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}] = new string[] { }
});
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CloudObjects API", Version = "v1" });
});
}
}
}
| 37 | 108 | 0.534327 | [
"MIT"
] | adamfoneil/CloudObjects | CloudObjects.App/Extensions/ServiceCollectionExtensions.cs | 3,221 | C# |
/*
* SimScale API
*
* The version of the OpenAPI document: 0.0.0
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OpenAPIDateConverter = SimScale.Sdk.Client.OpenAPIDateConverter;
namespace SimScale.Sdk.Model
{
/// <summary>
/// Simulations
/// </summary>
[DataContract]
public partial class Simulations : IEquatable<Simulations>
{
/// <summary>
/// Initializes a new instance of the <see cref="Simulations" /> class.
/// </summary>
/// <param name="links">links.</param>
/// <param name="meta">meta.</param>
/// <param name="embedded">embedded.</param>
public Simulations(CollectionLinks links = default(CollectionLinks), CollectionMeta meta = default(CollectionMeta), List<Simulation> embedded = default(List<Simulation>))
{
this.Links = links;
this.Meta = meta;
this.Embedded = embedded;
}
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name="_links", EmitDefaultValue=false)]
public CollectionLinks Links { get; set; }
/// <summary>
/// Gets or Sets Meta
/// </summary>
[DataMember(Name="_meta", EmitDefaultValue=false)]
public CollectionMeta Meta { get; set; }
/// <summary>
/// Gets or Sets Embedded
/// </summary>
[DataMember(Name="_embedded", EmitDefaultValue=false)]
public List<Simulation> Embedded { 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 Simulations {\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append(" Meta: ").Append(Meta).Append("\n");
sb.Append(" Embedded: ").Append(Embedded).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Simulations);
}
/// <summary>
/// Returns true if Simulations instances are equal
/// </summary>
/// <param name="input">Instance of Simulations to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Simulations input)
{
if (input == null)
return false;
return
(
this.Links == input.Links ||
(this.Links != null &&
this.Links.Equals(input.Links))
) &&
(
this.Meta == input.Meta ||
(this.Meta != null &&
this.Meta.Equals(input.Meta))
) &&
(
this.Embedded == input.Embedded ||
this.Embedded != null &&
input.Embedded != null &&
this.Embedded.SequenceEqual(input.Embedded)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Links != null)
hashCode = hashCode * 59 + this.Links.GetHashCode();
if (this.Meta != null)
hashCode = hashCode * 59 + this.Meta.GetHashCode();
if (this.Embedded != null)
hashCode = hashCode * 59 + this.Embedded.GetHashCode();
return hashCode;
}
}
}
}
| 32.088435 | 178 | 0.529786 | [
"MIT"
] | SimScaleGmbH/simscale-csharp-sdk | src/SimScale.Sdk/Model/Simulations.cs | 4,717 | C# |
using System;
using System.Windows.Forms;
namespace Mike.Utilities.Desktop
{
public static class ValorPago
{
public static decimal ValorPagoPeloCliente(TextBox txt)
{
try
{
decimal valorPago = 0;
valorPago = txt.Text == "" ? 0 : Convert.ToDecimal(txt.Text);
return valorPago;
}
catch (CustomException erro)
{
throw new CustomException(erro.Message);
}
catch (Exception erro)
{
throw new Exception(erro.Message);
}
}
}
}
| 20.6875 | 77 | 0.478852 | [
"MIT"
] | mikemajesty/Minha-Dll | Mike.Utilities.Desktop/ValorPago.cs | 664 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Protocol;
using Microsoft.Azure.Commands.Batch.Properties;
using Microsoft.Azure.Management.Batch.Models;
using Microsoft.Rest;
using System;
using System.Collections;
using System.Net.Http;
using System.Threading;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
namespace Microsoft.Azure.Commands.Batch
{
/// <summary>
/// Contains Batch account details for use when interacting with the Batch service.
/// </summary>
public class BatchAccountContext
{
private AccountKeyType keyInUse;
private BatchClient batchOMClient;
/// <summary>
/// The account resource Id.
/// </summary>
public string Id { get; private set; }
/// <summary>
/// The account endpoint.
/// </summary>
public string AccountEndpoint { get; private set; }
/// <summary>
/// The primary account key.
/// </summary>
public string PrimaryAccountKey { get; internal set; }
/// <summary>
/// The secondary account key.
/// </summary>
public string SecondaryAccountKey { get; internal set; }
/// <summary>
/// The name of the Batch account.
/// </summary>
public string AccountName { get; protected set; }
/// <summary>
/// The region in which the account was created.
/// </summary>
public string Location { get; private set; }
/// <summary>
/// The name of the resource group that the account resource is under.
/// </summary>
public string ResourceGroupName { get; internal set; }
/// <summary>
/// The subscription Id that the account belongs to.
/// </summary>
public string Subscription { get; private set; }
/// <summary>
/// The provisioning state of the account resource.
/// </summary>
public string State { get; private set; }
/// <summary>
/// The Batch service endpoint.
/// </summary>
public string TaskTenantUrl { get; protected set; }
/// <summary>
/// Tags associated with the account resource.
/// </summary>
public Hashtable Tags { get; private set; }
/// <summary>
/// A string representation of the Tags property.
/// </summary>
public string TagsTable
{
get { return Helpers.FormatTagsTable(Tags); }
}
/// <summary>
/// The core quota for this Batch account.
/// </summary>
public int CoreQuota { get; private set; }
/// <summary>
/// The pool quota for this Batch account.
/// </summary>
public int PoolQuota { get; private set; }
/// <summary>
/// The active job and job schedule quota for this Batch account.
/// </summary>
public int ActiveJobAndJobScheduleQuota { get; private set; }
/// <summary>
/// Contains information about the auto storage associated with a Batch account.
/// </summary>
public AutoStorageProperties AutoStorageProperties { get; set; }
/// <summary>
/// The key to use when interacting with the Batch service. Be default, the primary key will be used.
/// </summary>
public AccountKeyType KeyInUse
{
get { return this.keyInUse; }
set
{
if (value != this.keyInUse)
{
this.batchOMClient.Dispose();
this.batchOMClient = null;
}
this.keyInUse = value;
}
}
internal BatchClient BatchOMClient
{
get
{
if (this.batchOMClient == null)
{
if ((KeyInUse == AccountKeyType.Primary && string.IsNullOrEmpty(PrimaryAccountKey)) ||
(KeyInUse == AccountKeyType.Secondary && string.IsNullOrEmpty(SecondaryAccountKey)))
{
throw new InvalidOperationException(string.Format(Resources.KeyNotPresent, KeyInUse));
}
string key = KeyInUse == AccountKeyType.Primary ? PrimaryAccountKey : SecondaryAccountKey;
BatchServiceClient restClient = CreateBatchRestClient(TaskTenantUrl, AccountName, key);
this.batchOMClient = Microsoft.Azure.Batch.BatchClient.Open(restClient);
}
return this.batchOMClient;
}
}
internal BatchAccountContext()
{
this.KeyInUse = AccountKeyType.Primary;
}
internal BatchAccountContext(string accountEndpoint) : this()
{
this.AccountEndpoint = accountEndpoint;
}
/// <summary>
/// Take an AccountResource and turn it into a BatchAccountContext
/// </summary>
/// <param name="resource">Resource info returned by RP</param>
/// <returns>Void</returns>
internal void ConvertAccountResourceToAccountContext(AccountResource resource)
{
var accountEndpoint = resource.AccountEndpoint;
if (Uri.CheckHostName(accountEndpoint) != UriHostNameType.Dns)
{
throw new ArgumentException(String.Format(Resources.InvalidEndpointType, accountEndpoint), "AccountEndpoint");
}
this.Id = resource.Id;
this.AccountEndpoint = accountEndpoint;
this.Location = resource.Location;
this.State = resource.ProvisioningState.ToString();
this.Tags = TagsConversionHelper.CreateTagHashtable(resource.Tags);
this.CoreQuota = resource.CoreQuota;
this.PoolQuota = resource.PoolQuota;
this.ActiveJobAndJobScheduleQuota = resource.ActiveJobAndJobScheduleQuota;
if (resource.AutoStorage != null)
{
this.AutoStorageProperties = new AutoStorageProperties()
{
StorageAccountId = resource.AutoStorage.StorageAccountId,
LastKeySync = resource.AutoStorage.LastKeySync,
};
}
// extract the host and strip off the account name for the TaskTenantUrl and AccountName
var hostParts = accountEndpoint.Split('.');
this.AccountName = hostParts[0];
this.TaskTenantUrl = Uri.UriSchemeHttps + Uri.SchemeDelimiter + accountEndpoint;
// get remaining fields from Id which looks like:
// /subscriptions/4a06fe24-c197-4353-adc1-058d1a51924e/resourceGroups/clwtest/providers/Microsoft.Batch/batchAccounts/clw
var idParts = resource.Id.Split('/');
if (idParts.Length < 5)
{
throw new ArgumentException(String.Format(Resources.InvalidResourceId, resource.Id), "Id");
}
this.Subscription = idParts[2];
this.ResourceGroupName = idParts[4];
}
/// <summary>
/// Create a new BAC and fill it in
/// </summary>
/// <param name="resource">Resource info returned by RP</param>
/// <returns>new instance of BatchAccountContext</returns>
internal static BatchAccountContext ConvertAccountResourceToNewAccountContext(AccountResource resource)
{
var baContext = new BatchAccountContext();
baContext.ConvertAccountResourceToAccountContext(resource);
return baContext;
}
protected virtual BatchServiceClient CreateBatchRestClient(string url, string accountName, string key, DelegatingHandler handler = default(DelegatingHandler))
{
ServiceClientCredentials credentials = new Microsoft.Azure.Batch.Protocol.BatchSharedKeyCredential(accountName, key);
BatchServiceClient restClient = handler == null ? new BatchServiceClient(new Uri(url), credentials) : new BatchServiceClient(new Uri(url), credentials, handler);
restClient.HttpClient.DefaultRequestHeaders.UserAgent.Add(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.UserAgentValue);
restClient.SetRetryPolicy(null); //Force there to be no retries
restClient.HttpClient.Timeout = Timeout.InfiniteTimeSpan; //Client side timeout will be set per-request
return restClient;
}
}
}
| 39.645833 | 174 | 0.583079 | [
"MIT"
] | udayupasani/Azure-Vault | src/ResourceManager/AzureBatch/Commands.Batch/Models/BatchAccountContext.cs | 9,278 | C# |
namespace Modules.AQE.AQI
{
/// <summary>
/// 空气质量指数相关信息
/// </summary>
public class AQIAbout
{
/// <summary>
/// 空气质量指数上限
/// </summary>
public double AQIUpperLimit { get; set; }
/// <summary>
/// 空气质量指数级别
/// </summary>
public string Level { get; set; }
/// <summary>
/// 空气质量指数类别
/// </summary>
public string Type { get; set; }
/// <summary>
/// 空气质量指数表示颜色
/// </summary>
public string Color { get; set; }
/// <summary>
/// 对健康影响情况
/// </summary>
public string Effect { get; set; }
/// <summary>
/// 建议采取的措施
/// </summary>
public string Measure { get; set; }
/// <summary>
/// 空气质量等级数字表示
/// </summary>
public int NumberLevel { get; set; }
}
}
| 23.578947 | 49 | 0.440848 | [
"MIT"
] | xin2015/Modules | Modules/Modules.AQE/AQI/AQIAbout.cs | 1,034 | C# |
#pragma checksum "C:\Users\Home\Documents\GitHub\DBS-Fall-19-Bitbuilder\BitBuilder_v1\product_search.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "0DF02A05342F067FF11EF72DF3FF51C0"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BitBuilder_v1
{
partial class product_search :
global::Windows.UI.Xaml.Controls.Page,
global::Windows.UI.Xaml.Markup.IComponentConnector,
global::Windows.UI.Xaml.Markup.IComponentConnector2
{
/// <summary>
/// Connect()
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void Connect(int connectionId, object target)
{
switch(connectionId)
{
case 2: // product_search.xaml line 13
{
this.prod_namebox = (global::Windows.UI.Xaml.Controls.TextBox)(target);
}
break;
case 3: // product_search.xaml line 14
{
this.categ_box = (global::Windows.UI.Xaml.Controls.ComboBox)(target);
((global::Windows.UI.Xaml.Controls.ComboBox)this.categ_box).Loaded += this.categ_box_Loaded;
}
break;
case 4: // product_search.xaml line 17
{
this.search_btn = (global::Windows.UI.Xaml.Controls.Button)(target);
((global::Windows.UI.Xaml.Controls.Button)this.search_btn).Click += this.search_btn_Click;
}
break;
case 5: // product_search.xaml line 18
{
this.close_bttn = (global::Windows.UI.Xaml.Controls.Button)(target);
((global::Windows.UI.Xaml.Controls.Button)this.close_bttn).Click += this.close_bttn_Click;
}
break;
case 6: // product_search.xaml line 19
{
this.cart_add_bttn_Copy = (global::Windows.UI.Xaml.Controls.Button)(target);
((global::Windows.UI.Xaml.Controls.Button)this.cart_add_bttn_Copy).Click += this.cart_add_bttn_Copy_Click;
}
break;
case 7: // product_search.xaml line 21
{
this.search_grid = (global::Microsoft.Toolkit.Uwp.UI.Controls.DataGrid)(target);
}
break;
case 8: // product_search.xaml line 22
{
this.buildid_box = (global::Windows.UI.Xaml.Controls.TextBox)(target);
}
break;
default:
break;
}
this._contentLoaded = true;
}
/// <summary>
/// GetBindingConnector(int connectionId, object target)
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::Windows.UI.Xaml.Markup.IComponentConnector GetBindingConnector(int connectionId, object target)
{
global::Windows.UI.Xaml.Markup.IComponentConnector returnValue = null;
return returnValue;
}
}
}
| 43.6 | 183 | 0.545602 | [
"MIT"
] | AALAM98mod100/DBS-Fall-19-Bitbuilder | BitBuilder_v1/obj/x86/Debug/product_search.g.cs | 3,708 | C# |
#region License
// Copyright (c) 2018-2021, exomia
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#endregion
#pragma warning disable CA2211 // Non-constant fields should not be visible
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using Exomia.Vulkan.Api.SourceGenerator;
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming
namespace Exomia.Vulkan.Api.Core.Extensions.NV
{
[Obsolete(
"Deprecated without replacement", false,
UrlFormat = "https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_NV_glsl_shader.html#_deprecation_state")]
[VkExtGenerator]
public static partial class VkNvGlslShader
{
public const int VK_NV_GLSL_SHADER = 1;
public const int VK_NV_GLSL_SHADER_SPEC_VERSION = 1;
public const string VK_NV_GLSL_SHADER_EXTENSION_NAME = "VK_NV_glsl_shader";
}
} | 34.677419 | 135 | 0.737674 | [
"BSD-3-Clause"
] | exomia/vulkan-api | src/Exomia.Vulkan.Api.Core/Extensions/NV/Vk.NV.GlslShader.cs | 1,075 | C# |
using UnityEngine;
using System.Collections;
public class deactivate : MonoBehaviour {
public GameObject a;
public GameObject b;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (PlayerPrefs.GetInt ("task111c", 0) == 1) {
Destroy(a);
Destroy(b);
}
}
}
| 16.65 | 48 | 0.660661 | [
"Apache-2.0"
] | dtmakm27/Loony-s-Quest | Assets/deactivate.cs | 335 | C# |
using UnityEngine;
namespace TowerDefense
{
[CreateAssetMenu(menuName = "TowerDefense/GameTileContentFactory")]
public class GameTileContentFactory : GameObjectFactory
{
[SerializeField] private GameTileContent destinationPrefab = default;
[SerializeField] private GameTileContent emptyPrefab = default;
[SerializeField] private GameTileContent wallPrefab = default;
[SerializeField] private GameTileContent spawnPointPrefab = default;
[SerializeField] private Tower[] towerPrefabs = default;
public void Reclaim(GameTileContent content) {
Debug.Assert(content.OriginFactory == this, "Wrong factory reclaimed!");
Destroy(content.gameObject);
}
public GameTileContent Get(GameTileContentType type) {
switch (type) {
case GameTileContentType.Destination: return Get(destinationPrefab);
case GameTileContentType.Empty: return Get(emptyPrefab);
case GameTileContentType.Wall: return Get(wallPrefab);
case GameTileContentType.SpawnPoint: return Get(spawnPointPrefab);
}
Debug.Assert(false, "Unsupported type: " + type);
return null;
}
public Tower Get(TowerType type) {
Debug.Assert((int)type < towerPrefabs.Length, "Unsupported tower type!");
Tower prefab = towerPrefabs[(int)type];
Debug.Assert(type == prefab.TowerType, "Tower prefab at wrong index!");
return Get(prefab);
}
T Get<T>(T prefab) where T : GameTileContent {
T instance = CreateGameObjectInstance(prefab);
instance.OriginFactory = this;
return instance;
}
}
} | 35.139535 | 76 | 0.754467 | [
"MIT"
] | yeonhong/CatlikeCodingTutorials | Assets/4. Tower Defense/Scripts/GameTileContentFactory.cs | 1,513 | C# |
namespace Haven.Protocols.Legacy.Messages
{
public class PartyUpdate
{
public int[] MemberIds { get; set; }
}
} | 16.714286 | 42 | 0.709402 | [
"MIT"
] | k-t/haven-dotnet | Source/Haven.Protocols.Legacy/Messages/PartyUpdate.cs | 119 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#if !NO_PERF
using System;
namespace System.Reactive.Linq.ObservableImpl
{
class All<TSource> : Producer<bool>
{
private readonly IObservable<TSource> _source;
private readonly Func<TSource, bool> _predicate;
public All(IObservable<TSource> source, Func<TSource, bool> predicate)
{
_source = source;
_predicate = predicate;
}
protected override IDisposable Run(IObserver<bool> observer, IDisposable cancel, Action<IDisposable> setSink)
{
var sink = new _(this, observer, cancel);
setSink(sink);
return _source.SubscribeSafe(sink);
}
class _ : Sink<bool>, IObserver<TSource>
{
private readonly All<TSource> _parent;
public _(All<TSource> parent, IObserver<bool> observer, IDisposable cancel)
: base(observer, cancel)
{
_parent = parent;
}
public void OnNext(TSource value)
{
var res = false;
try
{
res = _parent._predicate(value);
}
catch (Exception ex)
{
base._observer.OnError(ex);
base.Dispose();
return;
}
if (!res)
{
base._observer.OnNext(false);
base._observer.OnCompleted();
base.Dispose();
}
}
public void OnError(Exception error)
{
base._observer.OnError(error);
base.Dispose();
}
public void OnCompleted()
{
base._observer.OnNext(true);
base._observer.OnCompleted();
base.Dispose();
}
}
}
}
#endif | 28.465753 | 133 | 0.488932 | [
"Apache-2.0"
] | Distrotech/mono | external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/All.cs | 2,080 | C# |
// Licensed to Finnovation Labs Limited under one or more agreements.
// Finnovation Labs Limited licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FinnovationLabs.OpenBanking.Library.Connector.Http;
using FinnovationLabs.OpenBanking.Library.Connector.Instrumentation;
using FluentAssertions;
using NSubstitute;
using Xunit;
namespace FinnovationLabs.OpenBanking.Library.Connector.IntegrationTests.LocalMockTests.Http
{
public class ApiClientTests
{
[Theory]
[InlineData("https://www.google.com/")]
public async Task ApiClient_SendAsync_Success(string url)
{
IHttpRequestBuilder b = new HttpRequestBuilder()
.SetMethod(HttpMethod.Get)
.SetUri(url);
HttpRequestMessage req = b.Create();
using (HttpClient http = new HttpClient())
{
ApiClient api = new ApiClient(
Substitute.For<IInstrumentationClient>(),
http);
HttpResponseMessage r = await api.LowLevelSendAsync(req);
r.StatusCode.Should().Be(HttpStatusCode.OK);
}
}
[Theory]
[InlineData("https://github.com/a5b2a8a9-1220-4aa4-aa83-0036a7bd1e69")]
public async Task ApiClient_SendAsync_NotFound(string url)
{
IHttpRequestBuilder b = new HttpRequestBuilder()
.SetMethod(HttpMethod.Get)
.SetUri(url);
HttpRequestMessage req = b.Create();
using (HttpClient http = new HttpClient())
{
ApiClient api = new ApiClient(
Substitute.For<IInstrumentationClient>(),
http);
HttpResponseMessage r = await api.LowLevelSendAsync(req);
r.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
}
[Theory]
[InlineData("https://a5b2a8a9-1220-4aa4-aa83-0036a7bd1e69.com/stuff")]
public void ApiClient_SendAsync_Failure(string url)
{
HttpRequestMessage req = new HttpRequestBuilder()
.SetMethod(HttpMethod.Get)
.SetUri(url)
.Create();
using HttpClient http = new HttpClient();
Func<Task> a = async () =>
{
ApiClient api = new ApiClient(
Substitute.For<IInstrumentationClient>(),
http);
HttpResponseMessage r = await api.LowLevelSendAsync(req);
};
a.Should().ThrowAsync<HttpRequestException>();
}
}
}
| 32.705882 | 92 | 0.592086 | [
"MIT"
] | finlabsuk/open-banking-connector-csharp | test/OpenBanking.Library.Connector.IntegrationTests/LocalMockTests/Http/ApiClientTests.cs | 2,782 | C# |
namespace rt
{
public class Light
{
public Vector Position { get; set; }
public CustomRGBColor Ambient { get; set; }
public CustomRGBColor Diffuse { get; set; }
public CustomRGBColor Specular { get; set; }
public double Intensity { get; set; }
public Light(Vector position, CustomRGBColor ambient, CustomRGBColor diffuse, CustomRGBColor specular, double intensity)
{
Position = new Vector(position);
Ambient = new CustomRGBColor(ambient);
Diffuse = new CustomRGBColor(diffuse);
Specular = new CustomRGBColor(specular);
Intensity = intensity;
}
}
} | 34.25 | 128 | 0.616058 | [
"MIT"
] | PaulMardar/mi-casa-es-su-casa | C#/ray-tracer-PaulMardar/Light.cs | 687 | 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.
#if DNX451
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#endif
using System.Threading.Tasks;
#if DNX451
using Moq;
#endif
using Xunit;
namespace Microsoft.AspNet.Mvc.ModelBinding.Test
{
public class CollectionModelBinderTest
{
#if DNX451
[Fact]
public async Task BindComplexCollectionFromIndexes_FiniteIndexes()
{
// Arrange
var valueProvider = new SimpleHttpValueProvider
{
{ "someName[foo]", "42" },
{ "someName[baz]", "200" }
};
var bindingContext = GetModelBindingContext(valueProvider);
var binder = new CollectionModelBinder<int>();
// Act
var boundCollection = await binder.BindComplexCollectionFromIndexes(bindingContext, new[] { "foo", "bar", "baz" });
// Assert
Assert.Equal(new[] { 42, 0, 200 }, boundCollection.ToArray());
}
[Fact]
public async Task BindComplexCollectionFromIndexes_InfiniteIndexes()
{
// Arrange
var valueProvider = new SimpleHttpValueProvider
{
{ "someName[0]", "42" },
{ "someName[1]", "100" },
{ "someName[3]", "400" }
};
var bindingContext = GetModelBindingContext(valueProvider);
var binder = new CollectionModelBinder<int>();
// Act
var boundCollection = await binder.BindComplexCollectionFromIndexes(bindingContext, indexNames: null);
// Assert
Assert.Equal(new[] { 42, 100 }, boundCollection.ToArray());
}
[Fact]
public async Task BindModel_ComplexCollection()
{
// Arrange
var valueProvider = new SimpleHttpValueProvider
{
{ "someName.index", new[] { "foo", "bar", "baz" } },
{ "someName[foo]", "42" },
{ "someName[bar]", "100" },
{ "someName[baz]", "200" }
};
var bindingContext = GetModelBindingContext(valueProvider);
var binder = new CollectionModelBinder<int>();
// Act
var retVal = await binder.BindModelAsync(bindingContext);
// Assert
Assert.Equal(new[] { 42, 100, 200 }, ((List<int>)retVal.Model).ToArray());
}
[Fact]
public async Task BindModel_SimpleCollection()
{
// Arrange
var valueProvider = new SimpleHttpValueProvider
{
{ "someName", new[] { "42", "100", "200" } }
};
var bindingContext = GetModelBindingContext(valueProvider);
var binder = new CollectionModelBinder<int>();
// Act
var retVal = await binder.BindModelAsync(bindingContext);
// Assert
Assert.NotNull(retVal);
Assert.Equal(new[] { 42, 100, 200 }, ((List<int>)retVal.Model).ToArray());
}
#endif
[Fact]
public async Task BindSimpleCollection_RawValueIsEmptyCollection_ReturnsEmptyList()
{
// Arrange
var binder = new CollectionModelBinder<int>();
var context = new ModelBindingContext()
{
OperationBindingContext = new OperationBindingContext()
{
MetadataProvider = TestModelMetadataProvider.CreateDefaultProvider(),
},
};
// Act
var boundCollection = await binder.BindSimpleCollection(context, rawValue: new object[0], culture: null);
// Assert
Assert.NotNull(boundCollection);
Assert.Empty(boundCollection);
}
[Fact]
public async Task BindSimpleCollection_RawValueIsNull_ReturnsNull()
{
// Arrange
var binder = new CollectionModelBinder<int>();
// Act
var boundCollection = await binder.BindSimpleCollection(bindingContext: null, rawValue: null, culture: null);
// Assert
Assert.Null(boundCollection);
}
#if DNX451
[Fact]
public async Task BindSimpleCollection_SubBindingSucceeds()
{
// Arrange
var culture = new CultureInfo("fr-FR");
var bindingContext = GetModelBindingContext(new SimpleHttpValueProvider());
Mock.Get<IModelBinder>(bindingContext.OperationBindingContext.ModelBinder)
.Setup(o => o.BindModelAsync(It.IsAny<ModelBindingContext>()))
.Returns((ModelBindingContext mbc) =>
{
Assert.Equal("someName", mbc.ModelName);
return Task.FromResult(new ModelBindingResult(42, mbc.ModelName, true));
});
var modelBinder = new CollectionModelBinder<int>();
// Act
var boundCollection = await modelBinder.BindSimpleCollection(bindingContext, new int[1], culture);
// Assert
Assert.Equal(new[] { 42 }, boundCollection.ToArray());
}
private static ModelBindingContext GetModelBindingContext(IValueProvider valueProvider)
{
var metadataProvider = new EmptyModelMetadataProvider();
var bindingContext = new ModelBindingContext
{
ModelMetadata = metadataProvider.GetMetadataForType(typeof(int)),
ModelName = "someName",
ValueProvider = valueProvider,
OperationBindingContext = new OperationBindingContext
{
ModelBinder = CreateIntBinder(),
MetadataProvider = metadataProvider
}
};
return bindingContext;
}
private static IModelBinder CreateIntBinder()
{
Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
mockIntBinder
.Setup(o => o.BindModelAsync(It.IsAny<ModelBindingContext>()))
.Returns(async (ModelBindingContext mbc) =>
{
var value = await mbc.ValueProvider.GetValueAsync(mbc.ModelName);
if (value != null)
{
var model = value.ConvertTo(mbc.ModelType);
return new ModelBindingResult(model, mbc.ModelName, true);
}
return null;
});
return mockIntBinder.Object;
}
#endif
}
}
| 34.543147 | 127 | 0.554739 | [
"Apache-2.0"
] | walkeeperY/ManagementSystem | test/Microsoft.AspNet.Mvc.ModelBinding.Test/Binders/CollectionModelBinderTest.cs | 6,807 | C# |
namespace Microsoft.Owin.Security.ApiKey
{
/// <summary>
/// Options which control the behaviour of the authentication middleware.
/// </summary>
public sealed class ApiKeyAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// The object provided by the application to process events raised by the API key
/// authentication middleware. The application must create an instance of
/// <c>ApiKeyAuthenticationProvider</c> and assign delegates to the mandatory events.
/// </summary>
public ApiKeyAuthenticationProvider Provider;
/// <summary>
/// Creates an instance of API key authentication options with default values.
/// </summary>
public ApiKeyAuthenticationOptions() : base("API Key")
{ }
/// <summary>
/// The header that shall contain the authentication data. Defaults to "Authorization".
/// <para>
/// An example header using the <see cref="ApiKeyAuthenticationOptions"/> defaults would be:
/// </para>
/// <para>Authorization: ApiKey 4fb4e33c83e5d026e8745102b72f10590f48e94af107db15074c799589a4753d</para>
/// </summary>
public string Header { get; set; } = "Authorization";
/// <summary>
/// The key of the key/value pair that represents the authentication type and its data.
/// Defaults to "ApiKey".
/// <para>
/// An example header using the <see cref="ApiKeyAuthenticationOptions"/> defaults would be:
/// </para>
/// <para>Authorization: ApiKey 4fb4e33c83e5d026e8745102b72f10590f48e94af107db15074c799589a4753d</para>
/// </summary>
public string HeaderKey { get; set; } = "ApiKey";
}
}
| 43.04878 | 111 | 0.644193 | [
"Apache-2.0"
] | GoBrightBV/Microsoft.Owin.Security.ApiKey | src/Microsoft.Owin.Security.ApiKey/ApiKeyAuthenticationOptions.cs | 1,767 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dragablz")]
[assembly: AssemblyDescription("Dragable tabable")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulholland Software Ltd/James Willock")]
[assembly: AssemblyProduct("Dragablz")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: XmlnsPrefix("http://dragablz.net/winfx/xaml/dragablz", "dragablz")]
[assembly: XmlnsDefinition("http://dragablz.net/winfx/xaml/dragablz",
"Dragablz")]
[assembly: XmlnsPrefix("http://dragablz.net/winfx/xaml/dockablz", "dockablz")]
[assembly: XmlnsDefinition("http://dragablz.net/winfx/xaml/dockablz",
"Dragablz.Dockablz")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: InternalsVisibleTo("Dragablz.Test")] | 42.03125 | 96 | 0.757249 | [
"MIT"
] | ChristianGutman/Dependencies | third_party/Dragablz/Dragablz/Properties/AssemblyInfo.cs | 2,693 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
namespace EnterpriseServerless.FunctionApp
{
public class LoaderIO
{
private static IConfigurationRoot _configuration { set; get; }
private readonly IConfigurationRefresher _configurationRefresher;
public LoaderIO(
IConfigurationRoot configuration,
IConfigurationRefresher configurationRefresher)
{
_configuration = configuration;
_configurationRefresher = configurationRefresher;
}
[FunctionName(nameof(LoaderIO))]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ExecutionContext context,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
await _configurationRefresher.TryRefreshAsync();
string loaderIOVerificationToken = _configuration["EnterpriseServerless:LoaderIO_VerificationToken"];
string responseMessage = string.IsNullOrEmpty(loaderIOVerificationToken)
? "This HTTP triggered function executed successfully, however its missing the verification token."
: loaderIOVerificationToken;
return new OkObjectResult(responseMessage);
}
}
}
| 35.829787 | 115 | 0.712589 | [
"MIT"
] | calloncampbell/Enterprise-Serverless-Demo | EnterpriseServerless.FunctionApp/Functions/HttpTrigger/LoaderIO.cs | 1,684 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Iai.V20180301.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class VerifyPersonRequest : AbstractModel
{
/// <summary>
/// 图片 base64 数据。
/// 若图片中包含多张人脸,只选取其中人脸面积最大的人脸。
/// 支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
/// </summary>
[JsonProperty("Image")]
public string Image{ get; set; }
/// <summary>
/// 图片的 Url 。 图片的 Url、Image必须提供一个,如果都提供,只使用 Url。
/// 图片存储于腾讯云的Url可保障更高下载速度和稳定性,建议图片存储于腾讯云。
/// 非腾讯云存储的Url速度和稳定性可能受一定影响。
/// 若图片中包含多张人脸,只选取其中人脸面积最大的人脸。
/// 支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
/// </summary>
[JsonProperty("Url")]
public string Url{ get; set; }
/// <summary>
/// 待验证的人员ID。人员ID具体信息请参考人员库管理相关接口。
/// </summary>
[JsonProperty("PersonId")]
public string PersonId{ get; set; }
/// <summary>
/// 图片质量控制。
/// 0: 不进行控制;
/// 1:较低的质量要求,图像存在非常模糊,眼睛鼻子嘴巴遮挡至少其中一种或多种的情况;
/// 2: 一般的质量要求,图像存在偏亮,偏暗,模糊或一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,至少其中三种的情况;
/// 3: 较高的质量要求,图像存在偏亮,偏暗,一般模糊,眉毛遮挡,脸颊遮挡,下巴遮挡,其中一到两种的情况;
/// 4: 很高的质量要求,各个维度均为最好或最多在某一维度上存在轻微问题;
/// 默认 0。
/// 若图片质量不满足要求,则返回结果中会提示图片质量检测不符要求。
/// </summary>
[JsonProperty("QualityControl")]
public ulong? QualityControl{ get; set; }
/// <summary>
/// 是否开启图片旋转识别支持。0为不开启,1为开启。默认为0。本参数的作用为,当图片中的人脸被旋转且图片没有exif信息时,如果不开启图片旋转识别支持则无法正确检测、识别图片中的人脸。若您确认图片包含exif信息或者您确认输入图中人脸不会出现被旋转情况,请不要开启本参数。开启后,整体耗时将可能增加数百毫秒。
/// </summary>
[JsonProperty("NeedRotateDetection")]
public ulong? NeedRotateDetection{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Image", this.Image);
this.SetParamSimple(map, prefix + "Url", this.Url);
this.SetParamSimple(map, prefix + "PersonId", this.PersonId);
this.SetParamSimple(map, prefix + "QualityControl", this.QualityControl);
this.SetParamSimple(map, prefix + "NeedRotateDetection", this.NeedRotateDetection);
}
}
}
| 35.164706 | 164 | 0.623285 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Iai/V20180301/Models/VerifyPersonRequest.cs | 4,077 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace DilMS_UI.Client
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.291667 | 99 | 0.588336 | [
"Apache-2.0"
] | kwkau/DilMS-UI | DilMS-UI.Client/App_Start/RouteConfig.cs | 585 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// class SameEnemiesWaveConfig
///
/// The class represents an enemies wave where all enemies use same prefab
/// </summary>
[CreateAssetMenu(fileName = "SameEnemiesWave_Config", menuName = "Enemies/Same Enemies Wave Config", order = 1)]
public class SameEnemiesWaveConfig : WaveConfig
{
[SerializeField]
protected uint mEnemiesCount;
[SerializeField]
protected GameObject mEnemyPrefab;
public override GameObject this[int index]
{
get
{
return mEnemyPrefab;
}
}
public override uint EnemiesCount => mEnemiesCount;
} | 20.9 | 112 | 0.748006 | [
"Apache-2.0"
] | bnoazx005/TowerDefensePrototype | Assets/Scripts/SameEnemiesWaveConfig.cs | 627 | C# |
using System.Collections.Generic;
namespace AndroidBinderator
{
public class NuGetDependencyModel
{
public bool IsProjectReference { get; set; }
public string NuGetPackageId { get; set; }
public string NuGetVersionBase { get; set; }
public string NuGetVersionSuffix { get; set; }
public string NuGetVersion =>
!IsProjectReference || string.IsNullOrWhiteSpace(NuGetVersionSuffix)
? NuGetVersionBase
: NuGetVersionBase + NuGetVersionSuffix;
public MavenArtifactModel MavenArtifact { get; set; }
public Dictionary<string, string> Metadata { get; set; } = new Dictionary<string, string>();
}
}
| 27.130435 | 94 | 0.746795 | [
"MIT"
] | 772801206/MyXamarinComponents | Util/Xamarin.AndroidBinderator/Xamarin.AndroidBinderator/Model/NuGetDependencyModel.cs | 626 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SeamothBrineResist;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SeamothBrineResist")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SeamothBrineResist")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91da81bf-73f9-42d0-b002-a3e63510d6b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(Main.version)]
[assembly: AssemblyFileVersion(Main.version)]
| 38.763158 | 85 | 0.739986 | [
"MIT"
] | DaWrecka/MetiousSubnauticaMods | SeamothBrineResist/Properties/AssemblyInfo.cs | 1,476 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Elasticsearch.Net.Serialization;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Parsing;
namespace Serilog.Sinks.ElasticSearch
{
/// <summary>
/// Custom Json formatter that respects the configured property name handling and forces 'Timestamp' to @timestamp
/// </summary>
public class ElasticsearchJsonFormatter : JsonFormatter
{
readonly IElasticsearchSerializer _serializer;
readonly bool _inlineFields;
/// <summary>
/// Construct a <see cref="ElasticsearchJsonFormatter"/>.
/// </summary>
/// <param name="omitEnclosingObject">If true, the properties of the event will be written to
/// the output without enclosing braces. Otherwise, if false, each event will be written as a well-formed
/// JSON object.</param>
/// <param name="closingDelimiter">A string that will be written after each log event is formatted.
/// If null, <see cref="Environment.NewLine"/> will be used. Ignored if <paramref name="omitEnclosingObject"/>
/// is true.</param>
/// <param name="renderMessage">If true, the message will be rendered and written to the output as a
/// property named RenderedMessage.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <param name="serializer">Inject a serializer to force objects to be serialized over being ToString()</param>
/// <param name="inlineFields">When set to true values will be written at the root of the json document</param>
public ElasticsearchJsonFormatter(bool omitEnclosingObject = false,
string closingDelimiter = null,
bool renderMessage = false,
IFormatProvider formatProvider = null,
IElasticsearchSerializer serializer = null,
bool inlineFields = false)
: base(omitEnclosingObject, closingDelimiter, renderMessage, formatProvider)
{
_serializer = serializer;
_inlineFields = inlineFields;
}
/// <summary>
/// Writes out individual renderings of attached properties
/// </summary>
protected override void WriteRenderings(IGrouping<string, PropertyToken>[] tokensWithFormat, IDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
output.Write(",\"{0}\":{{", "renderings");
WriteRenderingsValues(tokensWithFormat, properties, output);
output.Write("}");
}
/// <summary>
/// Writes out the attached properties
/// </summary>
protected override void WriteProperties(IDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
if (!_inlineFields)
output.Write(",\"{0}\":{{", "fields");
else
output.Write(",");
WritePropertiesValues(properties, output);
if (!_inlineFields)
output.Write("}");
}
/// <summary>
/// Writes out the attached exception
/// </summary>
protected override void WriteException(Exception exception, ref string delim, TextWriter output)
{
WriteJsonProperty("exception", exception, ref delim, output);
}
/// <summary>
/// (Optionally) writes out the rendered message
/// </summary>
protected override void WriteRenderedMessage(string message, ref string delim, TextWriter output)
{
WriteJsonProperty("renderedMessage", message, ref delim, output);
}
/// <summary>
/// Writes out the message template for the logevent.
/// </summary>
protected override void WriteMessageTemplate(string template, ref string delim, TextWriter output)
{
WriteJsonProperty("messageTemplate", template, ref delim, output);
}
/// <summary>
/// Writes out the log level
/// </summary>
protected override void WriteLevel(LogEventLevel level, ref string delim, TextWriter output)
{
var stringLevel = Enum.GetName(typeof(LogEventLevel), level);
WriteJsonProperty("level", stringLevel, ref delim, output);
}
/// <summary>
/// Writes out the log timestamp
/// </summary>
protected override void WriteTimestamp(DateTimeOffset timestamp, ref string delim, TextWriter output)
{
WriteJsonProperty("@timestamp", timestamp, ref delim, output);
}
/// <summary>
/// Allows a subclass to write out objects that have no configured literal writer.
/// </summary>
/// <param name="value">The value to be written as a json construct</param>
/// <param name="output">The writer to write on</param>
protected override void WriteLiteralValue(object value, TextWriter output)
{
if (_serializer != null)
{
var json = _serializer.Serialize(value, SerializationFormatting.None);
var jsonString = Encoding.UTF8.GetString(json);
output.Write(jsonString);
return;
}
base.WriteLiteralValue(value, output);
}
}
}
| 41.067164 | 174 | 0.618027 | [
"Apache-2.0"
] | blachniet/serilog | src/Serilog.Sinks.ElasticSearch/Sinks/ElasticSearch/ElasticsearchJsonFormatter-net40.cs | 5,505 | 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>
//------------------------------------------------------------------------------
namespace Adan.Client.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("100")]
public int MainOutputWindowSecondaryScrollHeight {
get {
return ((int)(this["MainOutputWindowSecondaryScrollHeight"]));
}
set {
this["MainOutputWindowSecondaryScrollHeight"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("localhost")]
public string ConnectHostName {
get {
return ((string)(this["ConnectHostName"]));
}
set {
this["ConnectHostName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("4000")]
public int ConnectPort {
get {
return ((int)(this["ConnectPort"]));
}
set {
this["ConnectPort"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Default")]
public string ProfileName {
get {
return ((string)(this["ProfileName"]));
}
set {
this["ProfileName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool AutoReconnect {
get {
return ((bool)(this["AutoReconnect"]));
}
set {
this["AutoReconnect"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool AutoClearInput {
get {
return ((bool)(this["AutoClearInput"]));
}
set {
this["AutoClearInput"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("2")]
public int MinLengthHistory {
get {
return ((int)(this["MinLengthHistory"]));
}
set {
this["MinLengthHistory"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("20")]
public int HistorySize {
get {
return ((int)(this["HistorySize"]));
}
set {
this["HistorySize"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("#")]
public char CommandChar {
get {
return ((char)(this["CommandChar"]));
}
set {
this["CommandChar"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(";")]
public char CommandDelimiter {
get {
return ((char)(this["CommandDelimiter"]));
}
set {
this["CommandDelimiter"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("1")]
public int HistoryCursorPosition {
get {
return ((int)(this["HistoryCursorPosition"]));
}
set {
this["HistoryCursorPosition"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("500")]
public int ScrollBuffer {
get {
return ((int)(this["ScrollBuffer"]));
}
set {
this["ScrollBuffer"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.Specialized.StringCollection CommandsHistory {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["CommandsHistory"]));
}
set {
this["CommandsHistory"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("0")]
public int Folder {
get {
return ((int)(this["Folder"]));
}
set {
this["Folder"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.Specialized.StringCollection MainOutputs {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["MainOutputs"]));
}
set {
this["MainOutputs"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("0")]
public int SettingsFolder {
get {
return ((int)(this["SettingsFolder"]));
}
set {
this["SettingsFolder"] = value;
}
}
}
}
| 38.414747 | 152 | 0.544266 | [
"MIT"
] | TagsRocks/mudclient | Adan.Client/Properties/Settings.Designer.cs | 8,338 | C# |
using System;
namespace Leeax.Web.Components.Theme
{
public class CssKeyAliasFormatter : ICssValueFormatter<KeyAlias>
{
public string Format(Type valueType, KeyAlias value)
=> "var(--" + value.Value + ")";
}
} | 24.4 | 68 | 0.643443 | [
"Apache-2.0"
] | Ieeax/web | src/Leeax.Web.Components.Theme/_CssFormatter/CssKeyAliasFormatter.cs | 246 | 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;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IWorkbookFunctionsHlookupRequest.
/// </summary>
public partial interface IWorkbookFunctionsHlookupRequest : IBaseRequest
{
/// <summary>
/// Gets the request body.
/// </summary>
WorkbookFunctionsHlookupRequestBody RequestBody { get; }
/// <summary>
/// Issues the POST request.
/// </summary>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync();
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsHlookupRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsHlookupRequest Select(string value);
}
}
| 33.032787 | 153 | 0.578164 | [
"MIT"
] | twsouthwick/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsHlookupRequest.cs | 2,015 | 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.
#nullable disable
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using static Interop;
using static Interop.Ole32;
using static Interop.Oleaut32;
namespace System.Windows.Forms.ComponentModel.Com2Interop
{
/// <summary>
/// This is the main worker class of Com2 property interop. It takes an IDispatch Object
/// and translates it's ITypeInfo into Com2PropertyDescriptor objects that are understandable
/// by managed code.
///
/// This class only knows how to process things that are natively in the typeinfo. Other property
/// information such as IPerPropertyBrowsing is handled elsewhere.
/// </summary>
internal class Com2TypeInfoProcessor
{
private static readonly TraceSwitch DbgTypeInfoProcessorSwitch = new TraceSwitch("DbgTypeInfoProcessor", "Com2TypeInfoProcessor: debug Com2 type info processing");
private Com2TypeInfoProcessor()
{
}
private static ModuleBuilder moduleBuilder = null;
private static ModuleBuilder ModuleBuilder
{
get
{
if (moduleBuilder == null)
{
AssemblyName assemblyName = new AssemblyName
{
Name = "COM2InteropEmit"
};
AssemblyBuilder aBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
moduleBuilder = aBuilder.DefineDynamicModule("COM2Interop.Emit");
}
return moduleBuilder;
}
}
private static Hashtable builtEnums;
private static Hashtable processedLibraries;
/// <summary>
/// Given an Object, this attempts to locate its type ifo
/// </summary>
public static ITypeInfo FindTypeInfo(object obj, bool wantCoClass)
{
ITypeInfo pTypeInfo = null;
// This is kind of odd. What's going on here is that if we want the CoClass (e.g. for
// the interface name), we need to look for IProvideClassInfo first, then look for the
// typeinfo from the IDispatch. In the case of many Oleaut32 operations, the CoClass
// doesn't have the interface members on it, although in the shell it usually does, so
// we need to re-order the lookup if we *actually* want the CoClass if it's available.
for (int i = 0; pTypeInfo == null && i < 2; i++)
{
if (wantCoClass == (i == 0))
{
if (obj is IProvideClassInfo pProvideClassInfo)
{
pProvideClassInfo.GetClassInfo(out pTypeInfo);
}
}
else
{
if (obj is IDispatch iDispatch)
{
iDispatch.GetTypeInfo(0, Kernel32.GetThreadLocale(), out pTypeInfo);
}
}
}
return pTypeInfo;
}
/// <summary>
/// Given an Object, this attempts to locate its type info. If it implementes IProvideMultipleClassInfo
/// all available type infos will be returned, otherwise the primary one will be alled.
/// </summary>
public unsafe static ITypeInfo[] FindTypeInfos(object obj, bool wantCoClass)
{
if (obj is IProvideMultipleClassInfo pCI)
{
uint n = 0;
if (pCI.GetMultiTypeInfoCount(&n).Succeeded() && n > 0)
{
var typeInfos = new ITypeInfo[n];
for (uint i = 0; i < n; i++)
{
if (pCI.GetInfoOfIndex(i, MULTICLASSINFO.GETTYPEINFO, out ITypeInfo result, null, null, null, null).Failed())
{
continue;
}
Debug.Assert(result != null, "IProvideMultipleClassInfo::GetInfoOfIndex returned S_OK for ITypeInfo index " + i + ", this is a issue in the object that's being browsed, NOT the property browser.");
typeInfos[i] = result;
}
return typeInfos;
}
}
ITypeInfo temp = FindTypeInfo(obj, wantCoClass);
if (temp != null)
{
return new ITypeInfo[] { temp };
}
return null;
}
/// <summary>
/// Retrieve the dispid of the property that we are to use as the name
/// member. In this case, the grid will put parens around the name.
/// </summary>
public unsafe static DispatchID GetNameDispId(IDispatch obj)
{
DispatchID dispid = DispatchID.UNKNOWN;
string[] names = null;
ComNativeDescriptor cnd = ComNativeDescriptor.Instance;
bool succeeded = false;
// first try to find one with a valid value
cnd.GetPropertyValue(obj, "__id", ref succeeded);
if (succeeded)
{
names = new string[] { "__id" };
}
else
{
cnd.GetPropertyValue(obj, DispatchID.Name, ref succeeded);
if (succeeded)
{
dispid = DispatchID.Name;
}
else
{
cnd.GetPropertyValue(obj, "Name", ref succeeded);
if (succeeded)
{
names = new string[] { "Name" };
}
}
}
// now get the dispid of the one that worked...
if (names != null)
{
DispatchID pDispid = DispatchID.UNKNOWN;
Guid g = Guid.Empty;
HRESULT hr = obj.GetIDsOfNames(&g, names, 1, Kernel32.GetThreadLocale(), &pDispid);
if (hr.Succeeded())
{
dispid = pDispid;
}
}
return dispid;
}
/// <summary>
/// Gets the properties for a given Com2 Object. The returned Com2Properties
/// Object contains the properties and relevant data about them.
/// </summary>
public static Com2Properties GetProperties(object obj)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties");
if (obj == null || !Marshal.IsComObject(obj))
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties returning null: Object is not a com Object");
return null;
}
ITypeInfo[] typeInfos = FindTypeInfos(obj, false);
// oops, looks like this guy doesn't surface any type info
// this is okay, so we just say it has no props
if (typeInfos == null || typeInfos.Length == 0)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties :: Didn't get typeinfo");
return null;
}
int defaultProp = -1;
int temp = -1;
ArrayList propList = new ArrayList();
Guid[] typeGuids = new Guid[typeInfos.Length];
for (int i = 0; i < typeInfos.Length; i++)
{
ITypeInfo ti = typeInfos[i];
if (ti == null)
{
continue;
}
uint[] versions = new uint[2];
Guid typeGuid = GetGuidForTypeInfo(ti, versions);
PropertyDescriptor[] props = null;
bool dontProcess = typeGuid != Guid.Empty && processedLibraries != null && processedLibraries.Contains(typeGuid);
if (dontProcess)
{
CachedProperties cp = (CachedProperties)processedLibraries[typeGuid];
if (versions[0] == cp.MajorVersion && versions[1] == cp.MinorVersion)
{
props = cp.Properties;
if (i == 0 && cp.DefaultIndex != -1)
{
defaultProp = cp.DefaultIndex;
}
}
else
{
dontProcess = false;
}
}
if (!dontProcess)
{
props = InternalGetProperties(obj, ti, DispatchID.MEMBERID_NIL, ref temp);
// only save the default property from the first type Info
if (i == 0 && temp != -1)
{
defaultProp = temp;
}
if (processedLibraries == null)
{
processedLibraries = new Hashtable();
}
if (typeGuid != Guid.Empty)
{
processedLibraries[typeGuid] = new CachedProperties(props, i == 0 ? defaultProp : -1, versions[0], versions[1]);
}
}
if (props != null)
{
propList.AddRange(props);
}
}
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties : returning " + propList.Count.ToString(CultureInfo.InvariantCulture) + " properties");
// done!
Com2PropertyDescriptor[] temp2 = new Com2PropertyDescriptor[propList.Count];
propList.CopyTo(temp2, 0);
return new Com2Properties(obj, temp2, defaultProp);
}
private unsafe static Guid GetGuidForTypeInfo(ITypeInfo typeInfo, uint[] versions)
{
TYPEATTR* pTypeAttr = null;
HRESULT hr = typeInfo.GetTypeAttr(&pTypeAttr);
if (!hr.Succeeded())
{
throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), (int)hr);
}
try
{
if (versions != null)
{
versions[0] = pTypeAttr->wMajorVerNum;
versions[1] = pTypeAttr->wMinorVerNum;
}
return pTypeAttr->guid;
}
finally
{
typeInfo.ReleaseTypeAttr(pTypeAttr);
}
}
/// <summary>
/// Resolves a value type for a property from a TYPEDESC. Value types can be
/// user defined, which and may be aliased into other type infos. This function
/// will recusively walk the ITypeInfos to resolve the type to a clr Type.
/// </summary>
private unsafe static Type GetValueTypeFromTypeDesc(in TYPEDESC typeDesc, ITypeInfo typeInfo, object[] typeData)
{
uint hreftype;
HRESULT hr = HRESULT.S_OK;
switch (typeDesc.vt)
{
default:
return VTToType(typeDesc.vt);
case VARENUM.UNKNOWN:
case VARENUM.DISPATCH:
// get the guid
typeData[0] = GetGuidForTypeInfo(typeInfo, null);
// return the type
return VTToType(typeDesc.vt);
case VARENUM.USERDEFINED:
// we'll need to recurse into a user defined reference typeinfo
Debug.Assert(typeDesc.union.hreftype != 0u, "typeDesc doesn't contain an hreftype!");
hreftype = typeDesc.union.hreftype;
break;
case VARENUM.PTR:
// we'll need to recurse into a user defined reference typeinfo
Debug.Assert(typeDesc.union.lptdesc != null, "typeDesc doesn't contain an refTypeDesc!");
if (typeDesc.union.lptdesc->vt == VARENUM.VARIANT)
{
return VTToType(typeDesc.union.lptdesc->vt);
}
hreftype = typeDesc.union.lptdesc->union.hreftype;
break;
}
// get the reference type info
hr = typeInfo.GetRefTypeInfo(hreftype, out ITypeInfo refTypeInfo);
if (!hr.Succeeded())
{
throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetRefTypeInfoFailed, hr), (int)hr);
}
try
{
// here is where we look at the next level type info.
// if we get an enum, process it, otherwise we will recurse
// or get a dispatch.
if (refTypeInfo != null)
{
TYPEATTR* pTypeAttr = null;
hr = refTypeInfo.GetTypeAttr(&pTypeAttr);
if (!hr.Succeeded())
{
throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), (int)hr);
}
try
{
Guid g = pTypeAttr->guid;
// save the guid if we've got one here
if (!Guid.Empty.Equals(g))
{
typeData[0] = g;
}
switch (pTypeAttr->typekind)
{
case TYPEKIND.ENUM:
return ProcessTypeInfoEnum(refTypeInfo);
case TYPEKIND.ALIAS:
// recurse here
return GetValueTypeFromTypeDesc(pTypeAttr->tdescAlias, refTypeInfo, typeData);
case TYPEKIND.DISPATCH:
return VTToType(VARENUM.DISPATCH);
case TYPEKIND.INTERFACE:
case TYPEKIND.COCLASS:
return VTToType(VARENUM.UNKNOWN);
default:
return null;
}
}
finally
{
refTypeInfo.ReleaseTypeAttr(pTypeAttr);
}
}
}
finally
{
refTypeInfo = null;
}
return null;
}
private static PropertyDescriptor[] InternalGetProperties(object obj, ITypeInfo typeInfo, DispatchID dispidToGet, ref int defaultIndex)
{
if (typeInfo == null)
{
return null;
}
Hashtable propInfos = new Hashtable();
DispatchID nameDispID = GetNameDispId((IDispatch)obj);
bool addAboutBox = false;
// properties can live as functions with get_ and put_ or
// as variables, so we do two steps here.
try
{
// DO FUNCDESC things
ProcessFunctions(typeInfo, propInfos, dispidToGet, nameDispID, ref addAboutBox);
}
catch (ExternalException ex)
{
Debug.Fail("ProcessFunctions failed with hr=" + ex.ErrorCode.ToString(CultureInfo.InvariantCulture) + ", message=" + ex.ToString());
}
try
{
// DO VARDESC things.
ProcessVariables(typeInfo, propInfos, dispidToGet, nameDispID);
}
catch (ExternalException ex)
{
Debug.Fail("ProcessVariables failed with hr=" + ex.ErrorCode.ToString(CultureInfo.InvariantCulture) + ", message=" + ex.ToString());
}
typeInfo = null;
// now we take the propertyInfo structures we built up
// and use them to create the actual descriptors.
int cProps = propInfos.Count;
if (addAboutBox)
{
cProps++;
}
PropertyDescriptor[] props = new PropertyDescriptor[cProps];
int defaultProp = -1;
HRESULT hr = HRESULT.S_OK;
object[] pvar = new object[1];
ComNativeDescriptor cnd = ComNativeDescriptor.Instance;
// for each item in uur list, create the descriptor an check
// if it's the default one.
foreach (PropInfo pi in propInfos.Values)
{
if (!pi.NonBrowsable)
{
// finally, for each property, make sure we can get the value
// if we can't then we should mark it non-browsable
try
{
hr = cnd.GetPropertyValue(obj, pi.DispId, pvar);
}
catch (ExternalException ex)
{
hr = (HRESULT)ex.ErrorCode;
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "IDispatch::Invoke(PROPGET, " + pi.Name + ") threw an exception :" + ex.ToString());
}
if (!hr.Succeeded())
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Adding Browsable(false) to property '" + pi.Name + "' because Invoke(dispid=0x{0:X} ,DISPATCH_PROPERTYGET) returned hr=0x{1:X}. Properties that do not return S_OK are hidden by default.", pi.DispId, hr));
pi.Attributes.Add(new BrowsableAttribute(false));
pi.NonBrowsable = true;
}
}
else
{
hr = HRESULT.S_OK;
}
Attribute[] temp = new Attribute[pi.Attributes.Count];
pi.Attributes.CopyTo(temp, 0);
props[pi.Index] = new Com2PropertyDescriptor(pi.DispId, pi.Name, temp, pi.ReadOnly != PropInfo.ReadOnlyFalse, pi.ValueType, pi.TypeData, !hr.Succeeded());
if (pi.IsDefault)
{
defaultProp = pi.Index;
}
}
if (addAboutBox)
{
props[props.Length - 1] = new Com2AboutBoxPropertyDescriptor();
}
return props;
}
private unsafe static PropInfo ProcessDataCore(ITypeInfo typeInfo, IDictionary propInfoList, DispatchID dispid, DispatchID nameDispID, in TYPEDESC typeDesc, VARFLAGS flags)
{
// get the name and the helpstring
using var nameBstr = new BSTR();
using var helpStringBstr = new BSTR();
HRESULT hr = typeInfo.GetDocumentation(dispid, &nameBstr, &helpStringBstr, null, null);
ComNativeDescriptor cnd = ComNativeDescriptor.Instance;
if (!hr.Succeeded())
{
throw new COMException(string.Format(SR.TYPEINFOPROCESSORGetDocumentationFailed, dispid, hr, cnd.GetClassName(typeInfo)), (int)hr);
}
string name = nameBstr.String.ToString();
if (string.IsNullOrEmpty(name))
{
Debug.Fail(string.Format(CultureInfo.CurrentCulture, "ITypeInfo::GetDocumentation didn't return a name for DISPID 0x{0:X} but returned SUCEEDED(hr), Component=" + cnd.GetClassName(typeInfo), dispid));
return null;
}
// now we can create our struct... make sure we don't already have one
PropInfo pi = (PropInfo)propInfoList[name];
if (pi == null)
{
pi = new PropInfo
{
Index = propInfoList.Count
};
propInfoList[name] = pi;
pi.Name = name;
pi.DispId = dispid;
pi.Attributes.Add(new DispIdAttribute((int)pi.DispId));
}
string helpString = helpStringBstr.String.ToString();
if (!string.IsNullOrEmpty(helpString))
{
pi.Attributes.Add(new DescriptionAttribute(helpString));
}
// figure out the value type
if (pi.ValueType == null)
{
object[] pTypeData = new object[1];
try
{
pi.ValueType = GetValueTypeFromTypeDesc(in typeDesc, typeInfo, pTypeData);
}
catch (Exception ex)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Hiding property " + pi.Name + " because value Type could not be resolved: " + ex.ToString());
}
// if we can't resolve the type, mark the property as nonbrowsable
// from the browser
//
if (pi.ValueType == null)
{
pi.NonBrowsable = true;
}
if (pi.NonBrowsable)
{
flags |= VARFLAGS.FNONBROWSABLE;
}
if (pTypeData[0] != null)
{
pi.TypeData = pTypeData[0];
}
}
// check the flags
if ((flags & VARFLAGS.FREADONLY) != 0)
{
pi.ReadOnly = PropInfo.ReadOnlyTrue;
}
if ((flags & VARFLAGS.FHIDDEN) != 0 ||
(flags & VARFLAGS.FNONBROWSABLE) != 0 ||
pi.Name[0] == '_' ||
dispid == DispatchID.HWND)
{
pi.Attributes.Add(new BrowsableAttribute(false));
pi.NonBrowsable = true;
}
if ((flags & VARFLAGS.FUIDEFAULT) != 0)
{
pi.IsDefault = true;
}
if ((flags & VARFLAGS.FBINDABLE) != 0 &&
(flags & VARFLAGS.FDISPLAYBIND) != 0)
{
pi.Attributes.Add(new BindableAttribute(true));
}
// lastly, if it's DISPID_Name, add the ParenthesizeNameAttribute
if (dispid == nameDispID)
{
pi.Attributes.Add(new ParenthesizePropertyNameAttribute(true));
// don't allow merges on the name
pi.Attributes.Add(new MergablePropertyAttribute(false));
}
return pi;
}
private unsafe static void ProcessFunctions(ITypeInfo typeInfo, IDictionary propInfoList, DispatchID dispidToGet, DispatchID nameDispID, ref bool addAboutBox)
{
TYPEATTR* pTypeAttr = null;
HRESULT hr = typeInfo.GetTypeAttr(&pTypeAttr);
if (!hr.Succeeded() || pTypeAttr == null)
{
throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), (int)hr);
}
try
{
bool isPropGet;
PropInfo pi;
for (uint i = 0; i < pTypeAttr->cFuncs; i++)
{
FUNCDESC* pFuncDesc = null;
hr = typeInfo.GetFuncDesc(i, &pFuncDesc);
if (!hr.Succeeded() || pFuncDesc == null)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring function item 0x{0:X} because ITypeInfo::GetFuncDesc returned hr=0x{1:X} or NULL", i, hr));
continue;
}
try
{
if (pFuncDesc->invkind == INVOKEKIND.FUNC ||
(dispidToGet != DispatchID.MEMBERID_NIL && pFuncDesc->memid != dispidToGet))
{
if (pFuncDesc->memid == DispatchID.ABOUTBOX)
{
addAboutBox = true;
}
continue;
}
TYPEDESC typeDesc;
// is this a get or a put?
isPropGet = (pFuncDesc->invkind == INVOKEKIND.PROPERTYGET);
if (isPropGet)
{
if (pFuncDesc->cParams != 0)
{
continue;
}
unsafe
{
typeDesc = pFuncDesc->elemdescFunc.tdesc;
}
}
else
{
Debug.Assert(pFuncDesc->lprgelemdescParam != null, "ELEMDESC param is null!");
if (pFuncDesc->lprgelemdescParam == null || pFuncDesc->cParams != 1)
{
continue;
}
unsafe
{
typeDesc = pFuncDesc->lprgelemdescParam->tdesc;
}
}
pi = ProcessDataCore(typeInfo, propInfoList, pFuncDesc->memid, nameDispID, in typeDesc, (VARFLAGS)pFuncDesc->wFuncFlags);
// if we got a setmethod, it's not readonly
if (pi != null && !isPropGet)
{
pi.ReadOnly = PropInfo.ReadOnlyFalse;
}
}
finally
{
typeInfo.ReleaseFuncDesc(pFuncDesc);
}
}
}
finally
{
typeInfo.ReleaseTypeAttr(pTypeAttr);
}
}
/// <summary>
/// This converts a type info that describes a IDL defined enum
/// into one we can use
/// </summary>
private unsafe static Type ProcessTypeInfoEnum(ITypeInfo enumTypeInfo)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum entered");
if (enumTypeInfo == null)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum got a NULL enumTypeInfo");
return null;
}
try
{
TYPEATTR* pTypeAttr = null;
HRESULT hr = enumTypeInfo.GetTypeAttr(&pTypeAttr);
if (!hr.Succeeded() || pTypeAttr == null)
{
throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), (int)hr);
}
try
{
uint nItems = pTypeAttr->cVars;
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: processing " + nItems.ToString(CultureInfo.InvariantCulture) + " variables");
ArrayList strs = new ArrayList();
ArrayList vars = new ArrayList();
object varValue = null;
using var enumNameBstr = new BSTR();
using var enumHelpStringBstr = new BSTR();
enumTypeInfo.GetDocumentation(DispatchID.MEMBERID_NIL, &enumNameBstr, &enumHelpStringBstr, null, null);
// For each item in the enum type info, we just need it's name and value and
// helpstring if it's there.
for (uint i = 0; i < nItems; i++)
{
VARDESC* pVarDesc = null;
hr = enumTypeInfo.GetVarDesc(i, &pVarDesc);
if (!hr.Succeeded() || pVarDesc == null)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring item 0x{0:X} because ITypeInfo::GetVarDesc returned hr=0x{1:X} or NULL", i, hr));
continue;
}
try
{
if (pVarDesc->varkind != VARKIND.CONST || pVarDesc->unionMember == IntPtr.Zero)
{
continue;
}
varValue = null;
// get the name and the helpstring
using var nameBstr = new BSTR();
using var helpBstr = new BSTR();
hr = enumTypeInfo.GetDocumentation(pVarDesc->memid, &nameBstr, &helpBstr, null, null);
if (!hr.Succeeded())
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring item 0x{0:X} because ITypeInfo::GetDocumentation returned hr=0x{1:X} or NULL", i, hr));
continue;
}
string name = nameBstr.String.ToString();
string helpString = helpBstr.String.ToString();
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum got name=" + (name ?? "(null)") + ", helpstring=" + (helpString ?? "(null)"));
// get the value
try
{
varValue = Marshal.GetObjectForNativeVariant(pVarDesc->unionMember);
}
catch (Exception ex)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: PtrtoStructFailed " + ex.GetType().Name + "," + ex.Message);
}
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: adding variable value=" + Convert.ToString(varValue, CultureInfo.InvariantCulture));
vars.Add(varValue);
// if we have a helpstring, use it, otherwise use name
string nameString;
if (!string.IsNullOrEmpty(helpString))
{
nameString = helpString;
}
else
{
Debug.Assert(name != null, "No name for VARDESC member, but GetDocumentation returned S_OK!");
nameString = name;
}
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: adding name value=" + nameString);
strs.Add(nameString);
}
finally
{
enumTypeInfo.ReleaseVarDesc(pVarDesc);
}
}
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: returning enum with " + strs.Count.ToString(CultureInfo.InvariantCulture) + " items");
// just build our enumerator
if (strs.Count > 0)
{
// get the IUnknown value of the ITypeInfo
IntPtr pTypeInfoUnk = Marshal.GetIUnknownForObject(enumTypeInfo);
try
{
string enumName = pTypeInfoUnk.ToString() + "_" + enumNameBstr.String.ToString();
if (builtEnums == null)
{
builtEnums = new Hashtable();
}
else if (builtEnums.ContainsKey(enumName))
{
return (Type)builtEnums[enumName];
}
Type enumType = typeof(int);
if (vars.Count > 0 && vars[0] != null)
{
enumType = vars[0].GetType();
}
EnumBuilder enumBuilder = ModuleBuilder.DefineEnum(enumName, TypeAttributes.Public, enumType);
for (int i = 0; i < strs.Count; i++)
{
enumBuilder.DefineLiteral((string)strs[i], vars[i]);
}
Type t = enumBuilder.CreateTypeInfo().AsType();
builtEnums[enumName] = t;
return t;
}
finally
{
if (pTypeInfoUnk != IntPtr.Zero)
{
Marshal.Release(pTypeInfoUnk);
}
}
}
}
finally
{
enumTypeInfo.ReleaseTypeAttr(pTypeAttr);
}
}
catch
{
}
return null;
}
private unsafe static void ProcessVariables(ITypeInfo typeInfo, IDictionary propInfoList, DispatchID dispidToGet, DispatchID nameDispID)
{
TYPEATTR* pTypeAttr = null;
HRESULT hr = typeInfo.GetTypeAttr(&pTypeAttr);
if (!hr.Succeeded() || pTypeAttr == null)
{
throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), (int)hr);
}
try
{
for (uint i = 0; i < pTypeAttr->cVars; i++)
{
VARDESC* pVarDesc = null;
hr = typeInfo.GetVarDesc(i, &pVarDesc);
if (!hr.Succeeded() || pVarDesc == null)
{
Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring variable item 0x{0:X} because ITypeInfo::GetFuncDesc returned hr=0x{1:X} or NULL", i, hr));
continue;
}
try
{
if (pVarDesc->varkind == VARKIND.CONST ||
(dispidToGet != DispatchID.MEMBERID_NIL && pVarDesc->memid != dispidToGet))
{
continue;
}
unsafe
{
PropInfo pi = ProcessDataCore(typeInfo, propInfoList, pVarDesc->memid, nameDispID, in pVarDesc->elemdescVar.tdesc, pVarDesc->wVarFlags);
if (pi.ReadOnly != PropInfo.ReadOnlyTrue)
{
pi.ReadOnly = PropInfo.ReadOnlyFalse;
}
}
}
finally
{
typeInfo.ReleaseVarDesc(pVarDesc);
}
}
}
finally
{
typeInfo.ReleaseTypeAttr(pTypeAttr);
}
}
private static Type VTToType(VARENUM vt)
{
switch (vt)
{
case VARENUM.EMPTY:
case VARENUM.NULL:
return null;
case VARENUM.I1:
return typeof(sbyte);
case VARENUM.UI1:
return typeof(byte);
case VARENUM.I2:
return typeof(short);
case VARENUM.UI2:
return typeof(ushort);
case VARENUM.I4:
case VARENUM.INT:
return typeof(int);
case VARENUM.UI4:
case VARENUM.UINT:
return typeof(uint);
case VARENUM.I8:
return typeof(long);
case VARENUM.UI8:
return typeof(ulong);
case VARENUM.R4:
return typeof(float);
case VARENUM.R8:
return typeof(double);
case VARENUM.CY:
return typeof(decimal);
case VARENUM.DATE:
return typeof(DateTime);
case VARENUM.BSTR:
case VARENUM.LPSTR:
case VARENUM.LPWSTR:
return typeof(string);
case VARENUM.DISPATCH:
return typeof(IDispatch);
case VARENUM.UNKNOWN:
return typeof(object);
case VARENUM.ERROR:
case VARENUM.HRESULT:
return typeof(int);
case VARENUM.BOOL:
return typeof(bool);
case VARENUM.VARIANT:
return typeof(Com2Variant);
case VARENUM.CLSID:
return typeof(Guid);
case VARENUM.FILETIME:
return typeof(Runtime.InteropServices.ComTypes.FILETIME);
case VARENUM.USERDEFINED:
throw new ArgumentException(string.Format(SR.COM2UnhandledVT, "VT_USERDEFINED"));
case VARENUM.VOID:
case VARENUM.PTR:
case VARENUM.SAFEARRAY:
case VARENUM.CARRAY:
case VARENUM.RECORD:
case VARENUM.BLOB:
case VARENUM.STREAM:
case VARENUM.STORAGE:
case VARENUM.STREAMED_OBJECT:
case VARENUM.STORED_OBJECT:
case VARENUM.BLOB_OBJECT:
case VARENUM.CF:
case VARENUM.BSTR_BLOB:
case VARENUM.VECTOR:
case VARENUM.ARRAY:
case VARENUM.BYREF:
case VARENUM.RESERVED:
default:
throw new ArgumentException(string.Format(SR.COM2UnhandledVT, ((int)vt).ToString(CultureInfo.InvariantCulture)));
}
}
internal class CachedProperties
{
private readonly PropertyDescriptor[] props;
public readonly uint MajorVersion;
public readonly uint MinorVersion;
private readonly int defaultIndex;
internal CachedProperties(PropertyDescriptor[] props, int defIndex, uint majVersion, uint minVersion)
{
this.props = ClonePropertyDescriptors(props);
MajorVersion = majVersion;
MinorVersion = minVersion;
defaultIndex = defIndex;
}
public PropertyDescriptor[] Properties
{
get
{
return ClonePropertyDescriptors(props);
}
}
public int DefaultIndex
{
get
{
return defaultIndex;
}
}
private PropertyDescriptor[] ClonePropertyDescriptors(PropertyDescriptor[] props)
{
PropertyDescriptor[] retProps = new PropertyDescriptor[props.Length];
for (int i = 0; i < props.Length; i++)
{
if (props[i] is ICloneable)
{
retProps[i] = (PropertyDescriptor)((ICloneable)props[i]).Clone();
;
}
else
{
retProps[i] = props[i];
}
}
return retProps;
}
}
private class PropInfo
{
public const int ReadOnlyUnknown = 0;
public const int ReadOnlyTrue = 1;
public const int ReadOnlyFalse = 2;
public string Name { get; set; }
public DispatchID DispId { get; set; } = DispatchID.UNKNOWN;
public Type ValueType { get; set; }
public ArrayList Attributes { get; } = new ArrayList();
public int ReadOnly { get; set; } = ReadOnlyUnknown;
public bool IsDefault { get; set; }
public object TypeData { get; set; }
public bool NonBrowsable { get; set; }
public int Index { get; set; }
public override int GetHashCode() => Name?.GetHashCode() ?? base.GetHashCode();
}
}
/// <summary>
/// A class included so we can recognize a variant properly.
/// </summary>
public class Com2Variant
{
}
}
| 39.15514 | 331 | 0.470451 | [
"MIT"
] | SergeySmirnov-Akvelon/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs | 41,898 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\dxgidebug.h(172,5)
using System;
using System.Runtime.InteropServices;
using DXGI_DEBUG_ID = System.Guid;
namespace DirectN
{
[Guid("d67441c7-672a-476f-9e82-cd55b44949ce"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IDXGIInfoQueue
{
[PreserveSig]
HRESULT SetMessageCountLimit(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ ulong MessageCountLimit);
[PreserveSig]
void ClearStoredMessages(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT GetMessageW(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ ulong MessageIndex, /* [annotation] _Out_writes_bytes_opt_(*pMessageByteLength) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] DXGI_INFO_QUEUE_MESSAGE[] pMessage, /* [annotation] _Inout_ */ IntPtr pMessageByteLength);
[PreserveSig]
ulong GetNumStoredMessagesAllowedByRetrievalFilters(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
ulong GetNumStoredMessages(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
ulong GetNumMessagesDiscardedByMessageCountLimit(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
ulong GetMessageCountLimit(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
ulong GetNumMessagesAllowedByStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
ulong GetNumMessagesDeniedByStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT AddStorageFilterEntries(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ ref DXGI_INFO_QUEUE_FILTER pFilter);
[PreserveSig]
HRESULT GetStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _Out_writes_bytes_opt_(*pFilterByteLength) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] DXGI_INFO_QUEUE_FILTER[] pFilter, /* [annotation] _Inout_ */ IntPtr pFilterByteLength);
[PreserveSig]
void ClearStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushEmptyStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushDenyAllStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushCopyOfStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ ref DXGI_INFO_QUEUE_FILTER pFilter);
[PreserveSig]
void PopStorageFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
uint GetStorageFilterStackSize(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT AddRetrievalFilterEntries(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ ref DXGI_INFO_QUEUE_FILTER pFilter);
[PreserveSig]
HRESULT GetRetrievalFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _Out_writes_bytes_opt_(*pFilterByteLength) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] DXGI_INFO_QUEUE_FILTER[] pFilter, /* [annotation] _Inout_ */ IntPtr pFilterByteLength);
[PreserveSig]
void ClearRetrievalFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushEmptyRetrievalFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushDenyAllRetrievalFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushCopyOfRetrievalFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT PushRetrievalFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ ref DXGI_INFO_QUEUE_FILTER pFilter);
[PreserveSig]
void PopRetrievalFilter(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
uint GetRetrievalFilterStackSize(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
[PreserveSig]
HRESULT AddMessage(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category, /* [annotation] _In_ */ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, /* [annotation] _In_ */ int ID, /* [annotation] _In_ */ [MarshalAs(UnmanagedType.LPStr)] string pDescription);
[PreserveSig]
HRESULT AddApplicationMessage(/* [annotation] _In_ */ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, /* [annotation] _In_ */ [MarshalAs(UnmanagedType.LPStr)] string pDescription);
[PreserveSig]
HRESULT SetBreakOnCategory(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category, /* [annotation] _In_ */ bool bEnable);
[PreserveSig]
HRESULT SetBreakOnSeverity(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, /* [annotation] _In_ */ bool bEnable);
[PreserveSig]
HRESULT SetBreakOnID(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ int ID, /* [annotation] _In_ */ bool bEnable);
[PreserveSig]
bool GetBreakOnCategory(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category);
[PreserveSig]
bool GetBreakOnSeverity(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity);
[PreserveSig]
bool GetBreakOnID(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ int ID);
[PreserveSig]
void SetMuteDebugOutput(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer, /* [annotation] _In_ */ bool bMute);
[PreserveSig]
bool GetMuteDebugOutput(/* [annotation] _In_ */ DXGI_DEBUG_ID Producer);
}
}
| 52.617886 | 333 | 0.671354 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/IDXGIInfoQueue.cs | 6,474 | C# |
//
// EditableDesignerRegion.cs
//
// Author:
// Marek Habersack <mhabersack@novell.com>
//
// (C) 2007 Novell, Inc.
//
//
// 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.
//
#if NET_2_0
using System;
namespace System.Web.UI.Design
{
public class EditableDesignerRegion : DesignerRegion
{
[MonoNotSupported ("")]
public EditableDesignerRegion (ControlDesigner owner, string name)
: base (owner, name)
{
throw new NotImplementedException ();
}
[MonoNotSupported ("")]
public EditableDesignerRegion (ControlDesigner owner, string name, bool serverControlsOnly)
: base (owner, name, serverControlsOnly)
{
throw new NotImplementedException ();
}
[MonoNotSupported ("")]
public virtual ViewRendering GetChildViewRendering (Control control)
{
throw new NotImplementedException ();
}
[MonoNotSupported ("")]
public virtual string Content {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
[MonoNotSupported ("")]
public bool ServerControlsOnly {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
[MonoNotSupported ("")]
public virtual bool SupportsDataBinding {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
}
}
#endif
| 26.282609 | 93 | 0.714227 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Design/System.Web.UI.Design/EditableDesignerRegion.cs | 2,418 | 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.
*/
/*************************************************************************************
Extended WPF Toolkit
Copyright (C) 2007-2015 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at http://xceed.com/wpf_toolkit
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System.Windows.Documents;
using Xceed.Wpf.Toolkit.LiveExplorer.Core.CodeFormatting;
using Xceed.Wpf.Toolkit;
namespace Xceed.Wpf.Toolkit.LiveExplorer.Core
{
/// <summary>
/// Formats the RichTextBox text as colored C#
/// </summary>
public class CSharpFormatter : ITextFormatter
{
public readonly static CSharpFormatter Instance = new CSharpFormatter();
public string GetText( FlowDocument document )
{
return new TextRange( document.ContentStart, document.ContentEnd ).Text;
}
public void SetText( FlowDocument document, string text )
{
document.Blocks.Clear();
document.PageWidth = 2500;
CSharpFormat cSharpFormat = new CSharpFormat();
Paragraph p = new Paragraph();
p = cSharpFormat.FormatCode( text );
document.Blocks.Add( p );
}
}
}
| 31.123077 | 86 | 0.661394 | [
"Apache-2.0"
] | yong7743/arcgis-pro-sdk-community-samples | Map-Authoring/DictionarySymbolPreview/FromLiveExplorer/Core/CSharpFormatter.cs | 2,023 | C# |
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using Rest.CometChat.Abstractions;
using Shouldly;
namespace Rest.CometChat.Tests
{
[Explicit]
[TestFixture]
public class FriendServiceTests : BaseServiceTests<IFriendService>
{
[TestCase("d05178fe-7741-48c8-b2be-e4e458c4eb53", "7853eb99-e8e1-4ec4-b12b-3c5434d51c02")]
public async Task AddFriend_Success(string uid, params string[] friends)
{
var result = await this.Service!.AddAsync(uid, friends.ToList());
result.ShouldNotBeNull();
result.Accepted.ShouldNotBeNull();
result.Accepted!.ShouldContainKey(friends[0]);
var friendResponse = result.Accepted[friends[0]];
friendResponse.Success.ShouldBe(true );
}
[TestCase("d05178fe-7741-48c8-b2be-e4e458c4eb53", "7853eb99-e8e1-4ec4-b12b-3c5434d51c02")]
public async Task ListFriend_Success(string uid, string friendUid)
{
var result = await this.Service!.ListAsync(uid);
result.ShouldNotBeNull();
result.ShouldSatisfyAllConditions
(
() => result.Meta.ShouldNotBeNull(),
() => result.Entities.ShouldNotBeNull(),
() => result.Entities!.ShouldContain(x => x.Uid == friendUid)
);
}
[TestCase("d05178fe-7741-48c8-b2be-e4e458c4eb53", "7853eb99-e8e1-4ec4-b12b-3c5434d51c02")]
public async Task RemoveFriend_Success(string uid, params string[] friends)
{
var result = await this.Service!.RemoveAsync(uid, friends.ToList());
result.ShouldNotBeNull();
result.ShouldSatisfyAllConditions
(
() => result.Success.ShouldBe(true)
);
}
protected override IFriendService GetService()
=> new FriendService(this.CometChatConfigMock!.Object);
}
} | 31.113208 | 92 | 0.735597 | [
"MIT"
] | diegostamigni/Rest.CometChat | Rest.CometChat.Tests/FriendServiceTests.cs | 1,649 | C# |
using System.Collections.Generic;
namespace Nssol.Platypus.Infrastructure.Infos
{
public class NodeInfo
{
/// <summary>
/// ノード名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 割り当て可能なメモリ(単位:Gi)
/// </summary>
public float Memory { get; set; }
/// <summary>
/// 割り当て可能なGPU数
/// </summary>
public int Gpu { get; set; }
/// <summary>
/// 割り当て可能なCpuコア数
/// </summary>
public float Cpu { get; set; }
/// <summary>
/// ノードに設定されたラベル
/// </summary>
public Dictionary<string, string> Labels { get; set; }
}
}
| 21.121212 | 62 | 0.482066 | [
"Apache-2.0"
] | yonetatuu/kamonohashi | web-api/platypus/platypus/Infrastructure/Infos/NodeInfo.cs | 793 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI.Models
{
public class Menu
{
public long Id { get; set; }
public string food1 { get; set; }
public string food2 { get; set; }
public string food3 { get; set; }
public string food4 { get; set; }
}
}
| 21.529412 | 41 | 0.617486 | [
"MIT"
] | nigarozluk/MenuAPI | WebAPI/Models/Menu.cs | 368 | C# |
namespace Quantify.Repository.Enum.Test.Assets.TestUnits
{
[BaseUnit(TestUnit_MultipleMissingAndInvalidUnitAttributes.Metre)]
public enum TestUnit_MultipleMissingAndInvalidUnitAttributes
{
Millimetre = 17,
[Unit("0.01")]
Centimetre = 18,
[Unit("Hello, World!")]
Decimetre = 19,
Metre = 20,
[Unit("10")]
Decametre = 21,
[Unit("Horse")]
Hectometre = 22,
Kilometre = 23
}
} | 26.388889 | 70 | 0.591579 | [
"MIT"
] | acidicsoftware/dotnet-quantify-repository-enum | test/Quantify.Repository.Enum.Test.Assets/TestUnits/TestUnit_MultipleMissingAndInvalidUnitAttributes.cs | 477 | C# |
using ExpandedContent.Config;
using ExpandedContent.Extensions;
using ExpandedContent.Utilities;
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes;
using Kingmaker.Blueprints.Classes.Prerequisites;
using Kingmaker.Blueprints.Classes.Selection;
using Kingmaker.Blueprints.Items;
using Kingmaker.Designers.Mechanics.Facts;
using Kingmaker.UnitLogic.Alignments;
using Kingmaker.UnitLogic.FactLogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExpandedContent.Tweaks.Deities {
internal class Alseta {
private static readonly BlueprintFeature CommunityDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("c87004460f3328c408d22c5ead05291f");
private static readonly BlueprintFeature LawDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("092714336606cfc45a37d2ab39fabfa8");
private static readonly BlueprintFeature MagicDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("08a5686378a87b64399d329ba4ef71b8");
private static readonly BlueprintFeature ProtectionDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("d4ce7592bd12d63439907ad64e986e59");
private static readonly BlueprintFeature CrusaderSpellbook = Resources.GetBlueprint<BlueprintFeature>("673d39f7da699aa408cdda6282e7dcc0");
private static readonly BlueprintFeature ClericSpellbook = Resources.GetBlueprint<BlueprintFeature>("4673d19a0cf2fab4f885cc4d1353da33");
private static readonly BlueprintFeature InquisitorSpellbook = Resources.GetBlueprint<BlueprintFeature>("57fab75111f377248810ece84193a5a5");
private static readonly BlueprintFeature ChannelPositiveAllowed = Resources.GetBlueprint<BlueprintFeature>("8c769102f3996684fb6e09a2c4e7e5b9");
private static readonly BlueprintFeature ChannelNegativeAllowed = Resources.GetBlueprint<BlueprintFeature>("dab5255d809f77c4395afc2b713e9cd6");
private static readonly BlueprintCharacterClass ClericClass = Resources.GetBlueprint<BlueprintCharacterClass>("67819271767a9dd4fbfd4ae700befea0");
private static readonly BlueprintCharacterClass InquistorClass = Resources.GetBlueprint<BlueprintCharacterClass>("f1a70d9e1b0b41e49874e1fa9052a1ce");
private static readonly BlueprintCharacterClass WarpriestClass = Resources.GetBlueprint<BlueprintCharacterClass>("30b5e47d47a0e37438cc5a80c96cfb99");
private static readonly BlueprintCharacterClass PaladinClass = Resources.GetBlueprint<BlueprintCharacterClass>("bfa11238e7ae3544bbeb4d0b92e897ec");
public static void AddAlsetaFeature() {
BlueprintItem MasterworkDagger = Resources.GetBlueprint<BlueprintItem>("dfc92affae244554e8745a9ee9b7c520");
BlueprintArchetype FeralChampionArchetype = Resources.GetBlueprint<BlueprintArchetype>("f68ca492c9c15e241ab73735fbd0fb9f");
BlueprintArchetype MantisZealotArchetype = Resources.GetModBlueprint<BlueprintArchetype>("MantisZealotArchetype");
BlueprintArchetype SilverChampionArchetype = Resources.GetModBlueprint<BlueprintArchetype>("SilverChampionArchetype");
BlueprintFeature DaggerProficiency = Resources.GetBlueprint<BlueprintFeature>("b776c19291928cf4184d4dc65f09f3a6");
var AlsetaIcon = AssetLoader.LoadInternal("Deities", "Icon_Alseta.jpg");
var AlsetaFeature = Helpers.CreateBlueprint<BlueprintFeature>("AlsetaFeature", (bp => {
bp.SetName("Alseta");
bp.SetDescription("\nTitles: The Welcomer " +
"\nAlignment: Lawful Neutral " +
"\nAreas of Concern: Doors, Transitions, Years " +
"\nDomains: Community, Law, Magic, Protection " +
"\nSubdomains: Arcane, Defense, Home, Inevitable " +
"\nFavoured Weapon: Dagger " +
"\nHoly Symbol: Two faces in profile " +
"\nSacred Animal: Tortoise " +
"\nAlseta acts as a guardian of boundaries. She strengthens city gates, shields guards from invaders’ arrows, and turns away unwelcome visitors. " +
"Alseta is also a guardian of metaphorical boundaries, particularly those related to time and life. Those who earn Alseta’s favor find that physical " +
"blockades often open easily to them, or that metaphorical obstacles melt away more easily than expected. They uncover new opportunities in unexpected " +
"places, and receive flashes of insight that illuminate options that otherwise wouldn’t have occurred to them. Alseta appears as a kindly human woman " +
"dressed in simple gray clothing, and she wears a smiling mask on the back of her head.");
bp.m_Icon = AlsetaIcon;
bp.Ranks = 1;
bp.IsClassFeature = true;
bp.HideInCharacterSheetAndLevelUp = false;
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.m_CharacterClass = WarpriestClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = FeralChampionArchetype.ToReference<BlueprintArchetypeReference>();
});
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.m_CharacterClass = WarpriestClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = MantisZealotArchetype.ToReference<BlueprintArchetypeReference>();
});
bp.AddComponent<PrerequisiteNoArchetype>(c => {
c.HideInUI = true;
c.m_CharacterClass = PaladinClass.ToReference<BlueprintCharacterClassReference>();
c.m_Archetype = SilverChampionArchetype.ToReference<BlueprintArchetypeReference>();
});
bp.Groups = new FeatureGroup[] { FeatureGroup.Deities };
bp.AddComponent<PrerequisiteAlignment>(c => {
c.Alignment = AlignmentMaskType.LawfulGood | AlignmentMaskType.LawfulNeutral | AlignmentMaskType.TrueNeutral | AlignmentMaskType.LawfulEvil;
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { ChannelPositiveAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { ChannelNegativeAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { CommunityDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { LawDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { ProtectionDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<AddFacts>(c => {
c.m_Facts = new BlueprintUnitFactReference[1] { MagicDomainAllowed.ToReference<BlueprintUnitFactReference>() };
});
bp.AddComponent<ForbidSpellbookOnAlignmentDeviation>(c => {
c.m_Spellbooks = new BlueprintSpellbookReference[1] { CrusaderSpellbook.ToReference<BlueprintSpellbookReference>() };
c.m_Spellbooks = new BlueprintSpellbookReference[1] { ClericSpellbook.ToReference<BlueprintSpellbookReference>() };
c.m_Spellbooks = new BlueprintSpellbookReference[1] { InquisitorSpellbook.ToReference<BlueprintSpellbookReference>() };
});
bp.AddComponent<AddFeatureOnClassLevel>(c => {
c.m_Class = ClericClass.ToReference<BlueprintCharacterClassReference>();
c.m_Feature = DaggerProficiency.ToReference<BlueprintFeatureReference>();
c.Level = 1;
c.m_Archetypes = null;
c.m_AdditionalClasses = new BlueprintCharacterClassReference[2] {
InquistorClass.ToReference<BlueprintCharacterClassReference>(),
WarpriestClass.ToReference<BlueprintCharacterClassReference>() };
});
bp.AddComponent<AddStartingEquipment>(c => {
c.m_BasicItems = new BlueprintItemReference[1] { MasterworkDagger.ToReference<BlueprintItemReference>() };
c.m_RestrictedByClass = new BlueprintCharacterClassReference[3] {
ClericClass.ToReference<BlueprintCharacterClassReference>(),
InquistorClass.ToReference<BlueprintCharacterClassReference>(),
WarpriestClass.ToReference<BlueprintCharacterClassReference>()
};
});
}));
}
}
}
| 68.626866 | 174 | 0.67997 | [
"MIT"
] | ka-dyn/kadynsWoTRMods | ExpandedContent/Tweaks/Deities/Alseta.cs | 9,204 | C# |
// ┌∩┐(◣_◢)┌∩┐
// \\
// LightManagerEditor.cs (26/03/2017) \\
// Autor: Antonio Mateo (Moon Antonio) \\
// Descripcion: Herramienta para controlar las luces de al escena. \\
// Fecha Mod: 28/04/2018 \\
// Ultima Mod: Redimension de GUI. \\
//******************************************************************************\\
#region Librerias
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
#endregion
namespace MoonAntonio
{
/// <summary>
/// <para>Herramienta para controlar las luces de al escena</para>
/// </summary>
[ExecuteInEditMode]
public class LightManagerEditor : EditorWindow
{
#region Variables Publicas
/// <summary>
/// <para>Lista de luces en la escena.</para>
/// </summary>
public List<Light> luces = new List<Light>(); // Lista de luces en la escena
/// <summary>
/// <para>Lista de las reflection probes en la escena</para>
/// </summary>
public List<ReflectionProbe> reflection = new List<ReflectionProbe>();// Lista de las reflection probes en la escena
#endregion
#region Variables Privadas
/// <summary>
/// <para>Luces para el escaneo.</para>
/// </summary>
private Light[] lights; // Luces para el escaneo
/// <summary>
/// <para>Reflection probes para el escaneo</para>
/// </summary>
private ReflectionProbe[] reflec; // Reflection probes para el escaneo
/// <summary>
/// <para>Estado de la herramienta.</para>
/// </summary>
private int estadoherramienta = 0; // Estado de la herramienta
/// <summary>
/// <para>Posicion del scroll lateral.</para>
/// </summary>
private Vector2 scrollPosicion; // Posicion del scroll lateral
#endregion
#region Menu
/// <summary>
/// <para>Iniciador de Manager Light</para>
/// </summary>
[MenuItem("Moon Antonio/ManagerLight",false,1)]
public static void Init()// Iniciador de Manager Light
{
Texture icono = AssetDatabase.LoadAssetAtPath<Texture>("Assets/Moon Antonio/Light Manager/Icon/icon.lightmanager.png");
GUIContent tituloContenido = new GUIContent(" Light Manager", icono);
var window = GetWindow<LightManagerEditor>();
window.minSize = new Vector2(0, 0);
window.titleContent = tituloContenido;
window.Show();
}
#endregion
#region Unity Metodos
/// <summary>
/// <para>Cuando esta activo LightManagerEditor</para>
/// </summary>
public void OnEnable()// Cuando esta activo LightManagerEditor
{
// Escaneo de las luces de la escena
Escaneo();
}
/// <summary>
/// <para>Cuando el inspector Actualiza</para>
/// </summary>
public void OnInspectorUpdate()// Cuando el inspector Actualiza
{
if (lights.Length > 0) Array.Clear(lights, 0, lights.Length);
if (reflec.Length > 0) Array.Clear(reflec, 0, reflec.Length);
if (luces.Count > 0) luces.Clear();
if (reflection.Count > 0) reflection.Clear();
Escaneo();
}
#endregion
#region UI
/// <summary>
/// <para>Interfaz de LightManagerEditor</para>
/// </summary>
private void OnGUI()// Interfaz de LightManagerEditor
{
EditorGUILayout.BeginVertical("box");
EditorGUILayout.BeginHorizontal("box");
if (GUILayout.Button("Lights")) estadoherramienta = 0;
if (GUILayout.Button("Reflection Probes")) estadoherramienta = 1;
EditorGUILayout.EndHorizontal();
scrollPosicion = EditorGUILayout.BeginScrollView(scrollPosicion, GUILayout.Width(500), GUILayout.Height(500));
switch (estadoherramienta)
{
#region Luces
case 0:
if (luces.Count > 0)
{
EditorGUILayout.BeginHorizontal("box");
EditorGUILayout.LabelField("Estado", GUILayout.MinWidth(100), GUILayout.Width(50));
EditorGUILayout.LabelField("Nombre", GUILayout.MinWidth(100), GUILayout.Width(140));
EditorGUILayout.LabelField("Tipo", GUILayout.MinWidth(100), GUILayout.Width(100));
EditorGUILayout.LabelField("Modo", GUILayout.MinWidth(100), GUILayout.Width(100));
EditorGUILayout.LabelField("Color", GUILayout.MinWidth(100), GUILayout.Width(50));
EditorGUILayout.LabelField("Intensidad", GUILayout.MinWidth(100), GUILayout.Width(200));
EditorGUILayout.EndHorizontal();
for (int n = 0; n < luces.Count; n++)
{
EditorGUILayout.BeginHorizontal("box");
luces[n].enabled = EditorGUILayout.Toggle(luces[n].enabled, GUILayout.MinWidth(100), GUILayout.Width(50));
luces[n].name = EditorGUILayout.TextField(luces[n].name, GUILayout.MinWidth(100), GUILayout.Width(140));
luces[n].type = (LightType)EditorGUILayout.EnumPopup(luces[n].type, GUILayout.MinWidth(100), GUILayout.Width(100));
luces[n].lightmapBakeType = (LightmapBakeType)EditorGUILayout.EnumPopup(luces[n].lightmapBakeType, GUILayout.MinWidth(100), GUILayout.Width(100));
luces[n].color = EditorGUILayout.ColorField(luces[n].color, GUILayout.MinWidth(100), GUILayout.Width(50));
luces[n].intensity = EditorGUILayout.Slider(luces[n].intensity, 0, 10, GUILayout.MinWidth(100), GUILayout.Width(200));
EditorGUILayout.EndHorizontal();
}
}
break;
#endregion
#region Reflection Probes
case 1:
if (reflection.Count > 0)
{
EditorGUILayout.BeginHorizontal("box");
EditorGUILayout.LabelField("Estado", GUILayout.MinWidth(100), GUILayout.Width(50));
EditorGUILayout.LabelField("Nombre", GUILayout.MinWidth(100), GUILayout.Width(140));
EditorGUILayout.LabelField("Tipo", GUILayout.MinWidth(100), GUILayout.Width(100));
EditorGUILayout.LabelField("Intensidad", GUILayout.MinWidth(100), GUILayout.Width(200));
EditorGUILayout.EndHorizontal();
for (int n = 0; n < reflection.Count; n++)
{
EditorGUILayout.BeginHorizontal("box");
reflection[n].enabled = EditorGUILayout.Toggle(reflection[n].enabled, GUILayout.MinWidth(100), GUILayout.Width(50));
reflection[n].name = EditorGUILayout.TextField(reflection[n].name, GUILayout.MinWidth(100), GUILayout.Width(140));
reflection[n].mode = (UnityEngine.Rendering.ReflectionProbeMode)EditorGUILayout.EnumPopup(reflection[n].mode, GUILayout.MinWidth(100), GUILayout.Width(100));
reflection[n].intensity = EditorGUILayout.Slider(reflection[n].intensity, 0, 10, GUILayout.MinWidth(100), GUILayout.Width(200));
EditorGUILayout.EndHorizontal();
}
}
break;
#endregion
default:
estadoherramienta = 0;
break;
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
#endregion
#region Metodos
/// <summary>
/// <para>Escanea las luces de la escena.</para>
/// </summary>
private void Escaneo()// Escanea las luces de la escena
{
// Agregar las luces a la lista
lights = FindObjectsOfType(typeof(Light)) as Light[];
if (lights.Length > 0)
{
foreach (Light light in lights)
{
luces.Add(light);
}
}
else
{
estadoherramienta = 1;
}
// Agregar las reclection a la lista
reflec = FindObjectsOfType(typeof(ReflectionProbe)) as ReflectionProbe[];
if (reflec.Length > 0)
{
foreach (ReflectionProbe reflectionP in reflec)
{
reflection.Add(reflectionP);
}
}
else
{
estadoherramienta = 0;
}
}
#endregion
}
}
| 33.183857 | 164 | 0.657973 | [
"MIT"
] | MoonAntonio/LightsManager | LightsManager Project/Assets/Moon Antonio/Light Manager/Editor/LightManagerEditor.cs | 7,418 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// ConversationDivisionMembership
/// </summary>
[DataContract]
public partial class ConversationDivisionMembership : IEquatable<ConversationDivisionMembership>
{
/// <summary>
/// Initializes a new instance of the <see cref="ConversationDivisionMembership" /> class.
/// </summary>
/// <param name="Division">A division the conversation belongs to..</param>
/// <param name="Entities">The entities on the conversation within the division. These are the users, queues, work flows, etc. that can be on conversations and and be assigned to different divisions..</param>
public ConversationDivisionMembership(DomainEntityRef Division = null, List<DomainEntityRef> Entities = null)
{
this.Division = Division;
this.Entities = Entities;
}
/// <summary>
/// A division the conversation belongs to.
/// </summary>
/// <value>A division the conversation belongs to.</value>
[DataMember(Name="division", EmitDefaultValue=false)]
public DomainEntityRef Division { get; set; }
/// <summary>
/// The entities on the conversation within the division. These are the users, queues, work flows, etc. that can be on conversations and and be assigned to different divisions.
/// </summary>
/// <value>The entities on the conversation within the division. These are the users, queues, work flows, etc. that can be on conversations and and be assigned to different divisions.</value>
[DataMember(Name="entities", EmitDefaultValue=false)]
public List<DomainEntityRef> Entities { 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 ConversationDivisionMembership {\n");
sb.Append(" Division: ").Append(Division).Append("\n");
sb.Append(" Entities: ").Append(Entities).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 ConversationDivisionMembership);
}
/// <summary>
/// Returns true if ConversationDivisionMembership instances are equal
/// </summary>
/// <param name="other">Instance of ConversationDivisionMembership to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ConversationDivisionMembership other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Division == other.Division ||
this.Division != null &&
this.Division.Equals(other.Division)
) &&
(
this.Entities == other.Entities ||
this.Entities != null &&
this.Entities.SequenceEqual(other.Entities)
);
}
/// <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.Division != null)
hash = hash * 59 + this.Division.GetHashCode();
if (this.Entities != null)
hash = hash * 59 + this.Entities.GetHashCode();
return hash;
}
}
}
}
| 34.628378 | 216 | 0.556488 | [
"MIT"
] | nmusco/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/ConversationDivisionMembership.cs | 5,125 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/mfmediaengine.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("DF6B87B6-CE12-45DB-ABA7-432FE054E57D")]
[NativeTypeName("struct IMFTimedTextNotify : IUnknown")]
[NativeInheritance("IUnknown")]
public unsafe partial struct IMFTimedTextNotify
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IMFTimedTextNotify*, Guid*, void**, int>)(lpVtbl[0]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IMFTimedTextNotify*, uint>)(lpVtbl[1]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IMFTimedTextNotify*, uint>)(lpVtbl[2]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public void TrackAdded([NativeTypeName("DWORD")] uint trackId)
{
((delegate* unmanaged<IMFTimedTextNotify*, uint, void>)(lpVtbl[3]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this), trackId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
public void TrackRemoved([NativeTypeName("DWORD")] uint trackId)
{
((delegate* unmanaged<IMFTimedTextNotify*, uint, void>)(lpVtbl[4]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this), trackId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public void TrackSelected([NativeTypeName("DWORD")] uint trackId, [NativeTypeName("BOOL")] int selected)
{
((delegate* unmanaged<IMFTimedTextNotify*, uint, int, void>)(lpVtbl[5]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this), trackId, selected);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
public void TrackReadyStateChanged([NativeTypeName("DWORD")] uint trackId)
{
((delegate* unmanaged<IMFTimedTextNotify*, uint, void>)(lpVtbl[6]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this), trackId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
public void Error(MF_TIMED_TEXT_ERROR_CODE errorCode, [NativeTypeName("HRESULT")] int extendedErrorCode, [NativeTypeName("DWORD")] uint sourceTrackId)
{
((delegate* unmanaged<IMFTimedTextNotify*, MF_TIMED_TEXT_ERROR_CODE, int, uint, void>)(lpVtbl[7]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this), errorCode, extendedErrorCode, sourceTrackId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
public void Cue(MF_TIMED_TEXT_CUE_EVENT cueEvent, double currentTime, IMFTimedTextCue* cue)
{
((delegate* unmanaged<IMFTimedTextNotify*, MF_TIMED_TEXT_CUE_EVENT, double, IMFTimedTextCue*, void>)(lpVtbl[8]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this), cueEvent, currentTime, cue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(9)]
public void Reset()
{
((delegate* unmanaged<IMFTimedTextNotify*, void>)(lpVtbl[9]))((IMFTimedTextNotify*)Unsafe.AsPointer(ref this));
}
}
}
| 44.344086 | 205 | 0.672405 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/mfmediaengine/IMFTimedTextNotify.cs | 4,126 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.FormRecognizer.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An object representing a recognized text line.
/// </summary>
public partial class Line
{
/// <summary>
/// Initializes a new instance of the Line class.
/// </summary>
public Line()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Line class.
/// </summary>
/// <param name="boundingBox">Bounding box of a recognized
/// line.</param>
/// <param name="text">The text content of the line.</param>
/// <param name="words">List of words in the text line.</param>
public Line(IList<int> boundingBox = default(IList<int>), string text = default(string), IList<Word> words = default(IList<Word>))
{
BoundingBox = boundingBox;
Text = text;
Words = words;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets bounding box of a recognized line.
/// </summary>
[JsonProperty(PropertyName = "boundingBox")]
public IList<int> BoundingBox { get; set; }
/// <summary>
/// Gets or sets the text content of the line.
/// </summary>
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
/// <summary>
/// Gets or sets list of words in the text line.
/// </summary>
[JsonProperty(PropertyName = "words")]
public IList<Word> Words { get; set; }
}
}
| 31.408451 | 138 | 0.587444 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/cognitiveservices/FormRecognizer/src/Generated/Models/Line.cs | 2,230 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using uFramework.Common.Extensions;
namespace uFramework.MVC.Extensions
{
public static class DataTableExtensions
{
public static MvcHtmlString DataTable<TModel, TProperty>
(this HtmlHelper<IEnumerable<TModel>> htmlHelper, params Expression<Func<TModel, TProperty>>[] columns)
where TModel : class
where TProperty : class
{
return DataTable(htmlHelper, HtmlHelper.GenerateIdFromName(typeof(TModel).Name), columns);
}
public static MvcHtmlString DataTable<TModel, TProperty>
(this HtmlHelper<IEnumerable<TModel>> htmlHelper, string name, params Expression<Func<TModel, TProperty>>[] columns)
where TModel : class
where TProperty : class
{
return DataTable(htmlHelper, name, null, columns);
}
public static MvcHtmlString DataTable<TModel, TProperty>
(this HtmlHelper<IEnumerable<TModel>> htmlHelper, string name, object options, params Expression<Func<TModel, TProperty>>[] columns)
where TModel : class
where TProperty : class
{
return DataTable(htmlHelper, name, HtmlHelper.AnonymousObjectToHtmlAttributes(options), columns);
}
public static MvcHtmlString DataTable<TModel, TProperty>
(this HtmlHelper<IEnumerable<TModel>> htmlHelper, string name, IDictionary<string, object> options, params Expression<Func<TModel, TProperty>>[] columns)
where TModel : class
where TProperty : class
{
if (columns.Count() < 0)
return null;
var table = new TagBuilder("table");
table.Attributes["id"] = name;
table.Attributes["border"] = "2";
var thead = new TagBuilder("thead");
var thead_tr = new TagBuilder("tr");
foreach (var col in columns)
{
var th = new TagBuilder("th");
th.SetInnerText(ModelMetadata.FromLambdaExpression<TModel, TProperty>(col, new ViewDataDictionary<TModel>()).DisplayName);
thead_tr.InnerHtml += th.ToString();
}
thead.InnerHtml += thead_tr.ToString();
var tbody = new TagBuilder("tbody");
foreach (var col in columns)
{
var tbody_tr = new TagBuilder("tr");
foreach (var item in htmlHelper.ViewData.Model)
{
var td = new TagBuilder("td");
if (col is Expression<Func<TModel, TProperty>>)
td.InnerHtml = col.GetValueFrom(item).ToString();
else
td.InnerHtml = "Custom";
tbody_tr.InnerHtml += td.ToString();
}
tbody.InnerHtml += tbody_tr.ToString();
}
//var tfoot = new TagBuilder("tfoot");
table.InnerHtml += thead.ToString();
table.InnerHtml += tbody.ToString();
//table.InnerHtml += tfoot.ToString();
var script = new TagBuilder("script");
script.Attributes["type"] = "text/javascript";
var settings =
(options == null ? string.Empty : (new JavaScriptSerializer()).Serialize(options.ToDictionary(o => o.Key.ToString(), o => o.Value.ToString())));
script.InnerHtml = @"
$(function() {
$('#" + name + @"').dataTable(" + settings + @");
});";
return MvcHtmlString.Create(table.ToString() + script.ToString());
}
}
}
| 39.785714 | 166 | 0.559374 | [
"MIT"
] | jmirancid/uFramework | uFramework.MVC/Extensions/DataTableExtensions.cs | 3,901 | C# |
/*
// <copyright>
// dotNetRDF is free and open source software licensed under the MIT License
// -------------------------------------------------------------------------
//
// Copyright (c) 2009-2020 dotNetRDF Project (http://dotnetrdf.org/)
//
// 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.
// </copyright>
*/
using System;
using System.Net;
namespace VDS.RDF.Configuration
{
/// <summary>
/// Factory class for producing Network Credentials.
/// </summary>
public class CredentialsFactory : IObjectFactory
{
/// <summary>
/// Tries to load a Network Credential based on information from the Configuration Graph.
/// </summary>
/// <param name="g">Configuration Graph.</param>
/// <param name="objNode">Object Node.</param>
/// <param name="targetType">Target Type.</param>
/// <param name="obj">Output Object.</param>
/// <returns></returns>
public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj)
{
String user, pwd;
ConfigurationLoader.GetUsernameAndPassword(g, objNode, false, out user, out pwd);
if (user != null && pwd != null)
{
obj = new NetworkCredential(user, pwd);
return true;
}
else
{
obj = null;
return false;
}
}
/// <summary>
/// Gets whether this Factory can load objects of the given Type.
/// </summary>
/// <param name="t">Type.</param>
/// <returns></returns>
public bool CanLoadObject(Type t)
{
return t.Equals(typeof(NetworkCredential));
}
}
}
| 38.054795 | 97 | 0.62023 | [
"MIT"
] | blackwork/dotnetrdf | Libraries/dotNetRDF/Configuration/CredentialsFactory.cs | 2,778 | C# |
using System;
namespace Ex003 {
class Program {
static void Main(string[] args) {
Console.WriteLine("Qual a hora atual ?");
int x = int.Parse(Console.ReadLine());
if (x < 12) {
Console.WriteLine("Bom dia");
} else if (x < 18) {
Console.WriteLine("Boa Tarde");
} else { // ou else if (x >= 18) {}
Console.WriteLine("Boa Noite");
}
int value = int.Parse(Console.ReadLine());
if (x % 2 == 0) {
Console.WriteLine("Par !");
} else {
Console.WriteLine("Impar !");
}
}
}
}
| 25.740741 | 54 | 0.427338 | [
"MIT"
] | Vini-Dev-Py/C-sharp.NET | Exercicos/Ex003/Ex003/Program.cs | 697 | C# |
using System;
using AGO.Core.Model.Dictionary;
using Newtonsoft.Json;
namespace AGO.Tasks.Controllers.DTO
{
public class CustomParameterTypeDTO
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
public CustomPropertyValueType ValueType { get; set; }
}
public class CustomParameterDTO: ModelDTO
{
public CustomParameterTypeDTO Type { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Include)]
public object Value { get; set; }
}
} | 21.16 | 63 | 0.729679 | [
"MIT"
] | olegsmetanin/apinet-server | AGO.Tasks/Controllers/DTO/CustomParameterDTO.cs | 531 | C# |
using System;
using System.Reflection;
using System.Reflection.Metadata;
namespace Lokad.ILPack.Metadata
{
public interface IAssemblyMetadata
{
BlobBuilder ILBuilder { get; }
UserStringHandle GetOrAddUserString(string value);
EntityHandle GetTypeHandle(Type type);
EntityHandle GetFieldHandle(FieldInfo field);
EntityHandle GetConstructorHandle(ConstructorInfo ctor);
EntityHandle GetMethodHandle(MethodInfo method);
}
}
| 26.888889 | 64 | 0.735537 | [
"MIT"
] | AaronRobinsonMSFT/ILPack | src/Metadata/IAssemblyMetadata.cs | 486 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreSystem : MonoBehaviour {
public int score;
public int scoreToBeat;
public Text scoreText;
public bool hasWon;
GameTimer gTimer;
// Use this for initialization
void Start ()
{
gTimer = GameObject.Find("Game Manager").GetComponent<GameTimer>();
}
// Update is called once per frame
void Update ()
{
scoreText.text = score.ToString();
if (gTimer.gameGoing == false)
{
if (score >= scoreToBeat)
{
print("Win");
hasWon = true;
}
else
{
print("Lose");
hasWon = false;
score = 0;
//gTimer.gameTime = 0;
//gTimer.gameGoing = true;
}
}
}
}
| 15.233333 | 75 | 0.485777 | [
"Apache-2.0"
] | DaffyNinja/Cute-Game | Cutesy Game/Assets/Scripts/Game/ScoreSystem.cs | 916 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 19.10.2021.
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using NUnit.Framework;
using xEFCore=Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Migrations.Generations.SET001.DataTypes.Clr.TimeSpan{
////////////////////////////////////////////////////////////////////////////////
using T_DATA=System.TimeSpan;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_ERR005__bad_IsUnicode
public static class TestSet_ERR005__bad_IsUnicode
{
private const string c_testTableName
="EFCORE_TTABLE_DUMMY";
private const string c_testColumnName
="MY_COLUMN";
//-----------------------------------------------------------------------
[Test]
public static void Test_0000()
{
var operation
=new CreateTableOperation
{
Name
=c_testTableName,
Columns
={
new AddColumnOperation
{
Name = c_testColumnName,
Table = c_testTableName,
ClrType = typeof(T_DATA),
IsNullable = false,
IsUnicode = true
},
},
};//operation
try
{
TestHelper.Exec
(new[]{operation});
}
catch(xEFCore.LcpiOleDb__DataToolException e)
{
CheckErrors.PrintException_OK(e);
Assert.AreEqual
(3,
TestUtils.GetRecordCount(e));
CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_IsUnicode_2
(TestUtils.GetRecord(e,0),
CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__TimeSpan__as_Decimal9_4,
true,
false);
CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2
(TestUtils.GetRecord(e,1),
CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator,
c_testTableName,
c_testColumnName);
CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1
(TestUtils.GetRecord(e,2),
CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator,
c_testTableName);
return;
}//catch
TestServices.ThrowWeWaitError();
}//Test_0000
};//class TestSet_ERR005__bad_IsUnicode
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Migrations.Generations.SET001.DataTypes.Clr.TimeSpan
| 29.829545 | 126 | 0.619429 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Migrations/Generations/SET001/DataTypes/Clr/TimeSpan/TestSet_ERR005__bad_IsUnicode.cs | 2,627 | C# |
using System.ComponentModel.DataAnnotations;
namespace Piling.Model
{
/// <summary>
/// ort status enum information model
/// </summary>
public enum OutputFormat
{
/// <summary>
/// Txt
/// </summary>
[Display(Name = "txt")]
Txt=0,
/// <summary>
/// Opened
/// </summary>
[Display(Name = "csv")]
Csv=1,
/// <summary>
/// Closed
/// </summary>
[Display(Name = "json")]
Json=2,
/// <summary>
/// Unsupported type
/// </summary>
[Display(Name = "undefined")]
Undefined = 3
}
}
| 18.942857 | 45 | 0.447964 | [
"MIT"
] | miynat/Piling | Piling/Model/OutputFormat.cs | 665 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using BaselineSolution.Bo.Internal;
using BaselineSolution.Framework.Extensions;
using BaselineSolution.Framework.Infrastructure;
namespace BaselineSolution.WebApp.Infrastructure.Extensions
{
public static class ExtensionsForModelStateDictionary
{
public static void AddModelErrorFor<TModel, TProperty>(this ModelStateDictionary modelState,
Expression<Func<TModel, TProperty>> property,
string errorMessage)
{
modelState.AddModelError(ExpressionHelper.GetExpressionText(property), errorMessage);
}
public static void AddResponseValidationError(this ModelStateDictionary modelState, ValidationMessage message)
{
if (message.FieldName.IsNullOrEmpty())
{
modelState.AddModelError("", message.Message);
}
else
{
var state = modelState.FirstOrDefault(x => x.Key.EndsWith(message.FieldName));
modelState.AddModelError(state.Key, message.Message);
}
}
public static List<string> GetErrorMessages(this ModelStateDictionary modelState)
{
var stringlist = new List<string>();
foreach (var item in modelState)
{
if (item.Value.Errors.Any())
{
var message = string.Format("{0} Contains errors {1}", item.Key, string.Join(", ", item.Value.Errors));
stringlist.Add(message);
}
}
return stringlist;
}
}
} | 33.411765 | 123 | 0.620892 | [
"MIT"
] | Adconsulting/BaseSolution | BaselineSolution.WebApp/Infrastructure/Extensions/ExtensionsForModelStateDictionary.cs | 1,706 | C# |
//Copyright 2018, Davin Carten, All rights reserved
using System.Runtime.InteropServices;
using System;
namespace emotitron.Utilities.SmartVars
{
public enum SmartVarTypeCode
{
None, Int, Uint, Bool, Float, Byte, Short, UShort, Char
}
[System.Serializable]
[StructLayout(LayoutKind.Explicit)]
public struct SmartVar
{
[FieldOffset(0)]
public SmartVarTypeCode TypeCode;
[FieldOffset(4)]
public Int32 Int;
[FieldOffset(4)]
public UInt32 UInt;
[FieldOffset(4)]
public Boolean Bool;
[FieldOffset(4)]
public Single Float;
[FieldOffset(4)]
public Byte Byte8;
[FieldOffset(4)]
public Int16 Short;
[FieldOffset(4)]
public UInt16 UShort;
[FieldOffset(4)]
public Char Char;
public readonly static SmartVar None = new SmartVar() { TypeCode = SmartVarTypeCode.None };
public static implicit operator SmartVar(Int32 v)
{
return new SmartVar { Int = v, TypeCode = SmartVarTypeCode.Int };
}
public static implicit operator SmartVar(UInt32 v)
{
return new SmartVar { UInt = v, TypeCode = SmartVarTypeCode.Uint };
}
public static implicit operator SmartVar(Single v)
{
return new SmartVar { Float = v, TypeCode = SmartVarTypeCode.Float };
}
public static implicit operator SmartVar(Boolean v)
{
return new SmartVar { Bool = v, TypeCode = SmartVarTypeCode.Bool };
}
public static implicit operator SmartVar(Byte v)
{
return new SmartVar { Byte8 = v, TypeCode = SmartVarTypeCode.Byte };
}
public static implicit operator SmartVar(Int16 v)
{
return new SmartVar { Short = v, TypeCode = SmartVarTypeCode.Short };
}
public static implicit operator SmartVar(UInt16 v)
{
return new SmartVar { UShort = v, TypeCode = SmartVarTypeCode.UShort };
}
public static implicit operator SmartVar(Char v)
{
return new SmartVar { Char = v, TypeCode = SmartVarTypeCode.Char };
}
public static implicit operator Int32(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.Int)
{
return v.Int;
}
throw new InvalidCastException();
}
public static implicit operator UInt32(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.Uint)
{
return v.UInt;
}
throw new InvalidCastException();
}
public static implicit operator Single(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.Float)
{
return v.Float;
}
else
{
UnityEngine.Debug.LogError("cant cast " + v.TypeCode + " to single float");
}
throw new InvalidCastException();
}
public static implicit operator Boolean(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.Bool)
{
return v.Bool;
}
throw new InvalidCastException();
}
public static implicit operator Byte(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.Byte)
{
return v.Byte8;
}
throw new InvalidCastException();
}
public static implicit operator Int16(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.Short)
{
return v.Short;
}
throw new InvalidCastException();
}
public static implicit operator UInt16(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.UShort)
{
return v.UShort;
}
throw new InvalidCastException();
}
public static implicit operator Char(SmartVar v)
{
if (v.TypeCode == SmartVarTypeCode.Char)
{
return v.Char;
}
throw new InvalidCastException();
}
public SmartVar Copy()
{
return new SmartVar() { TypeCode = this.TypeCode, Int = this.Int };
}
public override string ToString()
{
string str = TypeCode.ToString() + " ";
if (TypeCode == SmartVarTypeCode.None)
return str;
else if (TypeCode == SmartVarTypeCode.Bool)
return str + this.Bool;
else if (TypeCode == SmartVarTypeCode.Int)
return str + this.Int;
else if (TypeCode == SmartVarTypeCode.Uint)
return str + this.UInt;
else if (TypeCode == SmartVarTypeCode.Float)
return str + this.Float;
else if (TypeCode == SmartVarTypeCode.Short)
return str + this.Short;
else if (TypeCode == SmartVarTypeCode.UShort)
return str + this.UShort;
else if (TypeCode == SmartVarTypeCode.Byte)
return str + this.Byte8;
else if (TypeCode == SmartVarTypeCode.Char)
return str + this.Char;
return str;
}
}
}
| 20.823529 | 93 | 0.678202 | [
"MIT"
] | TwoTenPvP/NetworkSyncTransform | Assets/emotitron/Utilities/SmartVars/SmartVars.cs | 4,250 | 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>
//------------------------------------------------------------------------------
namespace chc.servicemanagertray.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Configuration.SettingsProviderAttribute(typeof(chc.servicemanagertray.PortableSettingsProvider))]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
[global::System.Configuration.SettingsManageabilityAttribute(global::System.Configuration.SettingsManageability.Roaming)]
public bool TrayBalloonShown {
get {
return ((bool)(this["TrayBalloonShown"]));
}
set {
this["TrayBalloonShown"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Configuration.SettingsProviderAttribute(typeof(chc.servicemanagertray.PortableSettingsProvider))]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<ArrayOfString xmlns:xsi=\"http://www.w3." +
"org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />")]
[global::System.Configuration.SettingsManageabilityAttribute(global::System.Configuration.SettingsManageability.Roaming)]
public global::System.Collections.Specialized.StringCollection Favorites {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["Favorites"]));
}
set {
this["Favorites"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Configuration.SettingsProviderAttribute(typeof(chc.servicemanagertray.PortableSettingsProvider))]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("DisplayName")]
[global::System.Configuration.SettingsManageabilityAttribute(global::System.Configuration.SettingsManageability.Roaming)]
public string SortColumnName {
get {
return ((string)(this["SortColumnName"]));
}
set {
this["SortColumnName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Configuration.SettingsProviderAttribute(typeof(chc.servicemanagertray.PortableSettingsProvider))]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Ascending")]
[global::System.Configuration.SettingsManageabilityAttribute(global::System.Configuration.SettingsManageability.Roaming)]
public global::System.Windows.Forms.SortOrder SortOrder {
get {
return ((global::System.Windows.Forms.SortOrder)(this["SortOrder"]));
}
set {
this["SortOrder"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Configuration.SettingsProviderAttribute(typeof(chc.servicemanagertray.PortableSettingsProvider))]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Normal")]
[global::System.Configuration.SettingsManageabilityAttribute(global::System.Configuration.SettingsManageability.Roaming)]
public global::System.Windows.Forms.FormWindowState FormWindowState {
get {
return ((global::System.Windows.Forms.FormWindowState)(this["FormWindowState"]));
}
set {
this["FormWindowState"] = value;
}
}
}
}
| 50.510204 | 159 | 0.647071 | [
"MIT"
] | BlueGreenWorld/service-manager-tray-for-windows | ServiceManagerTray/Properties/Settings.Designer.cs | 4,952 | C# |
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using ExportExtensionCommon;
using System.IO;
using System.Net.Sockets;
using System.Net.Security;
namespace CaptureCenter.EmailExport
{
public class EmailExportConnectionTestHandler : ConnectionTestHandler
{
public EmailExportConnectionTestHandler(VmTestResultDialog vmTestResultDialog) : base(vmTestResultDialog)
{
TestList.Add(new TestFunctionDefinition()
{ Name = "Try to reach Server (ping)", Function = TestFunction_Ping, ContinueOnError = true });
//TestList.Add(new TestFunctionDefinition()
// { Name = "Try to say EHLO", Function = TestFunction_ehlo, ContinueOnError = true });
TestList.Add(new TestFunctionDefinition()
{ Name = "Try to send test email", Function = TestFunction_TestEmail });
}
#region The test fucntions
private bool TestFunction_Ping(ref string errorMsg)
{
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(((EmailExportViewModel_CT)CallingViewModel).Servername);
if (reply.Status != IPStatus.Success)
{
errorMsg = "Return status = " + reply.Status.ToString();
return false;
}
return true;
}
catch (Exception e)
{
errorMsg = e.Message;
if (e.InnerException != null) errorMsg += "\n" + e.InnerException.Message;
return false;
}
}
private bool TestFunction_ehlo(ref string errorMsg)
{
EmailExportViewModel_CT viewModel_CT = CallingViewModel as EmailExportViewModel_CT;
try
{
using (TcpClient client = new TcpClient())
{
string server = viewModel_CT.Servername;
int port = viewModel_CT.Portnumber;
client.Connect(server, port);
// As GMail requires SSL we should use SslStream
// If your SMTP server doesn't support SSL you can
// work directly with the underlying stream
using (var stream = client.GetStream())
using (var sslStream = new SslStream(stream))
{
sslStream.AuthenticateAsClient(server);
using (var writer = new StreamWriter(sslStream))
using (var reader = new StreamReader(sslStream))
{
writer.WriteLine("EHLO " + server);
writer.Flush();
Console.WriteLine(reader.ReadLine());
// GMail responds with: 220 mx.google.com ESMTP
}
}
}
}
catch (Exception e)
{
errorMsg = "Could not EHLO. \n" + e.Message;
if (e.InnerException != null)
errorMsg += "\n" + e.InnerException.Message;
return false;
}
return true;
}
private bool TestFunction_TestEmail(ref string errorMsg)
{
EmailExportViewModel_CT viewModel_CT = CallingViewModel as EmailExportViewModel_CT;
try
{
IEmailExportClient client = viewModel_CT.GetClient();
client.SendEmail(
viewModel_CT.TestEmailAddress, new List<string>() { viewModel_CT.TestEmailAddress },
null, null, "OCC Email Export Selftest", "Hello World!", null, null
);
return true;
}
catch (Exception e)
{
errorMsg = "Could not send test email\n" + e.Message;
if (e.InnerException != null)
errorMsg += "\n" + e.InnerException.Message;
return false;
}
}
#endregion
}
}
| 39.45283 | 113 | 0.517695 | [
"Apache-2.0"
] | JohannesSchacht/ExportExtension_Email | CaptureCenter.EmailExport.Adapter/EmailExportConnectionTestHandler.cs | 4,184 | C# |
using System;
using System.Reflection;
using System.Runtime.Loader;
using Xunit;
namespace McMaster.NETCore.Plugins.Tests
{
public class PrivateDependencyTests
{
[Fact]
public void EachContextHasPrivateVersions()
{
var json9context = PluginLoader.CreateFromConfigFile(TestResources.GetTestProjectAssembly("JsonNet9"));
var json10context = PluginLoader.CreateFromConfigFile(TestResources.GetTestProjectAssembly("JsonNet10"));
var json11context = PluginLoader.CreateFromConfigFile(TestResources.GetTestProjectAssembly("JsonNet11"));
// Load newest first to prove we can load older assemblies later into the same process
var json11 = GetJson(json11context);
var json10 = GetJson(json10context);
var json9 = GetJson(json9context);
Assert.Equal(new Version("9.0.0.0"), json9.GetName().Version);
Assert.Equal(new Version("10.0.0.0"), json10.GetName().Version);
Assert.Equal(new Version("11.0.0.0"), json11.GetName().Version);
// types from each context have unique identities
Assert.NotEqual(
json11.GetType("Newtonsoft.Json.JsonConvert", throwOnError: true),
json10.GetType("Newtonsoft.Json.JsonConvert", throwOnError: true));
Assert.NotEqual(
json10.GetType("Newtonsoft.Json.JsonConvert", throwOnError: true),
json9.GetType("Newtonsoft.Json.JsonConvert", throwOnError: true));
}
private Assembly GetJson(PluginLoader loader)
=> loader.LoadAssembly(new AssemblyName("Newtonsoft.Json"));
}
}
| 42.871795 | 117 | 0.665072 | [
"Apache-2.0"
] | BernMcCarty/DotNetCorePlugins | test/Plugins.Tests/PrivateDependencyTests.cs | 1,674 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.